Login function runs different between local and server - c#

Here is my check login function:
protected bool checkLoginStatus(String email, String password)
{
bool loginStatus = false;
bool status = false;
try
{
Connector.openConn();
String str = "SELECT * FROM [User]";
SqlCommand cmd = new SqlCommand(str, Connector.conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "tblUser");
//check valid
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (email == dr["Email"].ToString()
&& password == Connector.base64Decode(dr["Password"].ToString()))
{
Session["login_status"] = true;
Session["username"] = dr["Name"].ToString();
Session["userId"] = dr["UserId"].ToString();
status = true;
break;
}
}
}
catch (Exception ex)
{ }
finally {
Connector.closeConn();
}
return status;
}
And call it at my aspx page:
String email = Login1.UserName.Trim();
String password = Login1.Password.Trim();
if (checkLoginStatus(email, password))
Response.Redirect(homeSite);
else
lblFailure.Text = "Invalid!";
I ran this page at localhost successful!
When I published it to server, this function only can run if email and password correct! Other, error occured:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I tried open SQL Server 2008 Configuration Manager and enable SQL Server Browser service (Logon as:NT Authority/Local Service) but it stills error.
(note: here is connection string of openConn() at Localhost (run on SQLEXpress 2005)
connectionString="Data Source=MYLAPTOP\SQLEXPRESS;Initial Catalog=Spider_Vcms;Integrated Security=True" />
)
At server (run on SQL Server Enterprise 2008)
connectionString="Data Source=SVR;Initial Catalog=Spider_Vcms;User Id=abc;password=123456;" />
anyone have an answer for my problem :(
thanks a lot!

That's a pretty strage behaviour.
First of all, on what line is exception thrown? When calling Fill()?
Also. Was identity impersonation used previously and is still on (although I can't see direct relation here, but whatever...)?

This mybe caused by the fact that SQL Server 2005 Express Edition does not allow remote connections by default:
From http://support.microsoft.com/kb/914277
Click Start, point to Programs,
point to Microsoft SQL Server 2005,
point to Configuration Tools, and
then click SQL Server Surface Area
Configuration.
On the SQL Server 2005 Surface Area
Configuration page, click Surface
Area Configuration for Services and
Connections.
On the Surface Area Configuration
for Services and Connections page,
expand Database Engine, click Remote
Connections, click Local and remote
connections, click the appropriate
protocol to enable for your
environment, and then click Apply.
Note: Click OK when you receive the following message:
Changes to Connection Settings will
not take effect until you restart the
Database Engine service.
On the Surface Area Configuration
for Services and Connections page,
expand Database Engine, click
Service, click Stop, wait until the
MSSQLSERVER service stops, and then
click Start to restart the
MSSQLSERVER service.

Related

How to convert ASP.NET Core code to access SQL Server to work with local SQLite DB?

I've been developing my web application to work with a SQL Server database hosted on Azure. To interface with it, I've been using code similar to the following:
SqlConnection scn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand("Select page_name from Pages where page_name = #page_name", scn);
cmd.Parameters.AddWithValue("#page_name", pageName);
try
{
scn.Open();
string ret = Convert.ToString(cmd.ExecuteScalar());
scn.Close();
return ret;
}
catch (Exception er)
{
throw er;
}
finally
{
if (scn != null)
{
if (scn.State != System.Data.ConnectionState.Closed)
{
scn.Close();
}
scn.Dispose();
}
}
Now that I've realized that I can use a local SQLite database, I'm trying to switch over to that, since there is no reason for this application to need a DB server. I've put in this new connection string:
Data Source=test2.db;
But I get an error:
An unhandled exception occurred while processing the request.
ExtendedSocketException: No such device or address
System.Net.Dns.InternalGetHostByName(string hostName)
SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 35 - An internal exception was caught)
It looks like it's still trying to connect to a SQL Server. How can I make it use the local SQLite database that I put in the connection string?
I figured it out, it was way simpler than I thought it would be.
Install the NuGet package System.Data.SQLite.
Replace all of the instances of SqlConnection, SqlCommand, SqlDataAdapter, etc. with their SQLite equivalents (eg. SQLiteConnection, SQLiteCommand, SQLiteDataAdapter).
In Startup.cs, change options.UseSqlServer to options.UseSqlite.

error connection to database c#

I'm trying to connect to a database from VS2017
var str = str1.ConnectionString =
"Data Source=141.*****.199;" +
"Initial Catalog=****;" +
"User id=***;" +
"Password=****;";
using (SqlConnection conn = new SqlConnection(str))
{
try
{
conn.Open();
var text = "SELECT * FROM Users u WHERE u.Id=76769";
...
}
catch (Exception e)
{
return req.CreateResponse(HttpStatusCode.OK, e.ToString());
}
and get error
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections.
It's azure function. If I set this connection from LogicApp, then there are no errors.
Why the connection does not work from the azure-function?
can someone help. Functions refer to the database not with only ip , which are listed on the portal. They have several variants. And on the portal these addresses do not look, only through https: //resources.azure.com. And yes, you just need to specify in the firewall all valid values
I am connecting to an SQL DB from Azure Function, and I noticed a little difference in connection string that I am using.
Pls try and see if it works for you:
"Server=tcp:141.*****.199,1433;Initial Catalog=****;User ID=*****;Password=*****;"
1433 - is the default MS SQL port number.

How to use Two SqlConnection in single TransactionScope in asp.net c#

I have installed sql server 2008 R2 in two systems, from this one system act as a server and another is client.
I need to copy product from server system database to client system database
In my web.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=SERVER-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="DBConnection1" connectionString="Data Source=CLIENT-PC\SQLEXPRESS2008;Initial Catalog=POS;Integrated Security=False;User Id=sa;Password=sql2008;Connection Timeout=1;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Here My Coding
using (TransactionScope trnsScope = new TransactionScope())
{
try
{
List<Master_ProductBLL> lstProduct = new List<Master_ProductBLL>();
//My First SQL Connection For Server
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
{
connection.Open();
//Here I can get All Products from Server Database
lstProduct = Master_ProductBLL.GetMaster_ProductBLLs(DBAction.Status.Active, "");
connection.Dispose();
}
//My Second SQL Connection For Client
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString))
{
connection.Open();
//Here I have save my Server Product into Client SQL Server
foreach (Master_ProductBLL item in lstProduct)
{
item.Save(true);
}
connection.Dispose();
}
trnsScope.Complete();
trnsScope.Dispose();
}
catch (TransactionException ex)
{
trnsScope.Dispose();
throw ex;
}
}
It shows an Error like
MSDTC on server 'CLIENT-PC\SQLEXPRESS2008' is unavailable
Unable to get the address of the distributed transaction coordinator for the server, from the server. Is DTC enabled on the server?
I have google it and find the following details
go to Services. (START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES)
Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
make this service to run Automatically for solving this issue permanently
I have done the above steps both server and client.
But Still have an error
I think for two (or more) SQL servers to be transactionnaly 'synced', you have to configure network DTC as MSDTC service is in charge of a lot of stuff about transactions... (your client should use the server's one).
To do this :
type dcomcnfg in run...
open Component services | Computers
Right click "Local Computer" and go to MSDTC tab
uncheck Use a local coordinator and type in your server name (or IP)
make sure you followed the steps mentionned in
MSDTC on server 'server is unavailable
on both the client and the server.
Not really sure it'll work, but pretty sure it won't if you don't do that.
Which database you want to use create object of that database.it is simple
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString();
SqlConnection connection1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection1"].ConnectionString

Error while connecting UWP with remote SQL Server

I want to connect UWP to SQL Server Database. I used below code to do that.
private LogIn GetDetails(string UserName)
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
connectionString.DataSource = "IP,Port";
connectionString.InitialCatalog = "Database Name";
connectionString.UserID = "sa";
connectionString.Password = "Password";
var logIn = new LogIn();
try
{
using (SqlConnection conn = new SqlConnection(connectionString.ConnectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = $"SELECT * FROM Login where UserName = '{UserName}'";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
logIn.UserName = reader.GetString(0);
logIn.Password = reader.GetString(1);
logIn.Type = reader.GetString(2);
}
}
}
}
}
return logIn;
}
catch (Exception)
{
return null;
}
}
This code throws below exception
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections
So I tried to open the SQL Server database in Server Explorer of Visual Studio. It connection opened properly but If I open the Tables folder It shows
So I tried to open the SQL Server database in SQL Server Management Studio. In that, It works properly. Connection opened properly and also I can view the tables inside Tables folder.
Don't have any idea about the place of error. Maybe in Code or Server Explorer of Visual Studio or SQL Server configuration of the server computer.
Solution tried
Creating a new SQL Server Login account and log in through new the
new account
Enabled Mixed Mode using below command
ALTER LOGIN [sa] WITH PASSWORD='newpassword', CHECK_POLICY=OFF
GO
ALTER LOGIN [sa] ENABLE
GO
You need to ensure that the required networking capabilities are declared in your appx manifest. Depending on your networking setup/configuration these are the ones to check for:
<Capability Name="internetClient" />
<Capability Name="internetClientServer" />
<Capability Name="privateNetworkClientServer" />
<uap:Capability Name="enterpriseAuthentication" />
You need to enable Mixed Mode and 'sa' user for logon.
ALTER LOGIN [sa] WITH PASSWORD='newpassword', CHECK_POLICY=OFF
GO
ALTER LOGIN [sa] ENABLE
GO
Taken from here.
Set below capabilities in Package.appxmanifest
Internet (Client & Server)
Private Network (Client & Server)

Connecting to SQL Azure with ADO.NET

Hi I try to connect to a SQL AZURE DB with ADO.NET.
Here is my code:
private static string userName = "<**#********>";
private static string password = "<********>";
private static string dataSource = "<******.database.windows.net>";
private static string databaseName = "<******>";
public void Save()
{
SqlDataReader queryResultCloud;
string queryString = "select * from tblScan";
SqlConnectionStringBuilder connString2Builder;
connString2Builder = new SqlConnectionStringBuilder();
connString2Builder.DataSource = dataSource;
connString2Builder.InitialCatalog = databaseName;
connString2Builder.Encrypt = true;
connString2Builder.TrustServerCertificate = false;
connString2Builder.UserID = userName;
connString2Builder.Password = password;
using (SqlConnection connection = new SqlConnection(connString2Builder.ConnectionString))
{
SqlCommand command = new SqlCommand(queryString);
command.Connection = connection;
connection.Open();
queryResultCloud = command.ExecuteReader();
connection.Close();
}
and I get next error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Your code seems to be correct. One thing to try is to set TrustServerCertificate to true, and see if it works. Note it is recommended to set this property to false when Encrypt is set to true. But there’re reports that combination cause connection issues. I would like to suggest you to check http://www.wadewegner.com/2010/08/using-the-trustservercertificate-property-with-sql-azure-and-entity-framework/ for more information. In addition, check again if you have configured SQL Azure firewall to allow connection to your local machine. If you’re behind a proxy, it is needed to add your proxy’s IP address to the firewall exception.
Best Regards,
Ming Xu.
You're likely behind a proxy that doesn't allow outbound connections to port 1433, which is the only port you can use with SQL Azure:
The Windows Azure SQL Database service is only available with TCP port
1433. To access a SQL Database database from your computer, ensure that your firewall allows outgoing TCP communication on TCP port 1433.
I'm in this situation as well, and the most promising / challenging solution appears to be this port bridging application technique, but the solution itself is dated and needs an older version of VS than I have installed, so I'm looking at some other alternatives.

Categories