C# Enterprise Application Datablocks error - c#

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.

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]));
}
}
}
}
}
}

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.

The Requested Database is not defined in the configuration

An application I am working on is using Microsoft Practices Enterprise to handle database interactions.
This was all fine and good, however at some point it simply stopped working. The only thing I can think of is that I restored the database I was working on from another database deployed on a different machine (accessed by a user(s) with different accounts than the one I am using now).
I have created 2 small tests (1 solution with 1 project having 1 class, Program.cs), the first works:
static void test1()
{
// Create a connection
SqlConnection sdwDBConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString());
// Open the connection
sdwDBConnection.Open();
// Create a String to hold the query.
string query = "SELECT * FROM [TestDB].[dbo].[Test1]";
// Create a SqlCommand object and pass the constructor the connection string and the query string.
SqlCommand queryCommand = new SqlCommand(query, sdwDBConnection);
// Use the above SqlCommand object to create a SqlDataReader object.
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
// Create a DataTable object to hold all the data returned by the query.
DataTable dataTable = new DataTable();
// Use the DataTable.Load(SqlDataReader) function to put the results of the query into a DataTable.
dataTable.Load(queryCommandReader);
// Example 1 - Print your Column Headers
String columns = string.Empty;
foreach (DataColumn column in dataTable.Columns)
{
columns += column.ColumnName + " | ";
}
Console.WriteLine(columns);
// Close the connection
sdwDBConnection.Close();
System.Console.Read();
}
Yielding:
ID1 | Value1 | Value2 | Value3 |
However the second one fails:
static void test2()
{
try
{
Database db = DatabaseFactory.CreateDatabase("Test"); //Line 59
using (DbCommand cmd = db.GetSqlStringCommand("SELECT * FROM [TestDB].[dbo].[Test1]"))
{
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
System.Console.WriteLine("{0} {1} {2}", reader.GetInt64(0)
, reader.GetString(1)
, reader.GetString(2));
}
}
}
}
catch (Exception e)
{
System.Console.WriteLine(e.Message + "\n" + e.StackTrace);
}
finally
{
System.Console.Read();
}
}
Yielding:
The requested database Test is not defined in configuration.
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.EnterpriseLibraryFactory.BuildUp[T](IReadWriteLocator locator, ILifetimeContainer
lifetimeContainer, String id, IConfigurationSource configurationSource)
at Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.EnterpriseLibraryFactory.BuildUp[T](String id, IConfigurationSource configuration
Source)
at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase(String name)
at ....Program.test2() in ...\Program.cs:line 59
This is my app.config
<?xml version="1.0"?>
<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" requirePermission="true" />
</configSections>
<dataConfiguration defaultDatabase="Test" />
<connectionStrings>
<add name="Test" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=SSPI; Connect Timeout=120" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
</configuration>
I think that if there where any connection/configuration issue the first one would fail as well. I have tried using the empty constructor as well, but that just throws another exception saying that the String parameter must not be null or empty.
Any insight on this would be appreciated.
It turns out that there is a conflict between Microsoft products. In my case, it was the ESB Toolkit installation. More information is available here.
Uninstalling the ESB Toolkit was in my case, the way to go.
If you using
Database sda = DatabaseFactory.CreateDatabase("DBConnectionString");
Make sure you have this setting in App.config
"connectionStrings
add name="DBConnectionString" connectionString="server=DBServerNameHere;database=DatabaseNameHere;Integrated Security=true;" providerName="System.Data.SqlClient"
connectionStrings"

my c# code throws an exception on accessing sql server

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

how to read the connection string from App.config file by C#

I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
This is my app.config file declaration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>
I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.
Can you please try
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
Then use the second method.
Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.
You simple define connection string in one class and call that string.....
public class Connection
{
/// <summary>
/// Connection String
/// </summary>
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
}
}
}
//Returning connction string
sqlConnection conn = new SqlConnection(Connection.ConnectionString);
connectionString=global::myProject.Properties.Settings.Default.myConnectionString

Categories

Resources