I am creating a WPF application and there are two databases, one is on client computer and the other one is on a remote server. And my client asks me to sync these two databases. He asked me when my WPF application connects to the internet, it should sync local data to the remote server, and if not connected to the internet, then it should save data locally.
Tell me is there a way to connect local and remote server, can WPF access two different databases on two different computers via internet
This basically boils down to using two different connection strings where you need them (either via ADO or EF or however you're accessing your data).
void doStuff() {
using (SqlConnection conn = new SqlConnection("your first connection string here"))
using (SqlCommand cmd = new SqlCommand) {
cmd.Connection = conn;
// do stuff with command
}
using (SqlConnection conn = new SqlConnection("your second connection string here"))
using (SqlCommand cmd = new SqlCommand) {
cmd.Connection = conn;
// do stuff with command
}
}
To access the remote database, you need the correct credentials, connection string, and the remote db must allow incoming connections. Your client should have details.
For a more configuration-based approach, you might do something like this:
<connectionStrings>
<add name="LocalConnection" connectionString="your first connection string here" />
<add name="RemoteConnection" connectionString="your second connection string here" />
</connectionStrings>
and use it like so:
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString;
Or wire those up to your entity framework/ORM classess accordingly.
Related
I am using SSIS 2019 and am able to execute SQL Command with ADO.Net Connection Manager.
I want to use OLEDB connection manager in a Script component within a Data Flow Task and I am getting the below error:
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Can someone please let me know if we can use OLEDB Connection in SSIS script component in a Data flow.
Here is code for connection strings
public override void PreExecute()
{
string conn = this.Connections.Connection.ConnectionString;
}
I am not getting build error in script C# code. But getting error at script component.
Using a Script Component
To access a connection manager within a script component, you should first specify this connection manager from the script component editor as shown in the image below:
Then, within the script component, you should use the Connections variable to access this connection manager (In this example, the connection manager assigned name is Connection):
var constr = Connections.Connection.ConnectionString;
screenshot
Executing a SQL command using C#
Next, you should use this connection string to initiate a SqlConnection object in order to use it by a SqlCommand as follows:
using(SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Write here your SQL command", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
Make sure you added a reference for using System.Data.SqlClient to use the SqlConnection and SqlCommand objects.
Important Note: If you are using SQL authentication, you should re-add the password to the connection string since it will not be retrieved from the connection manager for security reasons.
Using a Script Task
You should first retrieve the OLE DB connection string from the connection manager using the following command:
string constr = Dts.Connections["OledbCM"].ConnectionString;
Demonstration
I added Messagebox.Show(constr) command to the script task to show how the connection string looks like once retrieved:
Helpful Links:
SSIS Script Task : ConnectionString for ADO.Net & OleDb ConnectionManager
Check OLDEDB database Connection using script task in SSIS
Update 1: SqlConnection vs. OleDbConnection
Since you are using SqlConnection class which represents a connection to a SQL Server database. You will encounter the following error while trying to use the connection string retrieved from an OleDb Connection:
Keyword not supported "Provider"
The main reason is that the OleDB connection requires that the connection string contains the provider information since it has the ability to connect to different providers such as Oracle, Excel, Access, SQL. While SqlConnection class does not support this information since it is only using the SQL Server Native client provider.
How to solve this issue?
You can simply use a System.Data.OleDb.OleDbConnectionStringBuilder object to remove this part using the following code:
string con = Dts.Connections["OledbCM"].ConnectionString;
var connBldr = new OleDbConnectionStringBuilder(con);
connBldr.Remove("Provider");
con = connBldr.ConnectionString;
Or you can use Linq: (Remember to add the System.Linq namespace)
string con = Dts.Connections["OledbCM"].ConnectionString;
con = string.Join(";", con.Split(';').Where(c =>
!c.TrimStart().StartsWith("Provider")));
References
How do I remove "Provider=..." from a connection string
I am trying to learn how to build a web service with WCF in .Net framework 4.5 using Visual Studio 2019, and I am trying to connect my service to a database already created which I want to do operation on through that web service, my exact question is: how to open a connection between the two things using SQlConnection class?, beacause I saw the constructors of the SqlConnection but I could't understand where can we write the address/Path of our database?
It may be a little bit stupid question, but I need a better explanasion than the one that exists on the Microsoft web site.
Here is my code, which describes a void method that creates the connection string. and then we call it every time we creat a connection.
Note: DataSource is the server address, IntitialCatalog is the database name
private void ConnectToDB(string datasource, string initialcatalog)
{
SqlConnectionStringBiulder ConnectionStringBuilder = new SqlConnectionStringBuilder()
{
DataSource = datasource,
InitialCatalog = initialcatalog,
IntegratedSecurity = true
};
SqlConnection connection = new SqlConnection(ConnectionStringBuilder.ToString());
SqlCommand command = connection.CreateCommand();
}
Obviously we can add the other available attributes to the connection string, and modify them as we want.
I got some rather strange sql database connection issue.
We have a VM that is hosted on azure and installed sql server on it.
Randomly it throws
could not open a connection to SQL Server(53)
However, the exception was not thrown fromconn.Open(), but from the place I read the Sql Data reader. The problem will last like 5-10 minutes and then disappear for every long time (e.g. days).
using (SqlConnection conn = new SqlConnection(this.ConnStr))
{
conn.Open();
InsrumentName insrument = new InsrumentName();
using (SqlCommand cmd = new SqlCommand("WF_CHART_GETNAME", conn))
{
SqlParameter para = new SqlParameter("#code", SqlDbType.VarChar, 500);
para.Value = code;
cmd.Parameters.Add(para);
cmd.CommandType = CommandType.StoredProcedure;
var reader = cmd.ExecuteReader();
while (reader.Read()) --------------- Could not open a connection to SQL Server 53 thrown here
{
Do something
}
return insrument;
}
}
I had a look of the VM and sql server log, but couldn't find anything remotely close. Anyone gets some idea?
When a pooled connection is reused, the connection error won't be raised until a query is executed on the connection. Open just returns an unused connection from the pool.
Error 53 (gleaned from the command NET HELPMSG 53) is "The network path was not found." That suggests a name resolution error which seems to be intermittent in your case.
Next time this happens, try to PING the server from the client using the same name as specified in the connection string.
I would like to connect to an instance of SQL server over the network (or VPN) using Windows integrated security.
What steps exactly are necessary for me to accomplish this?
I am using Winforms.
You need to provide a connection string from a config file and use this to create an SQL connection; a typical example for integrated security might be:
Persist Security Info=False;
User ID=frosty;Password=flakes;
Initial Catalog=milkjug;
Data Source=supermarket
Integrated Security=True;
provider=System.Data.SqlClient;
Where 'supermarket' is your fully qualified database name (or IP address); this can also include port numbers.
In your code a block like the following:
SqlClient.SqlConnection myConnection = New SqlClient.SqlConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
The above is not tested and is from memory - should do the trick or at least point you in the right direction.
I have an application (WinForms) which using SQL Server as its database.
Now I am using app.config file to access ConnectionString.
Have a look at my app.config file
<configuration>
<connectionStrings>
<add name="dbConnectionString"
connectionString="Data Source=abc-79f1f531c9f;Initial Catalog=ItemStockInParth;Integrated Security=True;Pooling=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
You can see that Data Source=abc-79f1f531c9f.
Here ==> abc-79f1f531c9f is server name which is running on my (Developer's) PC.
Now when application is being installed at client's site, the server name should be changed to the server name which is running on the client machine or server name which will client machine use.
Then what should be the best criteria for handling this situation?
Means I have to create one new form which asking user to enter their Server Name and as per that I creating our ConnectionString?
Or dynamically getting the servername?
Or just hard-code the Server Name of client machine (or server name which will client machine use) inside our App.config file?
please help.....
You will probably want to provide a place where the user can enter the name of the server, or if you are clever, provide a list of available servers on the network (for example by using the code referenced by #user350374). Then you can generate an appropriate connection string as you need it using the SqlConnectionStringBuilder class:
var builder = new SqlConnectionStringBuilder();
builder.DataSource = ##SERVER NAME FROM USER##
builder.InitialCatalog = "ItemStockInParth";
builder.IntegratedSecurity = true;
builder.Pooling = false;
string connectionString = builder.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// use the connection here for your code
con.Close();
}
This would take the place of requesting the connection string from your configuration class, i.e., where you would normally say ConfigurationManager.ConnectionStrings['dbConnectionString'].ConnectionString.
Since you can programmatically read the list of connectionstrings defined in the app.config, I suggest you create a list of connection strings and ask the user which one to use:
foreach(ConnectionStringSettings setting in ConfigurationManager.ConnectionStrings)
{
...
}
It's better than to ask for the server name, as you can give a nice name to a connectionstring entry.
Is this what you are looking for
http://krishnapyrmca.wordpress.com/2010/11/23/get-sql-server-name-using-c/
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
<add key="Connectionstring" value="Data Source=.;
AttachDbFilename=|DataDirectory|\AppData.mdf;
Initial Catalog=Appdata;Integrated Security=True"/>
Simply add this code in the app.config file and attach your database to the setup file.
It automatically takes the database from the setup file of your project.