Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

The Using statement in C#

Posted on 2016-10-24
5
Medium Priority
?
77 Views
Last Modified: 2016-10-24
To date, I've been creating a public static class for connecting to host databases, and passing back a connection object. That entails closing the connection and disposing of all the associated objects.
I recently saw code that showed a using statement; I've really only used "using" declarations at the beginning of my code.
I see all of the examples online but none show the entire code for the class. Is there someone out there who'd like to share?
If you have any tips on implementing, I'm all ears!
0
Comment
Question by:Euless_Tech
5 Comments
 
LVL 21

Assisted Solution

by:Tapan Pattanaik
Tapan Pattanaik earned 500 total points
ID: 41857643
Hi Euless,

This is the sample example.

-----------------------------------------////////////////Step 1////////////////----------------------------------------
<configuration>
  <connectionStrings>
    <add name="CharityManagement" 
    connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
  </connectionStrings>
</configuration> 

---------------------------------///////////////////Step 2/////////////////////-----------------------------------------------------

var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;

---------------------------------//////////////////Step 3////////////////--------------------------------------------
using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
  int employeeID = findEmployeeID();    
  try    
  {

            connection.Open();
            SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
            command.CommandTimeout = 5;

            command.ExecuteNonQuery();    
   } 
   catch (Exception) 
   { 
      /*Handle error*/ 
   }

}

Open in new window

0
 
LVL 14

Accepted Solution

by:
Dustin Saunders earned 1000 total points
ID: 41857649
I always use using for my SQL connections (so much less to clean up).  Here is an example of my function I use to execute inserts/updates:

        public static void WriteSQL(string sqlQuery, DataTable parameters = null)
        {
            string cs = GetConnectionString();
            using (SqlConnection _cs = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand(sqlQuery);

                PutParameters(cmd, parameters);

                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = _cs;
                _cs.Open();
                cmd.ExecuteNonQuery();
            }
        }

Open in new window


(for reference, here is PutParameters)
        public static void PutParameters(SqlCommand cmd, DataTable parameters)
        {
            if (parameters != null)
            {
                foreach (DataRow row in parameters.Rows)
                {
                    if (row[2].ToString() == "int")
                    {
                        cmd.Parameters.Add(row[0].ToString(), SqlDbType.Int).Value = Convert.ToInt32(row[1]);
                    }
                    else if (row[2].ToString() == "varchar")
                    {
                        cmd.Parameters.Add(row[0].ToString(), SqlDbType.VarChar).Value = row[1].ToString();
                    }
                }
            }
        }

Open in new window

0
 

Author Comment

by:Euless_Tech
ID: 41857674
Either one of you that responded ever nest the using statements?
0
 
LVL 20

Assisted Solution

by:Daniel Van Der Werken
Daniel Van Der Werken earned 500 total points
ID: 41857687
The key factor for the Using statement is that the class  you're coding to implements IDisposable.

While I use this a lot, there are some cases where you wouldn't want to. For example, you might need a "handle" to the object outside of the open/close operations.

Most of the time though, you want to wrap everything you can in a using statement. Here's my example with iTextSharp. Note I've wrapped all the usings and this gives me a clean process.

                    using (Document iTextDocument = new Document(PageSize.A4, 0, 0, 0, 0))
                    {
                        using (FileStream sw = new FileStream(outputPDF, FileMode.Create))
                        {
                            using (PdfWriter pdfWriter = PdfWriter.GetInstance(iTextDocument, sw))
                            {
                                using (Bitmap bitmap = new Bitmap(inputTIFF))
                                {
                                    int pageCount = bitmap.GetFrameCount(FrameDimension.Page);
                                    iTextDocument.Open();
                                    PdfContentByte contentByte = pdfWriter.DirectContent;
                                    for (int i = 0; i < pageCount; i++)
                                    {
                                        bitmap.SelectActiveFrame(FrameDimension.Page, i);
                                        iTextSharp.text.Image itextImage = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);
                                        itextImage.ScalePercent(72.0f / itextImage.DpiX * 100);
                                        itextImage.SetAbsolutePosition(0.0f, 0.0f);
                                        contentByte.AddImage(itextImage);
                                        iTextDocument.NewPage();
                                    }
                                }
                            }
                        }
                    }

Open in new window

2
 

Author Closing Comment

by:Euless_Tech
ID: 41857730
Thanks guys. Appreciate the quick response.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question