0

I am used to working with the SqlHelper class and so would like to modify the existing code to make use of it.

existing code

public string GetData()
 {
  string message = string.Empty;
  string conStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
  using (SqlConnection connection = new SqlConnection(conStr))
   {
     string query = "usp_getdata";
     using (SqlCommand command = new SqlCommand(query, connection))
      {
        command.CommandType = CommandType.StoredProcedure;
        command.Notification = null;
        SqlDependency dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
         {
          reader.Read();
          message = reader[0].ToString();
         }
       }
     }
    return message;
 }

The most i could do is this. How can I make this better. The basic idea is to minimize the lines of code, make use of SqlHelper, and also use dataset instead of datareader.

public string GetData()
     {
      string message = string.Empty;
      string conStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
      SqlConnection connection = new SqlConnection(conStr);
            SqlCommand cmd = (SqlCommand)SqlHelper.CreateCommand(connection, "usp_getdata");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Notification = null;
            SqlDependency dependency = new SqlDependency(cmd);
            dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            message = ds.Tables[0].Rows[0]["Message"].ToString();
        return message;
     }
sukesh
  • 2,379
  • 12
  • 56
  • 111
  • What's the point of working with the abstract `DbCommand` when you just cast it to `SqlCommand` right after? And I'd refrain from "improving" code like this if your idea of improvement is to remove proper disposal of resources and removing lines of code (and empty lines) just to keep your line count down. – Luaan Jul 28 '15 at 12:15
  • I agree but is there a way to use SqlHelper in the exisitng code – sukesh Jul 28 '15 at 13:00
  • 1
    I don't see how. Not to mention that SqlHelper is hopelessly outdated... and it wasn't really all that useful when it was new either. Just write your own helper methods if you really want to. – Luaan Jul 28 '15 at 13:05

0 Answers0