views:

83

answers:

3

How can I make the code

string connStr = ConfigurationManager.ConnectionStrings "staceys_cakesConnectionString"].ConnectionString; 

work generically and not need the staceys_cakesConnectionString? Or how can I set it somewhere else so I only have to change it one place when I change it?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace SC1.Models.DAL 
{ 
  public class CategoryDAL 
  { 
    public CategoryDAL() 
    { 
    } 
    string connStr = ConfigurationManager.ConnectionStrings["staceys_cakesConnectionString"].ConnectionString; 

    // select all 
    public DataSet Select() 
    { 
      SqlConnection sqlConnection1 = new SqlConnection(); 
      string SqlString = "select * from Categories"; 
      SqlDataAdapter da = new SqlDataAdapter(SqlString, connStr); 
      DataSet ds = new DataSet(); 
      da.Fill(ds, "Categories"); 
      return (ds); 
    } 
    // save 
    // insert 
    // update 
    // delete 

  } 
} 

Example of a page function I have how can I make this one better using your suggestion @Adam or anyone else?

   // List
    public List<page> Select()
    {
      List<page> _list = new List<page>();
      string  SqlStatement = "select * from Pages";
      SqlConnection thisConnection = new SqlConnection(connStr);
      // Open the Connection
      thisConnection.Open();

      var thisCommand = thisConnection.CreateCommand();
      thisCommand.CommandText = SqlStatement;
      SqlDataReader thisReader = thisCommand.ExecuteReader();

      while (thisReader.Read())
      {
        // Create a new instance of the Current Page Object
        page currentPage = new page();
        // Fill the instance of the Current Page Object
        currentPage.PageID = Convert.ToInt32(thisReader["PageID"]);
        currentPage.ParentID = Convert.ToInt32(thisReader["ParentID"]);
        currentPage.CategoryID = Convert.ToInt32(thisReader["CategoryID"]);
        currentPage.Name = thisReader["Name"].ToString();
        currentPage.PageHTMLContent = thisReader["PageHTMLContent"].ToString();
        currentPage.NavigationText = thisReader["NavigationText"].ToString();
        currentPage.TopMenu = Convert.ToBoolean(thisReader["TopMenu"]);
        currentPage.SubMenu = Convert.ToBoolean(thisReader["SubMenu"]);
        currentPage.DisplayOrder = Convert.ToInt32(thisReader["DisplayOrder"]);
        currentPage.Active = Convert.ToBoolean(thisReader["Active"]);
        // Add the instance of the Current Page Object to the List<>.
        _list.Add(currentPage);
      }
      // Close the Database
      thisConnection.Close();
      return _list;      

    }
A: 

Depending on your application type, put it in an app.config or web.config file. Then you can use the ConfigurationManager class to access it.

Here's a helpful link

derek
Err, that's what he's *doing*. He wants to know how to remove the requirement that he pass the same key in everywhere.
Adam Robinson
+6  A: 

Just use a constant. For that matter, just use a static property and obtain the string that way.

public static class ConnectionStrings
{
    public static string StacyesCakes 
    { 
        get 
        { 
            ConfigurationManager.ConnectionStrings[
                  "staceys_cakesConnectionString"].ConnectionString; 
        }
    }
}

That will allow you to do things like:

using(var conn = new SqlConnection(ConnectionStrings.StaceysCakes))
{
    ...
}

Or (just adapting your existing code):

public DataSet Select() 
{ 
  SqlConnection sqlConnection1 = new SqlConnection(); 
  string SqlString = "select * from Categories"; 
  SqlDataAdapter da=new SqlDataAdapter(SqlString,ConnectionStrings.StaceysCakes); 
  DataSet ds = new DataSet(); 
  da.Fill(ds, "Categories"); 
  return (ds); 
} 

(You don't need sqlConnection1; you're not using it anywhere).

Note, however, that because SqlDataAdapter implements IDisposable and you're finished with it after this code executes, you should enclose it in a using block.

I would rewrite your function to something like this:

public DataSet Select() 
{ 
  using(SqlDataAdapter da = new SqlDataAdapter(
                            "select * from Categories",
                            ConnectionStrings.StaceysCakes))
  {
      DataSet ds = new DataSet(); 
      da.Fill(ds, "Categories"); 
      return ds;
  }
}
Adam Robinson
Is there a way to put the class in the web config so I don't have to do a using every time?
Nathan Stanford
@Nathan: the using is for very different purposes.
Henk Holterman
Since it's static you would only use 1 line of code to reference it so i suggest you use the above example as it is.
Jeroen
@Nathan: `using` is for cleaning up unmanaged resources. It's not something that can be done in one place. It's something that should have been in place in your existing code
Adam Robinson
@Adam would you mind showing me how to change the Select to return a list of objects... ex:List<Category> = select * from Categories? like the the DataSet code you did. I think returning a List of Objects from a reader would be better or what would you suggest?
Nathan Stanford
@Nathan: I would agree, though you're better off investing a little bit of time in learning how to use an ORM (Linq to SQL is very easy) rather than going down this route. You'll get the sort of interface that you're looking for, and it will take care of the routine database plumbing.
Adam Robinson
Okay... I am NEW to DotNet so next step learning Linq to SQL then what after that NHibernate? or what? I am spending my day learning so today. I will stop and start the Linq to SQL study. I had read a little on it but wanted to get the basics down first so that is now next on my list. Thanks
Nathan Stanford
You were a GREAT help @Adam Robinson and other too but I really liked the change and less code it takes.
Nathan Stanford
@Nathan: LINQ to SQL and NHibernate are different tools for the same problem; while it can be useful to know both, it's not a progression. I recommended LINQ to SQL just because it's simpler than the Entity Framework but still integrated into Visual Studio.
Adam Robinson
A: 

You could save the ConnectionString on your application configuration file. The next link explains more about it.

Connection String

Mario
The OP is already doing just that.
Henk Holterman
Sorry you're right, and a static property or method seems to be the best answer.
Mario