Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ADO.NET & Database » Building and consuming parameterized queries from ADO.Net to DLINQ

Building and consuming parameterized queries from ADO.Net to DLINQ

In this article, I will represent different techniques to build and make use of parameterized queries. The first way is the classical one, and I mean by that the ADO.Net technique. Then I’ll expose the second one using the new technology, namely DLINQ.

Author Rank:
Total page views :  3719
Total downloads :  62
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
Become a Sponsor


In this article, I will represent different techniques to build and make use of parameterized queries. The first way is the classical one, and I mean by that the ADO.Net technique. Then I'll expose the second one using the new technology, namely DLINQ.

First, the customers  table that will be used as data source is represented as under:


Figure 1

Say that we want to build a parameterized query that enables to select information about different customers those correspond to the country entered by the user. To do this, let's first leverage the UI.  For this reason, we create a new windows project named ParameterizedQuery. Then we add a data grid view, a group box and a combo box into the Form1 and we dispose them as follow:


Figure 2

The ADO.Net classic technique:

The data source used to leverage this example is the Customers table located in the NorthWind SQL server data base sample that is downloadable from http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&displaylang=en

After downloading and deploying the msi file, the NorthWind data base could be reached in C:\SQL Server 2000 data bases\NORTHWIND.MDF

In order to build a more secure system, we have to query data using stored procedures via SQL parameters rather than querying tables via inputs from the user input control such as a given text box  and that for the only purpose to avoid SQL injections queries.

First, let's create the stored procedure that enables querying data according to the country entered by the user via the ComboBox1 control. We can either use Visual Studio or Microsoft SQL Server to leverage that. And, indeed, this is the stored procedure core

ALTER PROCEDURE dbo.StoredProcedure1

         
        
(

             @Country nvarchar(15)

          )

         

AS

/* SET NOCOUNT ON */

SELECT     CompanyName, ContactName, ContactTitle, Address, City, PostalCode, Phone, Fax

FROM         Customers

WHERE    Country = @Country

 

RETURN

 

This is the result corresponding to the @Country = 'USA' parameterized executed query from within SQL Server.


Running [dbo].[StoredProcedure1] ( @Country = USA ).

CompanyName                              ContactName                    ContactTitle                   Address                                                      City            Region          PostalCode Phone                    Fax                     
---------------------------------------- ------------------------------ ------------------------------ ------------------------------------------------------------ --------------- --------------- ---------- ------------------------ ------------------------
Great Lakes Food Market                  Howard Snyder                  Marketing Manager              2732 Baker Blvd.                                             Eugene          OR              97403      (503) 555-7555           <NULL>                  
Hungry Coyote Import Store               Yoshi Latimer                  Sales Representative           City Center Plaza 516 Main St.                               Elgin           OR              97827      (503) 555-6874           (503) 555-2376          
Lazy K Kountry Store                     John Steel                     Marketing Manager              12 Orchestra Terrace                                         Walla Walla     WA              99362      (509) 555-7969           (509) 555-6221          
Let's Stop N Shop                        Jaime Yorres                   Owner                          87 Polk St. Suite 5                                          San Francisco   CA              94117      (415) 555-5938           <NULL>                  
Lonesome Pine Restaurant                 Fran Wilson                    Sales Manager                  89 Chiaroscuro Rd.                                           Portland        OR              97219      (503) 555-9573           (503) 555-9646          
Old World Delicatessen                   Rene Phillips                  Sales Representative           2743 Bering St.                                              Anchorage       AK              99508      (907) 555-7584           (907) 555-2880          
Rattlesnake Canyon Grocery               Paula Wilson                   Assistant Sales Representative 2817 Milton Dr.                                              Albuquerque     NM              87110      (505) 555-5939           (505) 555-3620          
Save-a-lot Markets                       Jose Pavarotti                 Sales Representative           187 Suffolk Ln.                                              Boise           ID              83720      (208) 555-8097           <NULL>                  
Split Rail Beer & Ale                    Art Braunschweiger             Sales Manager                  P.O. Box 555                                                 Lander          WY              82520      (307) 555-4680           (307) 555-6525          
The Big Cheese                           Liz Nixon                      Marketing Manager              89 Jefferson Way Suite 2                                     Portland        OR              97201      (503) 555-3612           <NULL>                  
The Cracker Box                          Liu Wong                       Marketing Assistant            55 Grizzly Peak Rd.                                          Butte           MT              59801      (406) 555-5834           (406) 555-8083          
Trail's Head Gourmet Provisioners        Helvetius Nagy                 Sales Associate                722 DaVinci Blvd.                                            Kirkland        WA              98034      (206) 555-8257           (206) 555-2174          
White Clover Markets                     Karl Jablonski                 Owner                          305 - 14th Ave. S. Suite 3B                                  Seattle         WA              98128      (206) 555-4112           (206) 555-4115          
No rows affected.
(13 row(s) returned)
@RETURN_VALUE = 0

Finished running [dbo].[StoredProcedure1].

Now, let's switch to the Form1 code behind and declare some objects:


SqlConnection
oConnection;

//The parameter used to enter data via UI input control

SqlParameter CountryParam = new SqlParameter("@Country", SqlDbType.NChar);

//The sql command  

SqlCommand cmdDataGrid = new SqlCommand("StoredProcedure1");

//The Source is the data set used as the data grid view data source

DataSet Source = new DataSet();

SqlDataAdapter oAdapter = new SqlDataAdapter();

 

And then we implement the load event handler with this code:

private void Form1_Load(object sender, EventArgs e)

{

 

//Precise that the type of the data source is a stored procedure

cmdDataGrid.CommandType = CommandType.StoredProcedure;

//This list is used to populate the combo box later

List<string> oList = new List<string>();

//The connection must be initialized

oConnection = new SqlConnection();

//The connection string could be changed to fit given needs

oConnection.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +

  @"C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';Integrated Security=True;" +

  @"Connect Timeout=30;User Instance=True";

//The try here enables to catch sql exceptions when opening the connection

try

{

    oConnection.Open();

   

    //This command is used to select all countries in the Customers data table

    SqlCommand cmdCombo = new SqlCommand("SELECT DISTINCT Country FROM Customers", oConnection);

    //The reader here is used to populate the oList

    SqlDataReader oReader = cmdCombo.ExecuteReader();

    try

    {

       while (oReader.Read())

       {

         oList.Add(oReader[0].ToString());

       }

    }

    finally { oReader.Close(); }

    //Set the data source of the data set Source as oList

    comboBox1.DataSource = oList;  

}

catch (SqlException caught)

{

    MessageBox.Show(caught.Message);

}

 

finally

{

    oConnection.Close();

}

}

After that, we implement the comboBox1 SelectedIndexChanged event handler with the following code:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

{

 

    try

    {

        //Set the connection

        cmdDataGrid.Connection = oConnection;

        //Set the sql parameter value as the selected comboBox1 text

        CountryParam.Value = comboBox1.Text;

        //Add the sql parameter to the command parameters collection

        cmdDataGrid.Parameters.Add(CountryParam);

        //Set the command of the adapter later used to fill the Source

        oAdapter.SelectCommand = cmdDataGrid;

        //Fill the Source data source used later as data source for the

        //dataGridView1

        oAdapter.Fill(Source);

        dataGridView1.DataSource = Source;

        dataGridView1.DataMember = Source.Tables[0].TableName;

    }

    finally

    {

       //As we don't need to save them in this example

       cmdDataGrid.Parameters.Clear();

    }

}

At last but not least, let's run the application and try to change the comboBox1 values.
 



Figure 3


The data grid view content changes according to the comboBox1 selected value.

 

The DLINQ new technique:

First, if System.Data.Linq doesn't appear in the namespace list then add we it, if it is not already found, then it is necessary to add a reference to System.Data.Linq. To do this, we can add a reference by right clicking the project and selecting Add reference, then by selecting System.Data.Linq in the .Net tab as bellow.

 



Figure 4


Then, we add a reference to the System.Data.Linq.Mappinq that enables us to define Entity classes  witches are a sort of proxies' objects that represent the effective tables located in the data base as the LINQ is object based and it couldn't interact directly with a relational model environment. The class that will represent the NorthWind table Customers is defined as under:

 

[Table(Name = "Customers")]

        class Customer

        {

            [Column(Name = "CustomerID", IsPrimaryKey = true)]

            public string Identifier;

            [Column(Name = "CompanyName")]

            public string CompanyName;

            [Column(Name = "ContactName")]

            public string ContactName;

            [Column(Name = "Address")]

            public string Address;

            [Column(Name = "City")]

            public string City;

            [Column(Name = "Region")]

            public string Region;

            [Column(Name = "Country")]

            public string Region;

        }

One among differences between ADO.Net and DLINQ is, in fact, that the DataContext object will replace the famous sqlConnection. And we have two ways to make use of DataContext. Simply, we can define a DataContext as follows:

DataContext oDataContext = new DataContext(
@"Data Source=STANDARD;Initial Catalog=" +
      @"C:\SQL SERVER 2000 SAMPLE DATABASES\NORTHWND.MDF';Integrated Security=True"
);

But it is worth to derive a given object form DataContext and append to it some customized members that could be helpful in our context. Indeed and according to this example, we need to deal only with the Customers table, so the new derived object should contain a method that returns the given table, namely the Customer table.

public class NorthWind : DataContext

{

        

           //Constructor

           public NorthWind():base(@"Data Source=STANDARD;Initial Catalog=" +

                             @"C:\SQL SERVER 2000 SAMPLE  DATABASES\NORTHWND.MDF';" +

                                   "Integrated Security=True")

           {

 

           }

            //Returns the Customer table from the Northwind data base

           public Table<Customer> GetCustomerTable()

           {

               return this.GetTable<Customer>();

           }

}

The rest of variables are defined within the scope of the Form1 as under:

/* The derived object from Data context

         * is used to define an instance used later

           to get the customer table*/

        NorthWind oNorthWind;

        /*The customer table variable */

        Table<Customer> Customers;

        /* This dataset will be used

            as datagrid view data source later*/

        DataSet Source;

        /*The oAdapter will be used to populate

         the data set Source*/

        SqlDataAdapter oAdapter;

        /*This command will be the result of the

          Onversion of the dlinq query into sqlcommand

          type*/

        SqlCommand oCommand;

Then we implement the Form1 load event handler as follow:

private void Form1_Load(object sender, EventArgs e)

       
{

            oAdapter = new SqlDataAdapter();

            oNorthWind = new NorthWind();

            //Custmer is set thanks to the NorthWind object method

            Customers = oNorthWind.GetCustomerTable();

            /* This query serves as data source for the

            combo box1, Distinct is used to avoid the redendance */

            var query = (from cust in Customers

                         select cust.Country).Distinct();

            //Populate the combo box

            foreach (string c in query)

            comboBox1.DataSource = query;

        }

To enable user display data according to the comboBox1 selected value, we implement the comboxBox1 selectedValueChanged event handler as bellow:

 

IQueryable<Customer> Query;

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

 

 {

  //An extention method is used here to query the Customer table

  Query = oNorthWind.GetCustomerTable().Where(cus => cus.Country == comboBox1.Text);

  /* The get GetCommand method enables to get a

  boxed command object that we have to unboxe it using "as SqlCommand" */

  oCommand = oNorthWind.GetCommand(Query) as SqlCommand;

  //The rest is easy to undersand ........

  oAdapter.SelectCommand = oCommand;

            Source = new DataSet();

            oAdapter.Fill(Source);

            dataGridView1.DataSource = Source;

            dataGridView1.DataMember = Source.Tables[0].TableName;       

           

 }

We run the application now:

Figure 5

 

 

As we expect, we obtain as same result as the first technique, that's it.

 

Good Dotneting!!!


Login to add your contents and source code to this article
 About the author
 
Bechir Bejaoui
The author holds a master degree in NTIC specialized  in software developement delivered by the high school of communication SUPCOM, he also holds a bachelor degree in finance delivered by  the  economic sciences and  management  university of Tunis "FSEGT". He's a freelance developer since 2006. Actually woking on the WPF, .Net framewok 3.5, silverlight and the other .Net new features, in addition, he is painter and sculptor.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Bejaoui.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.