The ConnectionString property has not been initialized. How to fix it? - c#

I am using a method(GetConnectionString()) in a class(Utility.cs) as part of another method(fillDT()) in another class(Function.cs).
internal class Utility
{
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Assignment_new.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
class Functions
{
public static DataTable fillDT(string sqlstatement) //Fills the datatable with data from sqlstatement
{
string connstr = Assignment_new.Utility.GetConnectionString();
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlstatement, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Whenever I call Functions.fillDT(#"sql statement"), the error pops out saying connection string is not initialized.

Make sure you use proper config files to save your connection string. I see you are tagging this question as WinForms, so your connection string should be inside App.Config file not in Web.Config. If this a web application then you should do the opposite, keep it in Web.Config file at the top most directory.
Also, if this is a desktop application and you are using App.Config file to save your settings, make sure that file is copied to your output directory, where the executable stays (usually the same name as the executable. i.e <EXNAme>.exe.config). Otherwise when the application runs, it won't find it.

You just checked your connection string to be null. Check string.IsNullOrEmpty() to see if it's not null. Besides, you need to set breakpoint and check if the connection string value you see in your app.config actually retrieved in your code and it is correct.

Related

Retrive DataSet from WCF application

I got the result in WCF Test Client while debugging, not sure how to get dataset value in browser. am working for the first time on wcf project
IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
DataSet Permit(getPermit name);
}
[DataContract]
public class getPermit{
string name = string.Empty;
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
Service.SVC
public System.Data.DataSet Permit(getPermit name)
{
DataSet ds = new DataSet();
string connection = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString.ToString();
string cmdText = "sql Query";
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
return ds;
}
}
After deploying to IIS, I didn't got any result after passing parameter as query string
i think, i need to mention some bindings in config file to make it work.
Not sure how to configure
Any Suggestions
At first, the problem doesn’t relate to dataset. The failure of connecting the database is the issue. I suggest you check whether the connection string use the integrated security to build the connection. When we deploy the project to IIS, Application pool identity will replace the identity that running VS, thereby the database connection will be invalid.
WCF webservice hosted on IIS returns empty xml response
Second, by default DataSet could be returned properly without specifying the name, this point is different from DataTable type.
Passing an inherited "Data Contract" through WCF call?
At last, the issue has none business with binding configuration except the returned data is too large. As Akshay mentioned, returning a dataset is not a best practice of transmitting data, we had better consider List and custom the user class with DataContract.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-data-contracts
Feel free to let me know if the problem still exists.

Why won't my query execute in my code, while it executes just fine in normal sql?

I've run into a problem while making a project for school, we are supposed to import data from a .txt file to our C# database. I thought I had it figured out but my "insert" lines weren't inserting data to my tables. So, in the end, I tried to insert only 1 line with all values written in, and it still won't insert the data into the database.
I tried the "New query" option by right clicking on my table and copy-pasted the insert line from my code, and that worked just fine, so I don't know why the line in the code isn't working.
class Program
{
static void Main(string[] args)
{
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
string q;
dataConnection.Open();
q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
SqlCommand dataCommand = new SqlCommand(q, dataConnection);
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
dataConnection.Close();
}
catch { Console.WriteLine("Fail"); }
}
}
I tried pasting the executenonquery line in a try block, and it DOES write "Success" on my screen, but the insert line does NOT execute.
Check the return value of dataCommand.ExecuteNonQuery(); (integer Value) if it return -1 something went wrong (for example a transaction rollback). If 0 no rows were affected.
int return_value = dataCommand.ExecuteNonQuery();
if(return_value > 0)
//goood :)
else
//something wrong :(
EDIT:
Btw is better dispose the commands after using them like below:
string connectionString = #"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BazaPRO2.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection dataConnection = new SqlConnection(connectionString);
dataConnection.Open();
string q = "INSERT INTO Sola(SolaID,Naziv,Naslov,Kraj,Posta,Telefon,Eposta) VALUES(1,'Test','Test','Test',1000,'Test','Test')";
using(SqlCommand dataCommand = new SqlCommand(q, dataConnection))
{
try
{
dataCommand.ExecuteNonQuery();
Console.WriteLine("Success");
}
catch { Console.WriteLine("Fail"); }
}
dataConnection.Close();
EDIT2: Considering questions in the comments.
What are you saying writing |DataDirectory| is "search in the application path for that dasabase", if you're debugging your application it means that it search the dabase in the output debug folder... If you wont that you should target a database out of your appliation directory with a relative/absolute path (look AppDomain.SetData method) or copy your database in your application directory... is hard answer you without knowing your goal :)
To be more specific, before initialize your SqlConnection call the following code:
AppDomain.SetData("DataDirectory", "C:\\TEST\\");
To set your |DataDirectory| pointing at your database path.

OLEDBconnection exception: invalid argument in c#

It's my first try to to read test data for my automated test scripts from excel sheet using oledbconnection with Dapper. Whatever i do, i get invalid argument exception. I need to select the cell from column C based on the values in columns A and B. Here is the code:
class ExcelDataAccess
{
public static string TestDataFileConnection()
{
var fileName = ConfigurationManager.AppSettings[#"Path\TestData.xlsx"];
var con = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = {0}; Extended Properties='Excel 12.0 Xml;HDR=YES;'", fileName);
return con;
}
public static UserData GetTestData(int TestCaseNumber, string Key)
{
using (var connection = new OleDbConnection(TestDataFileConnection()))
{
connection.Open();
var query = string.Format("select * from [DataSet$] where [TestCaseNumber]='{0}' and [Key]='{1}'", TestCaseNumber, Key);
var value = connection.Query<UserData>(query).FirstOrDefault();
connection.Close();
return value;
}
}
}
In the UserData class I get and set public variables with the table headers.
Thanks for any help!
I'm guessing this line is the problem:
var fileName = ConfigurationManager.AppSettings[#"Path\TestData.xlsx"];
Do you really have an entry in your app.config with a key of Path\TestData.xlsx? Can you show that line of your app's .config file?
I think you may have used the wrong key. Double check your entries in the appSettings section of your app's .config file.

SQL Server CE connecting string not allowing for data insertion

OK, I've been working on this since late last night and early this morning. I am trying to insert some data into a SQL Server CE database. I am at the end of my rope.
Here is the code I am trying to implement:
public static void InsertData(string sqlStatement)
{
try
{
//string strConn = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
//string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6); // remove file:\\
//string connectionString = #"Data Source=Database1.sdf";
//string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
//string connectionString = string.Format("Data Source={0}; Persist Security Info=False;", Path.Combine(Application.StartupPath, "Database1.sdf"));
//THIS ONE ACTUALLY WORKS!!!!!!!!!!!! :
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
string connectionString = Properties.Settings.Default.Database1ConnectionString;
SqlCeConnection sqlceCon = new SqlCeConnection(connectionString);
sqlceCon.Open();
SqlCeCommand sqlCeCom = new SqlCeCommand(sqlStatement, sqlceCon);
sqlCeCom.ExecuteNonQuery();
sqlCeCom.Dispose();
sqlceCon.Close();
}
catch (Exception e)
{
}
}
You can see all of the commented connection strings to see what I have tried. The strange thing is that I can simply use the following connection string in another method (a SELECT statement, not an INSERT INTO statement) that gets a single value from the data and it works fine.
string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
I have tested the query directly and like the comment says, the static path does work so that tells me my query is good. But of course I need something relative for publishing and multi-developer development.
Most of the connection strings I have tried allow the try block to complete with no errors, but the data doesn't get inserted.
Any suggestions?
I searched my heart out before posting this question, but Simon is right about similarity. However, we're going to have a better answer here. Corak is correct. I set property to not copy, deleted copy in bin\debug folder and app wouldn't run in debug mode because it couldn't find db even though paths all point to other file location. App is looking for copy in bin\debug. Ultimately, it was working all along. I recommend someone to make a connection to the copy in bin\debug so they can test values in the Server Explorer. Thanks for your help Corak and everyone else.
/*If your solution is web application, make sure Database1.sdf location path is under the
* App_Data folder
* Web.Config <add name="LocalDB" connectionString="Data Source=|DataDirectory|\Database1.sdf"/>
*/
protected string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDB"].ToString();
}
}
/*
* or you can use try absolute path as connectionstring
* modify your directory path as PhysicalApplicationPath result
*/
public string BaseDirConnString
{
get
{
if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
{
throw new ApplicationException("...");
}
return #"Data Source=" + HttpContext.Current.Request.PhysicalApplicationPath + "VIN Decoder\\Database1.sdf";
}
}
protected SqlCeConnection SqlCeConnection
{
get
{
var connection = new SqlCeConnection(BaseDirConnString);
connection.Open();
return connection;
}
}

Retrieving image from sql table using a file path, code error

A nice chap called Darin kindly provided me with some code in order for me to retrieve an image by its file path.
However, when I attempt to execute the code, I receive a "NullReferenceException was unhandled by user code; Use the 'new' keyword to create an object instance" on the first var line.
The code can be found below:
var connectionString = ConfigurationManager.ConnectionStrings["SomeCN"].ConnectionString;
using (var cn = new SqlConnection("Data Source=STRSQL04;Initial Catalog=PDC;Integrated Security=True"))
using (var cmd = cn.CreateCommand())
{
cn.Open();
cmd.CommandText = "Select imageID from accounts where MemberID = FM00012";
cmd.Parameters.AddWithValue("FM00012",5);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
var filepath = reader.GetString(0);
Image1.ImageUrl = filepath;
}
}
}
Can someone point out the error in my ways please?
Apologies as always for asking, what I suspect are, ridiculous questions.
You don't have a connection string called "SomeCN" (or whatever you're using for real) in your app config, so when you try to access the ConnectionString.ConnectionString parameter, it throws a nullref.
Can you post the contents of your app.config, or at least the ConnectionStrings element, so we can see?
Modifying application settings on MSDN (when you try it, you'll see one of the settings types in the dropdown of the settings editor is "ConnectionString").

Categories

Resources