Hi,
Can someone please help me?
I randomly get an error when running my website:
The ConnectionString property has not been initialized.
First time I run the web page it works. Second time it fails. Is this got anything to do with static methods?
This is my code in DAL layer:
ConStrings.cs
public class ConStrings
{
/// </summary>
public static string PizzaDeliveryConnectionString
{
get
{
{
// get from PL web.config
string myconnectionString = ConfigurationManager.ConnectionStrings["PizzaDeliveryConnectionString"].ConnectionString;
return myconnectionString;
}
}
}
public static SqlConnection GetPizzaDeliveryConnection()
{
return new SqlConnection(PizzaDeliveryConnectionString);
}
DLCustomer.cs
public class DLCustomer
{
static SqlConnection connString = DL.ConStrings.GetPizzaDeliveryConnection();
public static DataSet GetCustomerByPhoneNumber(string phonenumber)//static is good for returing data from db
{
DataSet ds = null;
ds = new DataSet();
try
{
using (var connection = connString)//using doesn't require connection closed
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("GetCustomerByPhoneNumber", connection))
{
cmd.Connection = connection;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@phonenumber", phonenumber);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds, "CustomersTable");
}
}
return ds;
}
}
catch (SqlException ex)
{
return ds;
}
}
BUSINESS LAYER
Customer.cs
public class Customer
{
private string phonenumber;
private DL.DLCustomer customerData;
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public String PhoneNumber
{
get
{
return this.phonenumber;
}
set
{
this.phonenumber = value;
if (this.PhoneNumber == "")
{
throw new Exception("Please provide Tel ...");
}
}
}
public Customer () // Default Constructor
{
//An instance of the Data access layer!
customerData = new DL.DLCustomer();
}
/// Function Find customer. Calls the
/// function in Data layer.
/// It returns the details of the customer using
/// customer ID via a Dataset to GUI tier.
/// </SUMMARY>
public static DataSet GetCustomerByPhoneNumber(Customer customer)
{
if (customer.phonenumber == "")
throw new Exception("Please provide phonenumber to search");
DataSet data = null;
data = DL.DLCustomer.GetCustomerByPhoneNumber(customer.phonenumber);
return data;
}
}
Presentation layer
protected void btnOrder_Click(object sender, EventArgs e)
{
Customer customer = new Customer();
//string dt = Request.Form[txtDate.UniqueID];
customer.PhoneNumber = txtPhoneNumber.Text;
// ClassLibrary1.DbFunc1.GetCustomerByPhoneNumber(customer) ;
rptCustomers.DataSource = Customer.GetCustomerByPhoneNumber(customer);
rptCustomers.DataBind();
}
web.config
<configuration>
<connectionStrings>
<add name="PizzaDeliveryConnectionString" connectionString="Data Source=mycomp;Initial Catalog=PizzaDelivery;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
No comments:
Post a Comment