How can I get a connection string from a text file? - c#

I have developed a Windows application with the backend of SQL Server to insert employee names. I am going to insert the employee details on three databases one by one. So, I like to get connecting values from text file. Whenever I want to change the connection, I just want to enter the login details in the text file.
How can I get a connection string from a text file?

Use an app.config (MSDN) file.
Allows you to configure multiple named connection strings which you can access via the System.Configuration.ConfigurationManager class' ConnectionStrings property

Plaese try like this
using System;
using System.IO;
class Test
{
public static void Main()
{
string txtpath = #"c:\textfile.txt";
try
{
if (File.Exists(txtpath))
{
using (StreamReader sr = new StreamReader(txtpath))
{
while (sr.Peek() >= 0)
{
string ss = sr.ReadLine();
string [] txtsplit = ss.Split(';');
//now loop through array
string server=txtsplit[0].Tostring();
string userid= split[1].Tostring(); // user id
string password= split[2].Tostring(); // password
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.ToString());
}
}
}

You don’t need to use plain text file to do this. There is a special configuration file you can use and a set of classes to make your life easier.
Add configuration file to you project
Go to Add new item in the solution and select Application Configuration File
Add connection strings to the configuration file
Just copy / paste this and modify connection string and connection string name as needed
<configuration>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
<add name="Conn2" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Add System.Configuration reference to your project
Right click references, go to add new and select System.Configuration from .NET tab
Add wrapper class
This is not needed but it will make your life easier. Create a class like this so you don’t have to call configuration manager every time you need to connect to database
using System;
using System.Configuration;
using System.Text;
namespace WindowsFormsApplication4
{
class Config
{
public static string CONNECTION_STRING_1
{
get
{
return ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
}
}
public static string CONNECTION_STRING_2
{
get
{
return ConfigurationManager.ConnectionStrings["Conn2"].ConnectionString;
}
}
}
}
Use connection strings in other methods like this
SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING_1);

class Sql
{
public static string ReadCS()
{
using (var streamReader = File.OpenText("SqlSettings.txt"))//Enter FileName
{
var lines = streamReader.ReadToEnd();
return lines;
}
}
public SqlConnection con = new SqlConnection(Sql.ReadCS());
}

Related

Deleting a VPN Connection

After I disconnect from the vpn using this code System.Diagnostics.Process.Start("rasdial.exe", "My_VPN /d"); It still shows on the VPN Connection list. How can I remove it from there through my program?
If you want to delete VPN connection you need to delete file "rasphone.pbk" or section with [VPN Name] in this file. The file is INI file with extension PBK.
By default the file located in %APPDATA%\Microsoft\Network\Connections\Pbk\rasphone.pbk
After delete operation you will need to restart "explorer.exe"
You can remove it by using WMI's PS_VpnConnection class.
using System.Management; // need to add a reference to the assembly [System.Management]
public class Program
{
public static void Main()
{
const string WMIScope = "root/Microsoft/Windows/RemoteAccess/Client";
const string WMIClass = "PS_VpnConnection";
using (var cls = new ManagementClass(WMIScope, WMIClass, null))
using (var methodParams = cls.GetMethodParameters("Remove"))
{
methodParams["Name"] = new[]{"your_vpn_name"};
methodParams["Force"] = true;
cls.InvokeMethod("Remove", methodParams, null);
}
}
}

How can I retrieve a generated value from my C#-code into my web.config file?

I know, that the following code looks naive, but it should only bring to mind, what I want to achieve.
My web.config file:
<connectionStrings>
<add name="ADConnectionString" connectionString="AppData.GetConnectionString()" />
</connectionStrings>
I want to get the string from C#:
public class AppData
{
public static string GetConnectionString()
{
return "LDAP://expample.domain.com:389/DC=example,DC=domain,DC=com";
}
}
I know it is possible to get data from the web.config in the C# code (The AppSettings for example). But is the opposite also possible?
I dont think it is possible as it is just an XML file. All you can do in XML file is add comment,create nodes,add attributes or add nested elements etc etc but you cant add any code to it.
However I think there are certain languages that allow you to do so
https://stackoverflow.com/questions/24486772/write-php-code-inside-xml-file
I DO NOT recommend use it. But you actually can do something like this:
using System.Web.Configuration;
using System.Configuration;
var config = WebConfigurationManager.OpenWebConfiguration(null);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["ADConnectionString"].ConnectionString = AppData.GetConnectionString();
config.Save();
Use Reflection
Here's an example:
private string test = WebConfigurationManager.ConnectionStrings["Test"].ConnectionString; //returns "ExecuteTest" -- note! no parenthesis!
protected void Page_Load(object sender, EventArgs e)
{
MethodInfo m = this.GetType().GetMethod(test); //expects static method
if (m != null)
{
object result = m.Invoke(this, new object[] { });
}
}
private static void ExecuteTest()
{
//do stuff
}
But no, you can't edit/pull data into the web.config on the fly. Changing the web.config will cause the application to restart killing all sessions. It's possible to build the web.config prior to starting but once it's up and running it's essentially locked down.

C# change custom connection string at runtime

Bit new on EF. I'm, creating application where user selects database from computer. and now i want to change connection string to match location of the database for example : this is current connection string that points to database location somewhere on disk (C:\Users\student\Documents\TestData.md) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Documents\TestData.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now when user selects new database from disk the connection sting needs to change to location where new database is located (C:\Users\student\Desktop\NewSelectedDatabase.mdf) :
add name="test" connectionString="metadata=res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDB)\v11.0;attachdbfilename="C:\Users\student\Desktop\NewSelectedDatabase.mdf";integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
now i've created filedialog so user can select database and to get its adress . i've also changed my edmax to to recive custom connection string :
public partial class Tester : DbContext
{
public Tester()
: base("name=Test")
{
}
public Tester(string customcs)
: base(customcs)
{
}
now my problem is what do i pass to constructor as custom connection string ? i hope you understood me because i'm realy bad at english and explainig things
When you have the EF designer up, on the properties window is a connectionstring setting. Once you have everything set as you like, clear that setting to none. It rewrites the generated code to accept a connection string passed in on instantiating.
var mything= new dbcontext (connstring)
Another option would be to just create a new class (.cs) file giving it the same namespace that your Tester EF context belongs to, and paste this in there:
public partial class Tester : DbContext {
public Tester(string _connectionString) : base(ConnectionString(_connectionString)) {
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.AutoDetectChangesEnabled = false;
}
private static string ConnectionString(string _connectionString) {
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ProviderConnectionString = _connectionString;
entityBuilder.Metadata = "res://*/Models.Tester.csdl|res://*/Models.Tester.ssdl|res://*/Models.Tester.msl";
entityBuilder.Provider = "System.Data.SqlClient";
return entityBuilder.ToString();
}
}
Notice it's a partial class (just like the auto-generated ones for Tester are) -- and so you're adding to the auto-generated class made by EF (again, make sure they're in the same namespaces, so it really is an addition to the partial class, not just you off making your own little one).
This way, you're adding a new construction instantiation (that's passing a connection string) that gets modified into the right entity-connection-string builder (via the private static ConnectionString method).
var myThing = new Tester(ConfigurationManager.ConnectionStrings["db_DBName"].ToString());
I have one line in the web.config for the connection:
<add name="db_DBName" connectionString="Data Source=DBSERVER;initial Catalog=DBNAME;" providerName="System.Data.SqlClient" />
the build target defines its transformantion, and I just pass the same string into the code all the time.

Add Entity Framework Model to Class Library

I have created a class library and added a EF Model but as soon as I declare a variable my project just skip the rest of my code without any error. I do not understand what is causing this to happen.
Library Code
public class Phisc
{
//Global DB Entity variable
live_restoreEntities db = new live_restoreEntities();
//Write data to file
public void PhiscFile(int value)
{
string strFileName, strFilePath;
StreamWriter stm;
//Create a file name that will be created
strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_PHISC";
//The path that were the file will be saved
strFilePath = "c:\\" + strFileName + ".txt";
//Validate if file exists
if (!System.IO.File.Exists(strFilePath))
System.IO.File.Create(strFilePath).Dispose();
stm = new StreamWriter(strFilePath, false);
stm.Write("This is a test message from C#");
stm.Close();
}
}
WinForm Code
private void Form1_Load(object sender, EventArgs e)
{
Phisc.Phisc pFile = new Phisc.Phisc();
pFile.PhiscFile(14);
}
When I create a instance of the library it does not hit my PhiscFile Method.
I have added a breakpoint to it and it stops at this constructor
public live_restoreEntities() : base("name=live_restoreEntities", "live_restoreEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
I am using a windows application to test my library
The parameterless constructor goes out and look for the conenctionstring in the App.config file. It look next to the .exe file.
I'm guessing that you need to include your App.config (from your entity library) to your WinForms library.
In the App.config, it should look like this:
<configuration>
<connectionStrings>
<add name="live_restoreEntities"
connectionString="<your connection string here>"
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>

Data Source in connection string - Setup project

I'm creating a setup project for my C# desktop application.
What the data source should be written in the connection string for the access database ?and where I should put my database file in the solution project ?
Assuming you're using the VS setup project, you need to add the access database file as content and place it in the application directory, for example. To specify the location in the configuration file, you need to write a custom action that modifies the connection string accordingly.
The following example is an installer class that sets the connection string after install phase (not tested):
[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
public Installer1()
{
InitializeComponent();
this.AfterInstall += new InstallEventHandler(Installer1_AfterInstall);
}
void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
string sTargetDir = Context.Parameters["TargetDir"];
string sAppConfig = Path.Combine(sTargetDir, "<your app>.exe.config");
string sDBPath = Path.Combine(sTargetDir, "<your db>.mdb");
XDocument doc = XDocument.Load(sAppConfig);
var elem = doc.Root.Element("/configuration/connectionStrings/add[#name='<your connection name>']");
string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", sDBPath);
elem.SetAttributeValue("connectionString", connectionString);
doc.Save(sAppConfig);
}
}
Alternatively, you can use Wix which has the XmlFile utility in the util extension which does it for you without you writing a custom action.

Categories

Resources