my c# code throws an exception on accessing sql server - c#

i am new to c# and sql
I am creating a simple student database
I added my database created in sql server 2008.
now i have a form where the inputs are given and i have a button insert to insert the data into the database.
But when i click the button i get an exception.
this is my App.config file
`<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<connectionStrings>
<appSettings>
<add name="ConString" connectionString="Data Source=ARAVIND-HP\SQLEXPRESS; Initial Catalog=test;Integrated Security=True" providerName="System.Data.sqlClient"/>
</appSettings>
</connectionStrings>
`
The form i used is given below
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class frmNewStudent : Form
{
public frmNewStudent()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmNewStudent_Load(object sender, EventArgs e)
{
}
private void btnInsert_Click(object sender, EventArgs e)
{
DB_Access access = new DB_Access();
access.add_student(txtRegNo.Text,txtFName.Text,txtLName.Text,txtPhone.Text);
MessageBox.Show("Data added successfully");
}
}
}
now i have two classes 1.DB_access 2.DB_Connections
the code of DB_access is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace test
{
class DB_Access
{
public SqlConnection conn;
public DB_Access()
{
conn = DB_Connection.GetConnection();
}
public void add_student(string regno, string fname, string lname, string phone)
{
if(conn.State.ToString()=="Closed")
{
conn.Open();
}
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "insert into student values('"+ regno +"','"+ fname +"','"+ lname +"','"+ phone +"')";
newCmd.ExecuteNonQuery();
}
}
}
the code of DB_Connections is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace test
{
class DB_Connection
{
public static SqlConnection NewCon;
public static string ConStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection(ConStr);
return NewCon;
}
}
}
when i run this and when i click the insert button i get the following exception:
An unhandled exception of type 'System.TypeInitializationException' occurred in test.exe
Additional information: The type initializer for 'test.DB_Connection' threw an exception.
and the line 'conn = DB_Connection.GetConnection();' gets highlighted
i am not able to find the error.please help me with this

System.TypeInitializationException means that program was unable to create type DB_Connection, more precisely was unable to initialize static field ConStr.
There is incorrect using of connectionStrings section. Look at http://msdn.microsoft.com/en-us/library/ms254494.aspx.

You don't need the <appSettings> node, that part should be just:
<connectionStrings>
<add name="ConString" connectionString="Data Source=ARAVIND-HP\SQLEXPRESS; Initial Catalog=test;Integrated Security=True" providerName="System.Data.sqlClient"/>
</connectionStrings>
You will get that TypeInitializationException when the static fields of the class can't be initialized (maybe because of an exception). That ConnectionStrings["ConString"] will result in a null, so reading the .ConnectionString property gives a NullReferenceException.

Seems that problem arises because the ConStr static member can not be initialized. Are you able to access the connection string through the configuration manager at other positions in your code just for testing purposes?
Additional tip for what Hans Kesting said: Do not edit the app.config file manually unless you have to. You can very easily manage connection strings and other settings using Visual Studio - this also avoids errors.

The connectionStrings setting in the web.config has a wrong format.
If fails on this line
public static string ConStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
The content of the web.config should be
<connectionStrings>
<add name="ConString" connectionString="Data Source=ARAVIND-HP\SQLEXPRESS; Initial Catalog=test;Integrated Security=True" providerName="System.Data.sqlClient"/>
</connectionStrings>

I think the problem with connection is in your App.config file
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections> <connectionStrings> <appSettings> <add
name="ConString" connectionString="Data Source=ARAVIND-HP\SQLEXPRESS;
Initial Catalog=test;Integrated Security=True"
providerName="System.Data.sqlClient"/> </appSettings>
</connectionStrings>
You don't need tag configSections inside configuration. Delete it and below startup in configuration paste correct connectionstring. As Alexander said, look at http://msdn.microsoft.com/en-us/library/ms254494.aspx and try in this way:
"<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<clear />
<add name="ConString"
connectionString="Data Source=ARAVIND-HP\SQLEXPRESS; Initial Catalog=test; Integrated Security=True"
providerName="System.Data.sqlClient"/>
</connectionStrings>
</configuration>"`
IMHO that should be ok

Related

I need to connect C# with SQL Server database using

I need to connect C# with SQL Server database using.
My Computer Name is "LKW15480", using "SQL Server" is "LKW15480\SQLEXPRESS", DB Name is "DB1". Computer Login "Administrator"
Error is "The 'configuration' element is not declared". Please Can you help me?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>`
</startup>
<connectionString>
<add name="cn"
connectionString="DataSource=LKW15480\SQLExpress;
Initial Catalog=DB1;
User ID=Administrator;"
ProvideName="System.Data.sqlClient"/>
</connectionString>
</configuration>
I am Learning about C# and SQL. I need Connect SQL Data Base and Filtering the data between two datetime.
I believe you are using the connection String declared in web.config
You must use ConfigurationManager to access the connection strings declared in web.config. Please check the namespace of ConfigurationManager. If .dll isn't referenced, please download it.
Here's a code sample from Microsoft.
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ReadProducts();
}
static void ReadProducts()
{
var connectionString = ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString;
string queryString = "SELECT Id, ProductName FROM dbo.Products;";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
}
}
}
}

Unable to connect with database: 'The ConnectionString property has not been initialized'

I am unable to connect my database from Sql-server in Visual studio for my school project. I've tried multiple solutions that didn't work... Hopefully you can help me out!
This is my ConnectionString in my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True" />
</connectionStrings>
</configuration>
I have written my code to be able to open a connection to my database and check if the user-credentials in the login Window are right. When clicking on btnSubmit() with the right credentials (same as in the database), it should redirect to a new Window.
Only problem is that I always receive the same error at conn.Open() when running my solution:
System.InvalidOperationException: 'The ConnectionString property has not been initialized.'
This is my code for my login Window:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MyClassLibrary;
namespace SlnProject
{
/// <summary>
/// Interaction logic for Login.xaml
/// </summary>
public partial class Login : Window
{
public Login()
{
InitializeComponent();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
string connectionString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
String query = "SELECT COUNT(1) from [User] WHERE #login = login AND #password = paswoord";
SqlCommand sqlCmd = new SqlCommand(query, conn);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#login", txtName.Text);
sqlCmd.Parameters.AddWithValue("#password", txtPassword.Text);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
Main.Content = new WpfAdmin();
}
else
{
MessageBox.Show("Foute ingave. Naam of passwoord is incorrect.");
}
}
}
private void btnKlant_Click(object sender, RoutedEventArgs e)
{
Main.Navigate(new WpfGebruiker());
}
I also verified if my connection was working and there were no problems to be seen in Visual Studio.
Does someone know how to fix this problem?
Thank you in advance.
Use the following, tested with your settings.
var connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
}
Another thing to try, see if your connection string is there in the list with Data appended to the name e.g. connStringData
var settings = ConfigurationManager
.ConnectionStrings
.OfType<ConnectionStringSettings>().ToList();
for (int index = 0; index < settings.Count(); index++)
{
Console.WriteLine($"{index,-3}{settings[index].Name,-10}{settings[index].ConnectionString}");
}
Alternate, change app.config to
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="SqlServerConnection" value="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True" />
</appSettings>
</configuration>
Usage
using (var conn = new SqlConnection(ConfigurationManager.AppSettings["SqlServerConnection"]))
{
conn.Open();
Console.WriteLine("Opened");
}

Allow Specialist IP address to use My Windows Form application C#

i have a windows form application i want to allow only IP Address list to
open the connection and use my application
i editing my app.config like that
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<security>
<ipSecurity allowUnlisted="false">
<clear/>
<add ipAddress="187.20.6.4" allowed="true"/>
<add ipAddress="192.8.0.6" allowed="true"/>
<add ipAddress="172.24.0.4" allowed="true"/>
<add ipAddress="172.29.16.138" allowed="true"/>
<add ipAddress="172.23.30.82" allowed="true"/>
<add ipAddress="10.0.2.15" allowed="true"/>
</ipSecurity>
</security>
<connectionStrings>
<add name="con" connectionString="Data Source=serverip;Initial Catalog=mydatabase;Persist Security Info=True;User ID=user;Password=pass"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
but it didn't work at all it now throw an error when i run my application and i get this error
The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
my code is :-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace myprogram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con= new SqlConnection("Data Source=serverip;Initial
Catalog=mydatabase;Persist Security Info=True;User
ID=username;Password=mypassword;
SqlCommand command = new SqlCommand();
SqlDataReader DataSearch;
DataTable Dt = new DataTable();
private void Eve_Ins()
{
int val;
if (int.TryParse(textbox.Text, out val))
{
if (int.TryParse(textbox2.Text, out val))
{
if (textbox3.Text != "")
{
con.Open();
if (!string.IsNullOrEmpty(textbox4.Text))
{
command.CommandText = "my sql command";
int i = command.ExecuteNonQuery();
con.Close();
I don't think you can do this via the config-file.
I suggest you are doing this before the application is loaded. There you just need to grab the current ip address of the user. If he isn't allowed, you can just say
Environment.Exit(0);
Full code example:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// check if network is connected
if (!NetworkInterface.GetIsNetworkAvailable() || CurrentIpRestricted(GetLocalIPAddress()))
{
// Exit Code Access Denied
Environment.Exit(5);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
// you need to think about, if you want a WhiteList or a Blacklist and configure the code
private static HashSet<string> Whitelist = new HashSet<string>();
private static bool CurrentIpRestricted(string local)
{
return !Whitelist.Contains(local);
}
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
}
The code from the IP Lookup is according to https://stackoverflow.com/a/6803109/4198052.
I hope I could help you.

set SqlConnection string properly

Im encountering a problem when setting sqlconnection.
this is my Web.Config file :
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="SimpleDB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30"
providerName=".NET Framework Data Provider for SQL Server"/>
</connectionStrings>
</configuration>
So basically i want to add row "Hello" to sql table named "book" which has only one string column caled "Name" on button click , but i get error : "[Win32Exception (0x80004005): The network path was not found]" and i dont see anything wrong in sqlconnection set up.
aspx.cs file :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string InsertData(string ID){
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:/Users/FluksikartoN/Documents/SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertData("hELLO");
}
You've changed your backslashes to forward slashes. Change them back and use # to not treat them as escape characters:
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
or just pull it from app.config since you put it there as well:
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"];
Why not use Web.Config connection string
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
there is no need of specifying connection string on page when you have specified it in Web.Config
You can simply use like this in your .cs file
SqlConnection con = new SqlConnection(System.Configuration.CofigurationManager.ConnectionString["SqlConn"].ConnectionString.ToString());
I hope this will work for you.

C# Enterprise Application Datablocks error

Can someone post a "working" example of the Enterprise Application Data block, to call a SP.
All the sample code I find starts with
// Create DataBase Instance
Database db = DatabaseFactory.CreateDatabase();
But my code throws an object reference not set to an instance....
Do you have your application configuration setup correctly?
Here is a quick example on calling a stored procedure via Enterprise Library Data Access Block:
using System;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace MyTest
{
internal class Program
{
private static void Main(string[] args)
{
var database = DatabaseFactory.CreateDatabase();
var command = database.GetStoredProcCommand("SomeSP");
using (IDataReader reader = database.ExecuteReader(command))
{
while (reader.Read())
{
Console.WriteLine("X: {0} Y: {1} Z: {2}",
reader["SomeField"],
reader["AnothterField"],
reader["Enabled"]);
}
}
Console.ReadLine();
}
}
}
And the corresponding app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<connectionStrings>
<add
name="DB"
providerName="System.Data.SqlClient"
connectionString="server=(local)\SQLEXPRESS;database=YourDB;Integrated Security=true" />
</connectionStrings>
<dataConfiguration defaultDatabase="DB"/>
</configuration>
I ran into that issue when I didn't have the defaultDatabase set to a corresponding connection string.

Categories

Resources