I made a web service that connects to a database hosted in SQL Server 2008 R2 on my local computer, and makes some operations on it.
This is the connection string in the web service:
conn = new SqlConnection("Data Source=amir-pc\\SQLEXPRESS;User Id=sa;Password=1234; Initial Catalog=Election;Integrated Security=True");
It works well and successfully accesses the database and runs right.
Now I want to add this web service to IIS.
I successfully added it on Windows 7 to the IIS and can run it from the browser.
localhost/election_service/service.asmx
but when I tried to call a function that checks the connection, it failed, and I don't know why.
This is the function:
[WebMethod]
public string Check_conn()
{
try
{
conn.Open();
conn.Close();
return "ok";
}
catch
{
return "failed";
}
}
Is there any modification I must to do to be able to access the database?
Hi can you give more information please try change you code for know what is exception is raising.
public string dbcheck()
{
try
{
conn.Open();
conn.Close();
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
}
Hi, then .. is a login issue:Open IIS Open Application Pool Select your current application pool are you current working (by default is DefaultAppPool) Go to Advanced Options, and find Identity and change to (NT AUTHORITY\Network Service) Then you has been changed your application user, now you need to add permision to network service to database Open SQlMananger, then go to Node Security, rigth click and properties go to NT AUTHORITY\Network Service go to User mapping and add the database you want to allow access.
Related
I want to query an Azure SQL Database from an Azure Function executing on my machine in debug using Managed Identities (i.e. the identity of my user connected to Visual Studio instead of providing UserId and Password in my connection string).
I followed this tutorial on Microsoft documentation so my Azure SQL Server has an AD user as admin which allowed me to give rights (db_datareader) to an Azure AD group I created with my Azure Function Identity and my user in it (and also my Function App deployed in Azure).
If I deploy and run in Azure my Azure Function, it is able to query my database and everything is working fine. But when I run my Azure Function locally, I have the following error :
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
The code of my function is the following:
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "test")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
using (var connection = new SqlConnection(Environment.GetEnvironmentVariable("sqlConnectionString")))
{
connection.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net");
log.LogInformation($"Access token : {connection.AccessToken}");
try
{
await connection.OpenAsync();
var rows = await connection.QueryAsync<Test>("select top 10 * from TestTable");
return new OkObjectResult(rows);
}
catch (Exception e)
{
throw e;
}
}
}
The code retrieves a token correctly, the error occurs on line await connection.OpenAsync().
If I open the database in Azure Data Studio with the same user than the one connected to Visual Studio (which is member of the AD group with the rights on the database), I can connect and query the database without any issue.
Is it a known issue or am I missing something here ?
After trying your specific scenario, I tested quite a few ways to try and get it to work locally. This didn't work, giving the same error message you're getting.
I discussed it with some people, when a possible solution came up. I tested it: it works!
The main issue in my case was that my subscription (and my user) is a Microsoft account (Outlook). Because of this, you need to specify the tenantId in the GetAccessTokenAsync() call.
Apparently, for managed identities you do not have to specify the tenantId. With a user, it's a good idea to explicitly specify it. In case of a personal MS account, specifying it is mandatory.
My code (sort of):
var tokenProvider = new AzureServiceTokenProvider();
using (var connection = new SqlConnection(CONNECTIONSTRING))
using (var command = new SqlCommand(QUERY, connection))
{
connection.AccessToken = await tokenProvider.GetAccessTokenAsync("https://database.windows.net/", "<YOUR_TENANT_ID>");
await connection.OpenAsync();
var result = (await command.ExecuteScalarAsync()).ToString();
return new OkObjectResult(result);
}
This solution has been tested and works both when specifying the tenantId (or Directory ID, the tenant's GUID) and the 'onmicrosoft'-name (xxx.onmicrosoft.com).
Is your local machine's IP Address white-listed?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure
I Have strange problem when i tried to publish my asp.net mvc application to my local (pc) iis with "Always Encrypted" Enabled.
My application keep timeout when i tried to access database using EF6 at local IIS (not express) :
But if i tried to access & debug my asp.net mvc app using Visual Studio 2017, database with 'always encrypted enabled' can be accessed perfectly without timeout.
And also i can access it with SQL Management Studio without problem.
Both (SMSS & ASP.NET web config) using this configuration.
Column Encryption Setting=enabled;
Note : I'm using ASP.NET MVC 5 & EF 6, SQL Server 2016 Developer Edition.
Sorry for my bad english.
UPDATED :
I have tried using .NET Framework Data Provider to see if there's any clue that'll help me solving this issue, Using following code :
var context = new TestDevEntities();
StringBuilder sb = new StringBuilder();
string connectionString = context.Database.Connection.ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT [id],[name],[CCno] FROM [TestDev].[dbo].[testEncCol]", connection, null, SqlCommandColumnEncryptionSetting.ResultSetOnly))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
sb.Append(reader[2] + ";");
}
}
}
}
}
above code show me this error :
Now, with this kind of error i know i exactly i must do :)
Change the identity of application pool to the 'user' who previously generated the certificate.
Export currentuser cert (used by always encrypted) and import to the user that you want to use as application pool identity.
Now its worked!
EF should throw some kind of error as clear as .NET Data Providers do, instead of timeout failure that really confuse me #_#
UPDATED (1) :
Now the question is how to use it (Certificate) with default ApplicationPoolIdentity instead of custom account?
UPDATED (2) :
I have done what jakub suggest, but still no luck.
Thanks
One way (could be the only way) to use the DefaultAppPool identity instead of a custom (user) account is to store the certificate in the Local Machine certificate store (not Current User).
Once you create a certificate in the Local Machine certificate store, you need to grant DefaultAppPool access to the cert. You can do that using Microsoft Management Console (and the plugin for Local Computer certs):
Right click on the cert, select All Tasks > Manage Private Keys.
Click Add.
Set location to your computer (not your domain).
Enter IIS AppPool\DefaultAppPool as the object name.
Click OK twice.
I'm using a LocalDB database with EntityFramework on an ASP.NET MVC project.
How can I simulate a connection failure to test the following try...catch block?
try
{
if (ModelState.IsValid)
{
db.Entry(course).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save changes.");
}
I've tried trying to take the database offline in SQL management studio, but it just hangs. I can't stop the SQL service as LocalDB doesn't run as a service.
Have you tried giving it a non-existing name of LocalDB instance? Just put this in your connection string for this test:
Server=(localdb)\missing_instance`
(if you embed this connection string in code don't forget to escape the \ character :-))
connectionString="Server=(localdb)\\missing_instance;..."
You can stop a LocalDB instance even though it doesn't run as a service, you can use the SQLLocalDB.exe tool to do this:
SqlLocalDB Utility
I have surfed the web for two days looking for a better way to configure my application that I am uploading to AppFog so that it successfully connects to the mysql database in the cloud.
I have created the mysql service and I did bind it to the application. I also created tables and put some data on them using the local console ( using af tunnel mydatabase) in linux
but my apps does not seem to find the database. My application uses JDBC ... I used the database username and password and databasename given to me from the console (those funny chars in the screen) and it did not work. so I put my own credentials, still, no success...
I tried using the url that points to my application at the port given to the on the console, but still... actually, I put in the details the showed on the console to connect to the database in the cloud after deploying ... but my app seems not to find my database and its tables....
I do not know what is wrong...
please help..
MORE:
This is the code I used to try this connection:
try {
String connectionURL = "jdbc:mysql://http://someapp.aws.af.cm:10000 /OnlinePassword";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectionURL, USER, PASS);
statement = conn.createStatement();
}
Use appfog environment variable called VCAP_SERVICES to automatically detect your MySQL database credentials and connection info. You can take advantage of this to display all the info which will be in JSON format and use it to connect your app to MySQL database. You may try this.
First create a servlet and retrieve your database connection using a context attribute as follows:
public class DbInfoServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
request.setAttribute("jsonContent", java.lang.System.getenv("VCAP_SERVICES"));
request.getRequestDispatcher("/index.jsp").view.forward(request, response);
}
}
Then create a index.jsp file to display you DB connection info as follows:
<body>
<p>
<!-- Click here to display DB info -->
<!-- Display of your DB connection and credentials info is here. This will show in JSON document format
-->
<c:out value="${jsonContent}" />
</p>
</body>
Use hostname(i.e. IP), port, name(i.e. database name), username, password parameters from JSON document content to modify your JDBC connection code as follows:
try {
String connectionURL = "jdbc:mysql://hostname:3306/name";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectionURL, username, password);
statement = conn.createStatement();
}
If the above doesn't work, simply ensure that you are using the latest version of MySQL-connector-java jar file.
Have fun!
I'm building a little library that can be used to query Active Directory resources. I've tested it out before and it works as I expect it to.
The problem is I have created a brand new VMWare virtual computer with Windows Server 2003 installed, created the domain, added some dummy objects and now when I try to run the application I get the error:
"Network logon failure unknown user name or bad password".
//Example 1: Find all users in Active Directory. Be sure your LDAP connection string is correct.
string ldapConnection = #"LDAP://sergio-j9i2vccv/dc=contoso,dc=com";
string username = "Administrador"; //I'm using a spanish version of WS2003.
string password = String.Empty;
UserFinder userSearcher = new UserFinder(ldapConnection, username, password);
try
{
var users = userSearcher.FindAllUsers();
foreach (var user in users)
{
Console.WriteLine(user.Name);
Console.WriteLine(user.Path);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Facts:
My host laptop can ping my virtual server, and vice-versa.
The domain is correctly created.
The application has run correctly when testing on another VM.
My only idea is that somehow I need to give permission to the Administrator account (the one I chose to use) to query the domain.
How do I achieve this?
Or I might even create a brand new user and give that permission to query the domain.
Any suggestions? I'm sure there's an option somewhere I have to enable.
Thank you!
EDIT!
I just installed the .NET Framework 4 on the Server 2003 virtual machine and ran the application from there. It runs flawlessly.
So with that new knowledge, what could be causing this error?
I just think, that your administrator can't have an empty password. Try with a valid passowrd (respecting the password rules).
JP