windows service not add data to database after release - c#

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>

Related

how do I make my oledb program work on a different pc

Hey I'm new to programming and have never made an actual program that needs to work on another pc. The program is connected with a databank. When I'm on another pc i change program.exe.config file so that i can apply the right location of the databank but its still doesn't work. here is the code i have, maybe something is wrong here.
app.config:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
in standard code:
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb");
The first thing is that you are specifying a connection string in your application configuration file:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
You aren't using the connection string from your Program.exe.config, instead you are copying-and-pasting the connection string.
If you change your code slightly, perhaps you can see what i mean:
//Get the connection string to use
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb";
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
What you should be doing is pulling the connection string from your application's configuration:
//Get our connection string setting, and the connectionString it contains
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
String connectionString = cs.ConnectionString;
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
There is one more change that you can make. Your connection string entry itself specifies which provider you want to use:
providerName="System.Data.OleDb"
But then you go ahead and use that provider yourself:
OleDbConnection con = new OleDbConnection(...);
If you changed your connection string to use a different provider:
providerName="System.Data.SqlClient"
your code would still be using the OleDbConnection, rather than the provider given in the application configuration.
Fortunately, the .NET framework has a handy little helper function, where it can create the correct provider for you:
public static DbConnection GetConnection()
{
//Get the connection string info from our application config
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
if (cs == null)
throw new Exception("Could not find connection string settings");
//Get the factory for the given provider (e.g. "System.Data.OleDbClient")
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
if (factory == null)
throw new Exception("Could not obtain factory for provider \"" + cs.ProviderName + "\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open();
return conn;
}

Connection string in app.config

how to add this C# code connection string in app.config file for windows forms application program ?
i see examples of adding access db but i need to add excel file data , so can't find previous question on excel file connection in app.config.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
Try this in web config file-
<connectionStrings>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0'" />
<add name="ConnStrName" connectionString="Data Source=database;Initial Catalog=database-name;Persist Security Info=True;User ID=your username;Password=your password" />
</connectionStrings>
i solved this myself .
app.config settings :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MSIDConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'"
providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
added these 2 lines in Form1.cs
using System.Data.OleDb;
using System.Configuration;
in button click event :
private void button1_Click(object sender, EventArgs e)
{
string excelconn = ConfigurationManager.ConnectionStrings["MSIDConn"].ConnectionString;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = excelconn;
OleDbCommand command9 = new OleDbCommand
(
"SELECT P1, P2, P3 " +
" FROM [PE_Actual$] ", conn
);
DataSet ds9 = new DataSet();
OleDbDataAdapter adaptor9 = new OleDbDataAdapter(command9);
adaptor9.Fill(ds9, "testtable");
dataGridView1.DataSource = ds9.Tables[0].DefaultView;
}
Usually they sit in a section on their own:
<connectionStrings>
<add name="myConnectionName" providerName="myProvider" connectionString="Data Source=D:\MISD_report.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0" />
</connectionStrings>
I do not know what the providerName for OLE/ Excel is or what name to use so the provider finds the correct connection string.

Null reference exception in asp .net

we are working on a project in which we need to show places on google map. For places, we are providing latitude and longitude from database. we are facing null reference exception error in the following place:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
How to resolve this error please guide me.
Cause of Exception:-
When you say:
System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"]
Since there is no connection string with name Data Source=KhUSHAL.., thus ConnectionStrings will return null and on that you are trying to access ConnectionString property which will result in Null reference exception. Read about this error here.
Basically you are mixing both, either do this:-
string CS ="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;Integrated Security=True";
using (SqlConnection con = new SqlConnection(CS))
{
//Your code
}
Or fetch it from Web.Config(Preferred way):-
First define the connection in Web.Config:
<connectionStrings>
<add name="Test" connectionString="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then read it like this:-
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
//Your code
}
Do you have the ConnectionString in the Web.Config of the UI project?
Fix:
Copy that ConnectionString and Paste in your Web.Config
Your code,
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
is Invalid, this is not the way to declare connection string and access them.
How can we declare Connection Strings and can Access them??
No1:>In a Page
string strConnectionString="server=localhost;database=myDb;uid=myUser;password=myPass;;
Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
}
No2.>Web.Config you can declare then under configuration and appSeting
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings("myConnectionString")))
{
}
No3>Web.Config you can declare then under configuration and connectionStrings
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
}

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>

How to use configuration application block of enterprise library?

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.

Categories