How to use configuration application block of enterprise library? - c#

I have a list of activity code and full name which is placed in web.config file.
But now they are increased to a large number. So I want to remove that from config file and to create a db and access it with help of configuration application block.
Any ideas would be helpful.

You have to add a App.Config file.
Add the connectionstring to the configuration
<configuration>
<connectionStrings>
<add name="connectionstringname"
connectionString="server=localhost;user id=your_bd_userid;Password=your_db_password;database=your_db_name"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
Your form code goes here
public void LoadActivityData
{
string cnString = ConfigurationManager.ConnectionStrings["connectionstringname"].ConnectionString;
MySqlConnection myConn = new MySqlConnection(cnString);
DataSet dsActivity = new DataSet();
string selectStr = "SELECT * FROM YourActivityTable";
MySqlDataAdapter adapter = new MySqlDataAdapter(selectStr, myConn);
adapter.Fill(dsActivity, "Activities");
grdView1.DataSource = dsActivity;
}
Use System.Configuration namespace to get the configurationmanager class.

Related

Using a connection string in a app.config file in a .cs file

I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}

windows service not add data to database after release

I`m new to ASP.Net and I need to create windows service for adding data to mssql database but the problem is my code is work in visual studio before release after I release its not adding data to database
string strConn = ConfigurationManager.ConnectionStrings["MyDBConfig"].ConnectionString;
SqlConnection oSqlConnection = new SqlConnection(strConn);
oSqlConnection.Open();
string insertText = #"INSERT INTO csvs(Agency,Status) VALUES ('Tst','0')";
using (var command2 = new SqlCommand(insertText, oSqlConnection))
{
command2.ExecuteNonQuery();
}
this is my app.config file
<connectionStrings>
<add name="MyDBConfig" connectionString="Data Source=.\SQLExpress;Initial Catalog=test;Integrated Security=True"/>
</connectionStrings>

Autocomplete textbox in C# for windows application

when i run this code this error comes..
object reference not set to an instance of an object.
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT NAME FROM CUSTOMER", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
MyCollection.Add(reader.GetString(0));
}
txtcname.AutoCompleteCustomSource = MyCollection;
con.Close();
}
Make sure your connection string in web.config something like
<connectionStrings>
<add name="ConString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Problem : i'm sure that you didn't declare the connection string in your config file under <ConnectionStrings> section.
OR
you might have declared it with some defferent Key name but not ConString.
Solution: you should declare the proper Connection String with Name ConString in your config file under <ConnectionStrings> section.
Make sure that your config file either App.Config or web.config has ConnectionString similar to following:
<connectionStrings>
<add name="ConString" connectionString="Data Source=ServerName;Intial Catalog=DatabaseName;UID=userID;Password=password;Integrated Security=True;" />
</connectionStrings>

binding datagrid for Wpf to a DB

I am trying bind a DataGrid for WPF to a table in MS SQL Database.
1) First I created a App.config file as followsrrr
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
2) Secondly, I added a datagrid to my Form with a name grdEventLog
<Grid>
<DataGrid Name="grdEventLog"/>
</Grid>
3) then I added this code to MainWindow.xaml.cs file as follows:
using System.Data;
using System.Data.SqlClient;
using System.Web;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FillDataGrid();
}
private void FillDataGrid()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EventLog");
sda.Fill(dt);
grdEventLog.ItemsSource = dt.DefaultView;
}
}
After typing all these entries, I have the error at ConfigurationManager stating "The name does not exist in the current context"
I am trying to add reference cfgmgr32.dll to overcome this error. But it is not being accepted. Can anyone suggest to over come this error ?!
Alternative suggestion for approaching databinding in WPF is also welcome.
The problem is not in databinding itself. Seems, there is a typo either in config file, or in key used in ConnectionStrings[]. It would be useful if you post entire error with stacktrace here.
P.S. There is a typo in your config file.
It should be not
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
but
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
</connectionStrings>
See the last line.

visual web developer C# issue

So I am getting an error after the page is live and the information is trying to post.
SqlConnection conn = new SqlConnection("AddusConString");
SqlCommand cmd = new SqlCommand(sql);
int checkValue = 0;
checkValue++; //increment ID used to build parameter name
string parmName = String.Format("#Value{0}", checkValue);
SqlParameter newParameter = new SqlParameter();
newParameter.ParameterName = parmName;
// Handle TextBox value
cmd.Parameters.Add("#FName", FName.Text);
cmd.Parameters.Add("#LName", LName.Text);
It Highlights the
SqlConnection conn = new SqlConnection("AddusConString");
Saying "Format of the initialization string does not conform to specification starting at index0"
This is the code that I have for my web.config page
<configuration>
<connectionStrings>
<add name="AddusConString" connectionString="Data Source=localhost;Initial Catalog=AddusWebsite;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
</system.web>
You're using a string containing the value "AddusConString" rather than the value from the Web.Config. To get the value from the connection string section of the web.config you need to use the ConfigurationManager class.
Try:
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["AddusConString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
You have a few problems.
First, you must reference the connection string from web.Config through code similar to the following:
string myConnectionString = ConfigurationManager.ConnectionStrings["AddusConString"].ConnectionString;
SqlConnection conn = new SqlConnection(myConnectionString);
Second, there's nothing that associates the SqlCommand with the SqlConnection you've created, thusly:
SqlCommand cmd = new SqlCommand(sql, conn);
Lastly, and perhaps it was simply omitted for the purposes of the example, there's no code to indicate the query is ever going to be fired, such as:
cmd.ExecuteNonQuery(); //assuming the query is an Insert.
Your code doesnt recognise "AddusConstring" just like that.
Reference it so that it looks in the web.config:
string connString = ConfigurationManager.ConnectionStrings["AddusConstring"].ToString();

Categories