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
Related
I have a web app and a batch pool.
In the batch pool, created tasks are using the same database as the web app.
Today I started receiving the following exception in the batch:
A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
The code base has not changed, older versions do not work, there were no updates, it just popped out of the blue. I repeated a couple tasks in a controlled debug environment in VS and they went through without any exceptions thrown. I went in and added the batch node’s IP to the sql server firewall rules, also no result. Meanwhile, the web application uses the database just fine.
Both the web app and batch pool are located in East US.
Here’s a snippet from Program.cs in my batch task:
MyEntities db; //MyEntities extends DbContext
System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder connstr = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder();
connstr.ProviderConnectionString = connectionString;
connstr.Provider = "System.Data.SqlClient";
connstr.Metadata = "res://*/MyEntities.csdl|res://*/MyEntities.ssdl|res://*/MyEntities.msl";
try {
db = new PepeEntities(connstr.ConnectionString);
}
The connection string looks like this:
Persist Security Info=True; Data Source=<host>; Initial Catalog=<database name>; Integrated Security=False; User ID=<login>; Password=<password>; MultipleActiveResultSets=True; Connect Timeout=30; Encrypt=True;
Edit:
This problem has subsided the same way it appeared: out of the blue. I’ll carry out tests whenever it surfaces again.
You can try one of these 2 possibilities:
1. Enabling an Execution Strategy:
public class MyEntitiesConfiguration : DbConfiguration
{
public MyEntitiesConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
}
}
# please view more details here:https://msdn.microsoft.com/en-US/data/dn456835
2. if you have explicitly opened the connection, ensure that you close it. You can use an using statement:
using(var db = new PepeEntities(connstr.ConnectionString){
..do your work
}
https://blogs.msdn.microsoft.com/appfabriccat/2010/12/10/sql-azure-and-entity-framework-connection-fault-handling/
I'm working on an ASP.NET site and I am trying to write to a local instance of a SQL Server 2012. The server is (localdb)\MyInstance. The database is "cms".
In my root web.config file, I have added the connection settings:
<configuration>
<connectionStrings>
<add
name="myDBConnection"
connectionString="Server=(localdb)\MyInstance;Database=cms;User ID=sa;password=local;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In the contact.aspx.cs file, I am using this to test the connection:
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["myDBConnection"].ToString());
connection.Open();
if ((connection.State & ConnectionState.Open) > 0) {
Response.Write("Connection OK!");
connection.Close();
} else {
Response.Write("No Connection!");
}
But, each time I test, I get "No connection" error. I'm not sure what I'm missing here. I've gone over the settings based on this post: ASP.NET Contact Form - output to email and access database. I also test using this code snippet: http://www.aubrett.com/InformationTechnology/SQL/TestSQLConnection.aspx
I suspect there is something not correct about the format of the connection string in the web.config file and have tried various formats from http://www.connectionstrings.com/sqlconnection/
but nothing seems to work.
Does anyone know what I'm missing here?
I have decided to start programming in ASP.NET MVC using C#
I have been following tutorials and implementing them into my own project.
What happens is that once i click Debug in Chrome/Firefox etc my database connection closes (the red cross appears)! (But when I refresh it manually it has the tick - till that point) I have a feeling it's to do with the connectionString in web.config. I don't like connection strings, to me they seem full of jargon. How many parameters do you REALLY need for a test project?
<connectionStrings>
<add name="PetsDBEntities" connectionString="metadata=res://*/MainDBModel.csdl|res://*/MainDBModel.ssdl|res://*/MainDBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Unfortunately my knowledge of c#/asp.net mvc is VERY limited, hence following a tutorial but I know you guys at SO are really good at what you do.
The database named PetsDBEntities has the following properties.
Data Source: Microsoft SQL Server Database File (SQL Client)
Database File Name: projects/app_data/PetsDB.mdf
If i right click the database and click >Modify Connection and then click test connection I get a "This connection cannot be tested because the specified database file does not exist"
This is where the code breaks. NOTE: The values being submitted are passed through, it just seems that it is unable to connect and add the row to the database.
if (ModelState.IsValid)
{
using( var db = new PetsDBEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var regUser = db.Users.Create();
regUser.Email = user.Email;
regUser.Password = encrpPass;
regUser.PasswordSalt = crypto.Salt;
regUser.UserID = Guid.NewGuid();
db.Users.Add(regUser);
db.SaveChanges(); //--------THIS IS WHERE I GET AN ERROR---------
return RedirectToAction("Index", "Pictures");
}
}
else
{
ModelState.AddModelError("", "Login Data is incorrect!");
}
return View();
Hopefully this is enough information for you guys to spot where the problem is.
Thansk for anyone that can help! Again, I am new and not entirely sure what information is completely needed.
Your issue is likely with the db filename.
attachdbfilename=|DataDirectory|E:\Visual Studio 2013\Projects\Pets\Pets\App_Data\PetsDB.mdf;
Should be:
attachdbfilename=|DataDirectory|\PetsDB.mdf;
Maybe this can help?
A simple connection string for SQL Server could be Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
You mentioned that when you click on test connection, you are getting an error. Your question title might be misleading, as i can assume that you didn't established the connection at all.
Can you go to "Server Explorer" -> "Data Connections" -> "Add Connection" -> "Microsoft SQL Server Database File", i assume you are using the .mdf file directly instead of connecting to SQL server?
Click on "Test Connection" and if everything goes well, you can retrieve the connectionstring from the properties.
I'm using the entity framework in a winforms application.
When i set scsb.DataSource ="localhost" every thing works fine but when i try to connect to onother DB server i got an exception:
"The underlying provider failed on Open."
public DistributionSSEntities1 Connection()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = "192.168.1.100";
scsb.InitialCatalog = "DistributionSS";
scsb.IntegratedSecurity = true;
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata ="res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DistributionSSEntities1 db = new DistributionSSEntities1(builder.ToString());
return db;
}
Has the remote Sql been setup to allow remote connections? Has the remote Sql been allowed access through the windows firewall... there's so many reasons why it wouldn't connect.
You're using Integrated Security - which may work great for a local Sql; but the network user that your WinForm app is running under must have the correct rights to access the remote box.
I'd suggest to start eliminating possibilities do the following:
Check the Sql logs on the target server. That always has the exact reason why an attemp failed - not the watered down version you get through the exception. (eg. C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\Log)
Connect to it using a sql username password - not integrated security to make sure it's not that
Firewall
EDIT
It's important to remember that the error messages return to the client regarding login attempt failures are purposefully obscure or without information - to limit an attacker gaining enough information to improve the attack (see the technet article for proof). So checking the Sql Server logs is a necessity - if your login/connection attempt actually made it to the server.
From Article:
To increase security, the error message that is returned to the client
deliberately hides the nature of the authentication error. However, in
the SQL Server error log, a corresponding error contains an error
state that maps to an authentication failure condition. Compare the
error state to the following list to determine the reason for the
login failure.
public DistributionSSEntities Connection()
{
string ConString = "SERVER=192.168.1.100;DATABASE=DistributionSS;UID=sa;PASSWORD=125;";
SqlConnectionStringBuilder SCB= new SqlConnectionStringBuilder(ConString);
//------------------------
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata = "res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = SCB.ConnectionString;
DistributionSSEntities db = new DistributionSSEntities(builder.ToString());
return db;
}
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.