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"
Related
i make a service based database , every time i try to insert data , it seems the application works fine , but when i reload the database and want to see the data it show this messages "This database cannot be imported. It is either an unsupported SQL Server version or an unsupported database compatibility." and the data not updated, i dont know how to fix this , already search some solution from SO but still not get it ..
if you need some details , you can ask in comment *because i dont know what to put in this
EDIT :
App.conf
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="Database1Entities1" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="TravelokaCMR.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
how i insert data
Database1Entities1 db = new Database1Entities1();
foreach (string files in filesindirectory)
{
string name = Path.GetFileName(files);
string subname = name.Substring(10, 8);
DateTime subTime = DateTime.ParseExact(subname, "yyyyMMdd", null);
TimeSpan span = otime2.Subtract(subTime);
if (span.Days < 2)
{
// Console.WriteLine(files);
foreach (string subfiles in Directory.GetFiles(files))
{
xlWb = xlApp.Workbooks.Open(subfiles);
xlWs = xlWb.Sheets[1];
xlRange = xlWs.UsedRange;
rowFile = xlRange.Rows.Count;
colFile = xlRange.Columns.Count;
dataFile = new string[rowFile][];
for (int i = 0; i < dataFile.Length; i++)
{
dataFile[i] = new string[colFile];
}
for (int i = 0; i < rowFile; i++)
{
try
{
dataFile[i][0] = xlWs.Cells[i + 1, 1].value2.ToString();
//MessageBox.Show(dataMapping[i][j]);
}
catch (Exception ee)
{
dataFile[i][0] = "";
}
}
for (int i = 0; i < rowFile; i++)
{
CMRTable cmr = new CMRTable();
items = dataFile[i][0].Split(';');
cmr.Merchant_name = items[1];
cmr.Sett_date = items[2];
cmr.Proc_date = items[3];
cmr.Mid = items[4];
cmr.cardtype = items[5];
cmr.Trx_date = items[6];
cmr.Jam_trx = items[7];
cmr.Auth = items[8];
cmr.Cardno = items[9];
cmr.Trx_type = items[10];
cmr.amount = items[11];
cmr.rate = items[12];
cmr.disc_amt = items[13];
cmr.tenor_ins = items[14];
cmr.rate_ins = items[15];
cmr.disc_ins = items[16];
cmr.net_amt = items[17];
cmr.purchase_id = items[18];
cmr.merchant_descriptor = items[19];
db.AddToCMRTables(cmr);
db.SaveChanges();
}
After a chat, following was found.
In looking at your connection string, it seems like the path to your mdf is not correct. Please look into replacing the |DataDirectory|\ with actual path and retry the process.
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=**|DataDirectory|**\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="Database1Entities1" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=**|DataDirectory|**\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="TravelokaCMR.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=**|DataDirectory|**\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
NOTE: Each of your connection string points to Database1.mdf. Not sure if thats intentional.
I created a project in my laptop and it was working fine.
I transferred my project to another laptop and now it gives me a System.NullReferenceException error.
Somehow, the database doesn't establishes, it gives a NULL exception.
My code:
public partial class registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// error is here
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["registerationConnectionString"].ConnectionString);
conn.Open();
string chekuser = "select count(*) from userdata where uname='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(chekuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already Exist: ");
}
conn.Close();
}
}
}
WEB.CONFIG
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
You don't have any connection string at web.config file with name = registerationConnectionString thus ConfigurationManager.ConnectionStrings["registerationConnectionString"] gives us null value and then when we want to get ConnectionString of null, it gives us System.NullReferenceException. You can resolve this by adding following portion in web.config.
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=YourServerName;
Initial Catalog=YourDatabaseName;
Persist Security Info=True;
User ID=yourUserId;
Password=yourPassword" />
</connectionStrings>
Since the error is occuring on this line:
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings
["registerationConnectionString"]
.ConnectionString);
You should assume that the ConfigurationManager.ConnectionStrings is null, and look for your configuration file that was probably not correctly copied over. When you attempt the .ConnectionString from the index accessor of the .ConfigurationManager.ConnectionStrings it returns null as you have not configured one in your web.config. Look in web.config for the connectionStrings portion.
Update
Since you have provided the web.config simply add the connectionStrings as desired:
<configuration>
<connectionStrings>
<add name="registerationConnectionString"
connectionString="Data Source=.;Initial Catalog=DBNAME;Integrated Security=True;Connect Timeout=15;" />
</connectionStrings>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
</configuration>
I m getting this code when i want to interact with database.
my web.config contains a connection string that is:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<add name="WebNewYearConnectionString" connectionString="Data Source=XXXX; Initial Catalog=XXXXX; User ID=XXXXX; Password=XXXXXX;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<customErrors mode="Off"/>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0"/>
<add name="Microsoft SQL Server Compact Edition Client Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact Edition Client 4.0" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
and my code contains
xSqlConnections con = new SqlConnections("System.Configuration.ConfigurationManager.ConnectionStrings["WebNewYearConnectionString"].ConnectionString");
protected void Page_Load(object sender, EventArgs e)
{
string Clientname = Request.QueryString["name"];
string str = "select * from Client_Detail where Client_Name='" + Clientname + "'";
DataTable dat;
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds, "tab");
DataTable dat = new DataTable();
dat = ds.Tables["tab"];
EventName.Text = dat.Rows[0]["Event_Name"].ToString();
Event_Description.Text = dat.Rows[0]["Description"].ToString();
Event_Date.Text = dat.Rows[0]["Date"].ToString();
Entry_Fee.Text = dat.Rows[0]["Price"].ToString();
Event_Client.Text = dat.Rows[0]["Client_Name"].ToString();
Event_Location.Text = dat.Rows[0]["Event_Location"].ToString();
Session["Event_Name"] = EventName.Text;
}
and my code is giving this error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
in
da.Fill(ds, "tab");
this line
xSqlConnections con = new SqlConnections("System.Configuration.ConfigurationManager.ConnectionStrings["WebNewYearConnectionString"].ConnectionString");
protected void Page_Load(object sender, EventArgs e)
{
con.open();
string Clientname = Request.QueryString["name"];
string str = "select * from Client_Detail where Client_Name='" + Clientname + "'";
DataTable dat;
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
da.Fill(ds, "tab");
DataTable dat = new DataTable();
dat = ds.Tables["tab"];
EventName.Text = dat.Rows[0]["Event_Name"].ToString();
Event_Description.Text = dat.Rows[0]["Description"].ToString();
Event_Date.Text = dat.Rows[0]["Date"].ToString();
Entry_Fee.Text = dat.Rows[0]["Price"].ToString();
Event_Client.Text = dat.Rows[0]["Client_Name"].ToString();
Event_Location.Text = dat.Rows[0]["Event_Location"].ToString();
Session["Event_Name"] = EventName.Text;
con.Close();
}
* EDIT *
If this has resolved the issue, you need to double check your connection string as it isn't resolving correctly.
An easy way to do this is to go to Server Explorer in VS Studio and manually add a connection to your Database. Test the connection to see if it resolves. If it does, you can copy the connection string from the properties tab for the data connection.
Hope this helps.
Are there actually quotes around the whole thing in your code? If so then that is your problem.
xSqlConnections con = new SqlConnections("System.Configuration.ConfigurationManager.ConnectionStrings["WebNewYearConnectionString"].ConnectionString");
^
Change your connection instance like this:
xSqlConnections con = new SqlConnections(System.Configuration.ConfigurationManager.ConnectionStrings["WebNewYearConnectionString"].ConnectionString);
I created a new database (AC_2012) on my localhost in SQL Server 2008 Management Studio.
I'm trying to connect it via connection string in web.config in Visual Studio 2010 Premium. It won't pick it up.
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="AC_2012"
connectionString="server=.\SQLEXPRESS;database=AC_2012; integrated security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
And here's how I'm trying to call the connection string.. yes it isn't finished..
public static void storedProcedure(string[] paramName, string[] paramValue, string sproc)
{
SqlConnection conn = null;
SqlDataReader reader = null;
try
{
string connStr = ConfigurationManager.ConnectionStrings["AC_2012"].ConnectionString;
conn = new SqlConnection(connStr);
reader = new SqlDataReader();
DataTable dt = new DataTable();
conn.Open();
SqlCommand cmd = new SqlCommand(sproc, conn);
for (int x = 0; x < paramName.Count(); x++)
{
cmd.Parameters.Add(new SqlParameter(paramName[x], paramValue[x]));
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
}
}
catch (Exception e)
...
Database names with an underscore _ need to be delimited with square braces [].
Try
connectionString="server=.\SQLEXPRESS;database=[AC_2012]; integrated security=True; "
Alternatively, just don't put an underscore in your database name.
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.