c# student registration system help linked to a SQL database - c#

Please help with this coding error? I am new to C# and SQL and need some fast help.
This is the code I have already, the problem comes when I debug it throws an error when I get to
string ConnectionString = ConfigurationManager
.ConnectionStrings["Student1"]
.ConnectionString;
The error message is
null reference exception was unhandled.
No matter what I do I can't seem to fix this error. Any ideas?
static class Program
public static SqlConnection GetConnection
{
get
{
string ConnectionString = ConfigurationManager
.ConnectionStrings["Student1"]
.ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
return con;
}
}

You must verify that you have connection string in your configuration file
<configuration>
<connectionStrings>
<add name="Student1"
connectionString="...."
providerName="...." />
</connectionStrings>
....

In addition to the other answer(s) it might be worth pointing out why you get this error.
Basically your code here:
string ConnectionString = ConfigurationManager.ConnectionStrings["Student1"].ConnectionString;
Is trying to access the ConfigurationManager.ConnectionStrings collection, the indexer for this collection returns a NULL if no value is found (some other collections will raise an index out of range exception)
It is likely the value is NULL because you are missing the connection string from your app.config - but since you aren't checking to see if the connection string object returned by the indexer is null and you are trying to use it's value, a null reference exception is thrown
A good check would be:
var conn = ConfigurationManager.ConnectionStrings["Student1"];
if(conn == null) throw new Exception("No connection string in config file"); // etc
string ConnectionString = conn.ConnectionString;
This way you could throw a more meaningful exception if the connection string was absent

Related

Error when trying to open() sql server

I am new to net developing and have managed to work my way through a lot of questions I have had just by looking through the forums.
It appears that the issue that I am having is something that a number of others have had I have found that they are all different and just haven't for the life of me been able to work through it.
I am trying to insert player registration details into database but when I try to invoke the wcf server it am met with the exception type on my conn.Open():
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.
In addition I am using the build it sql server and the connection string used is one from properties on the database.
I am not too sure how to proceed.
public string playerRegistration(playerDetails playerInfo)
{
string Message;
using (SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"))
{
conn.Open();
using (var cmd = new SqlCommand("INSERT into Player(pid, pfname, plname, pphone, paddress, pdob) VALUES (#pid, #pfname, #plname, #pphone, #paddress, #pdob)", conn))
{
cmd.Parameters.AddWithValue("#pid", playerInfo.Pid);
cmd.Parameters.AddWithValue("#pfname", playerInfo.Pfname);
cmd.Parameters.AddWithValue("#plname", playerInfo.Plname);
cmd.Parameters.AddWithValue("#pphone", playerInfo.Pphone);
cmd.Parameters.AddWithValue("#paddress", playerInfo.Paddress);
cmd.Parameters.AddWithValue("#pdob", playerInfo.Pdob);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
Message = " Details inserted successfully";
}
else
{
Message = " Details not inserted successfully";
}
conn.Close();
return Message;
}
}
}
Make sure to use #".." (a verbatim string literal) with connection strings to avoid simple escaping mistakes.
The code shown with "..\v.." contains a vertical tab escape which produces an invalid connection string. There is no compiler error because the string literal is syntactically valid although the resulting string is incorrect.
Recommended fix with a verbatim string literal and elimination of double slashes:
#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\Users\Daniel.."
Alternative fix (note the \\v):
"Data Source=(LocalDB)\\v11.0;AttachDbFilename=c:\\Users\\Daniel.."
The problem is in your connection string
"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\\Users\\Daniel\\documents\\visual studio 2013\\Projects\\Prac4\\WebApplication1\\App_Data\\ADODatabase.mdf;Integrated Security=True"
Search the internet to find the required format for SQL Server. You do not need an MDF file name, here's a helpful link:
https://www.connectionstrings.com/sql-server/

how to write connectionstring in web.config file

My code works well but after trying to host it. Its database always response with the null value . I failed to host it. and now when i try to debug in my PC its also have the same problem of null response.
my class file and its scalar query code.
public Object ExecuteScalarQuery(String sp)
{
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
// string _ConnString = ConfigurationManager.ConnectionStrings["rfid"].ConnectionString;
SqlConnection myConnection = new SqlConnection(_ConnString);
SqlCommand cmd = new SqlCommand(sp, myConnection);
Object result = 0;
try
{
myConnection.Open();
result = cmd.ExecuteScalar();
}
catch (Exception ex)
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
finally
{
//if (myConnection.State == ConnectionState.Open)
// myConnection.Close();
}
return result;
}
And web.config file having connectionstring
<connectionStrings>
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True " providerName="System.Data.SqlClient"/>
while doing step by step debugging its connectionstring look like this which is not being working.
"Data Source=CHINTAN-PC\\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True "
One thing to check is that results are being returned by your stored procedure. I copied your code, made a table and a stored procedure to query all records from it, and it returned null when the table was empty and the value of the first column of the first row when I added a couple records.
add the property 'pooling'.
<add name="rfid" connectionString="Data Source=CHINTAN-PC\SQLEXPRESS;Initial Catalog=msdb;Integrated Security=True; pooling=false;" providerName="System.Data.SqlClient"/>
go to server explorer, select you data base. in the right pane(Properties) copy connection string and paste it. if that doesn't work. go to sql management studio. its your windows authentication and sql authentication problem. make a new sql authentication login and give userid="" and password="" like "sa" and "sa123" in the connection string.
Use toString to retrieve the string value
String _ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["rfid"].ConnectionString.toString();

Database connection simplified - Is this right?

I'm trying to teach myself c#, and have found various examples on connecting to a MSSQL database. What I've done seems to be the simplest way to do it, but still seems overly complicated.
Is there a better way?
here's my code:
static void dbcon()
{
List<int> familyID = new List<int>();
String connString = "Server=[myServer]\\[myInstance];Database=[dbName];User Id=[userID};Password=[password];";
using (var sqlconn = new SqlConnection(connString))
{
using (var cmd = sqlconn.CreateCommand())
{
try
{
sqlconn.Open();
cmd.CommandText = "SELECT id FROM family";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
familyID.Add(Convert.ToInt32(reader["id"].ToString()));
}
}
foreach (int tempy in familyID)
{
Console.WriteLine("id: " + tempy);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
This is fine for an app that only runs one sql statement, but you wouldn't want to use all that code every time you wanted new data.
What you want to do is separate the code that creates the connection, from the code that gets and runs the sql, from the code that deals with the results.
This way, the connection code (and possibly the data display code) can be written once and called each time you want to execute different sql, and you only have to concentrate on how to write the code that gets the data you want.
hth
Details: First of all welcome to Stackoverflow. Just a few tips below
Having your connection string hard coded like that is bad practice. You should ALWAYS have it in your App.config (or Web.config if it is a web application). The reason is because if you have it hard coded and your boss ask you to change the Applications Database connection string you will need to recompile the entire application. If you have it in a App.config file you just need to change it (open it up with notepad) and save it.
Example on how to add it to the app.config
<configuration>
<connectionStrings>
<add name="myConnectionString"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB;
Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then to access it in your code (You will need to add a reference to System.Configuration as well as add using System.Configuration;)
string connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
In regards to your other code I would change your exception catching to include the Sql Exception first and then fall back to any other exceptions.
catch (SqlException ex)
{
// Handle the Sql Exception code
}
catch (Exception ex)
{
// Handle the Normal Exception code
}
The example contained in the docs for SqlConnectionStringBuilder is quite easy to follow and understand as an alternative way.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
Edit:
Actually, the example I copied above shows you how the SqlConnectionStringBuilder class handles an "...invalid value in a safe manner". Whoops. At least it gives you an idea of how it works.
For more info on the various methods of obtaining, storing and constructing your connection string within ADO.NET, look at the MSDN documentation on Connection Strings

How to validate ConnectionString exists and if not do not throw error

The connection name 'MySqlServer' was not found in the applications configuration or the connection string is empty.
So, I have a page with a panel that will display when the connection in the web config is found and the connection is valid; using a try/catch as long as the add name"VALUE" is in the config connection strings if the server data is bad the page will load and the panel is set to invisible... I need to be able to handle the following...
If the named value in this case MySqlServer is used in the aspx; aspx.cs but not found in the config I do not want the error to occur; connection name was not found.... I just want to not show the panel like when the SqlConnection.Open fails when the name is found but data is bad...
aspx
<asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource"
ConnectionString="<%$ ConnectionStrings:MySqlServer %>"
aspx.cs
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand();
try
{
SqlConnection.Open();
config
<connectionStrings>
<add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
</connectionStrings>
You can try :
if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...
If you're using .NET 4.5+ and have access to C# 6.0, you can make use of the null conditional operator (?) to try and get the connection string without automatically throwing an exception:
string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------
if (string.IsNullOrWhiteSpace(connectionString))
{
// Don't even bother trying to open the connection.
// Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
//return;
//throw;
}
// If your code has made it this far, it means you have a valid connection string. Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (var sqlCommand = new SqlCommand)
{
// Do stuff.
}
}
You can check if there are any connections strings by using count.
var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
//There is at least more then one connection string.
}
Update
public static class Extension
{
public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
try
{
return value[key].ConnectionString.Length > 0;
}catch
{
return false;
}
}
}
You can use the extension as follow.
if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
//If true you know there is a valid connectionstring.
}

How To Work With SQL Database Added As Item In Visual Studio 2008?

If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)

Categories