Tuesday, January 01, 2008

Rusty - Copy

John Russell Plant

My name is John, but most of my friends refer to me as Rusty. I'm a software developer, living in Clearwater, FL since January of 2005 and currently work for a web based benefit provider company called Motivano located in Tampa, FL. There I develop code in C#, VB.NET, ASP.NET and T-SQL. I've been writing code professionally for over twenty years using a variety of different languages and in varying Industries. I have been a part of the online community since the days of FidoNet running The 19th Hole BBS.  

My Interest include coding, motorcycles, sailing and gaming on Xbox Live.  Well, that is enough about me, get back to the blog.

posted on Tuesday, January 01, 2008 6:33:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Monday, December 10, 2007

aa718325_vs08_isHere 

It has been a while since I have posted, and I am sure everyone knows by now.  Visual Studio 2008 was released to manufacturing ( RTM ) and can be downloaded by MSDN subscribers. Product demos and trail editions can also be downloaded.

posted on Monday, December 10, 2007 4:24:20 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Friday, September 28, 2007

 

posted on Friday, September 28, 2007 9:52:01 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Monday, September 10, 2007

Return of the Stored Procedure

We have seen a couple examples of how to use LINQ to SQL in the previous posts  LINQ to SQL Part 1, LINQ to SQL Part 2, and how easy it is to use. The next question now becomes, What if your company strictly uses stored procedures for all of its data accessing?  Companies today can have stored procedures number from the hundreds to the thousands. With LINQ to SQL, you can still call your stored procedures and even mix and match the type styles.

First off, if you are using SQLMETAL, you will have to add an extra parameter to your DataContext build. Here is the needed extra parameter hi-lighted in red. This will again build the needed class to enable you to access the database.

SQLMETAL /SERVER:ORCASBETA2_VSTS\SQLEXPRESS /DATABASE:NORTHWIND /CODE:NWIND.CS /SPROCS

Once we have the class built and added to our project, we can get down to work. Here is a some sample code using the Northwind database.

   1: static void TestWithAdo()
   2:        {
   3:            SqlConnection conn = new SqlConnection(Properties.Settings.Default.NorthwindConnectString);
   4:  
   5:            SqlCommand spCommand = new SqlCommand("SalesByCategory", conn);
   6:            spCommand.CommandType = CommandType.StoredProcedure;
   7:            spCommand.Parameters.Add("@CategoryName", "Seafood");
   8:            spCommand.Parameters.Add("@OrdYear", "2007");
   9:  
  10:            conn.Open();
  11:  
  12:            SqlDataReader reader = spCommand.ExecuteReader();
  13:            while (reader.Read())
  14:            {
  15:                Console.WriteLine("{0,-20}\t{1,10:c}",
  16:                            reader["ProductName"].ToString().PadRight(20, ' ').Substring(0, 20),
  17:                            reader["TotalPurchase"]);
  18:            };
  19:  
  20:            reader.Close();
  21:            conn.Close();
  22:        }

First, let's look at the standard ADO.NET way of accessing a stored procedure in .NET.  We create a SqlConnection object, followed by a SqlCommand Object. We than have to add parameters and open the connection. Finally, we need to create an SqlDataReader object before we can retrieve the first row of data from the database. Quite a few steps for each a every stored procedure we wish to call. 

Now lets take a look at LINQ to SQL 

   1: static void TestWithLinq()
   2:         {
   3:             Northwind db = new Northwind(Properties.Settings.Default.NorthwindConnectString);
   4:  
   5:             var SalesReport = db.SalesByCategory("Seafood", "2007");
   6:  
   7:             foreach (var SalesItem in SalesReport)
   8:             {
   9:                 Console.WriteLine("{0,-20}\t{1,10:c}",
  10:                         SalesItem.ProductName.PadRight(20, ' ').Substring(0, 20),
  11:                         SalesItem.TotalPurchase);
  12:             }
  13:         }

With LINQ we can really reduce most of the needed ADO.NET code down to just a line or two.  Once the Northwind object has been instantiated, we can simply call the stored procedure like any other method in the class as observed in the above code.  I don't know any programmer that uses SQL day in and out that won't be foaming at the mouth for this.

kick it on DotNetKicks.com
posted on Monday, September 10, 2007 3:48:36 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Thursday, August 30, 2007
In LINQ to SQL Part 1 I used a very simple query, almost too simple.  This time I want to take it a step up and add a few joins into the mix, and show how to handle them. Below is a standard TSQL query that will to pull the employee name and his/her territory and region from the Northwind database.  We start all selecting the four columns we want pulled and join several tables together.  Finally, we order the results by lastname and then by firstname. Nothing odd or strange here in TSQL.
 
   1: select e.lastname, e.firstname, t.territoryDescription,r.regiondescription
   2: from employees e
   3: join employeeterritories et on e.employeeid = et.employeeid 
   4: join territories t on t.territoryid = et.territoryid
   5: join region r on r.regionid = t.regionid
   6: order by lastname,firstname
 
In LINQ we once again write our code in somewhat of a reverse order. We start with the from statement and than do our joins statements , followed by the orderby and then select the four columns we want pulled into our resultset. This resultset will be a enumerable anonymous type that can be used with databinding or use with a simple foreach statement.
 
   1: var EmployeeList = from employees in nw.Employees
   2:                    join employeeTerritories in nw.EmployeeTerritories 
   3:                      on employees.EmployeeID equals employeeTerritories.EmployeeID
   4:                    join territories in nw.Territories 
   5:                      on employeeTerritories.TerritoryID equals territories.TerritoryID                               
   6:                    join region in nw.Region 
   7:                      on territories.RegionID equals region.RegionID  
   8:                    orderby employees.LastName,employees.FirstName 
   9:                    select new
  10:                    {
  11:                        employees.LastName,
  12:                        employees.FirstName,
  13:                        territories.TerritoryDescription,
  14:                        region.RegionDescription 
  15:                    };

The following code shows not only the query above, but how simple it is to loop through your resultset and display the information. Remember, when writing your code, you will get the full use of intellisense to help you.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5:  
   6: namespace ConsoleTest001
   7: {
   8:  
   9:     class Program
  10:     {
  11:         static void Main(string[] args)
  12:         {
  13:             Northwind nw = new Northwind(Properties.Settings.Default.NorthwindConnectString);
  14:  
  15:             var EmployeeList = from employees in nw.Employees
  16:                                join employeeTerritories in nw.EmployeeTerritories 
  17:                                  on employees.EmployeeID equals employeeTerritories.EmployeeID
  18:                                join territories in nw.Territories 
  19:                                  on employeeTerritories.TerritoryID equals territories.TerritoryID                               
  20:                                join region in nw.Region 
  21:                                  on territories.RegionID equals region.RegionID  
  22:                                orderby employees.LastName,employees.FirstName 
  23:                                select new
  24:                                {
  25:                                    employees.LastName,
  26:                                    employees.FirstName,
  27:                                    territories.TerritoryDescription,
  28:                                    region.RegionDescription 
  29:                                };
  30:                           
  31:             foreach(var e in EmployeeList)
  32:             {
  33:                 Console.WriteLine("{0,-10} {1,-10}\t{2}\t{3,20}", 
  34:                                     e.LastName, 
  35:                                     e.FirstName,
  36:                                     e.TerritoryDescription.PadRight(20,' ').Substring(0,20),
  37:                                     e.RegionDescription);
  38:             }
  39:  
  40:             Console.ReadLine();
  41:  
  42:         }
  43:     }
  44: }

Here is the result of of the LINQ to SQL query written out to the console.

sshot-2

 

kick it on DotNetKicks.com
posted on Thursday, August 30, 2007 2:37:15 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]


 Wednesday, August 22, 2007
An upcoming new feature of C# 3.0 and part of Visual Studio 2008 ( Orcas ) will be Automatic Properties. This feature is meant to help reduce the number of lines of code a developer has to make and improve the developer experience. Currently, when a developer creates a new class, he has to create a getter and setter for each field. This seems rather redundant when you have no initial setup logic to add, but there are very good reasons such as data binding and future assembly compatibility.  I'm sure most developers have written code similar to the following before:
 
   1: class Customer
   2: {
   3:     private string _FirstName;
   4:     private string _LastName;
   5:  
   6:     public string FirstName
   7:     {
   8:         get
   9:         {
  10:             return _FirstName;
  11:         }
  12:         set
  13:         {
  14:             _FirstName = value;
  15:         }
  16:     }
  17:     public string LastName
  18:     {
  19:         get
  20:         {
  21:             return _LastName;
  22:         }
  23:         set
  24:         {
  25:             _LastName = value;
  26:         }
  27:     }
  28: }

A pretty straight forward customer class with two properties ( FirstName, LastName ).  Now with automatic properties, the same code can be compressed down to fewer lines. When the compiler encounters code like the following, it will automate the generation of the private fields along with get and set method.  This lets the developer write fewer lines of code up front and follow good class design. Later on, if needed, the developer can put custom getter/setter code without having to recompile the consuming assembly.

   1: class Customer
   2: {
   3:     public string FirstName { get; set; }
   4:     public string LastName { get; set; }
   5: }

The last information I've heard is that this as a C# only feature. I haven't heard of anything similar for VB.NET at this time. 

posted on Wednesday, August 22, 2007 1:11:03 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Tuesday, August 21, 2007

I'm sure everyone so far has at least heard of LINQ. If you haven't, it is Microsoft's new technology for Language Integrated Querying.  LINQ is part of the upcoming 3.5 .Net Framework which will be part of Visual Studio 2008 ( codename Orcas ). LINQ will be able to query in memory objects such as Generics or datasets  in addition to external items like XML documents and SQL databases. As of this post, Visual Studio 2008 is currently in Beta 2 and available for download from Microsoft.

The flavors of LINQ include:

  • LINQ to SQL
  • LINQ to Objects
  • LINQ to  Datasets
  • LINQ  to XML

This will be a LINQ to SQL example so I will be using the standard Northwind database for this article, you will need it installed onto your machine. If you will be using the SQL Express Edition I would also recommend installing SQL Management Studio Express. It will make the management of your database much easier.

The first thing we need to do is to create a DataContext for the our Northwind database. There are two ways to do this: 1. Use SQLMETAL to create a entity class if you need to model a complete database automatically. This way is also useful if you need have a constantly changing scheme since you can have SQLMETAL run each time you build your application using the Pre-Build Event.  2. The second way is to create a DataContext via the LINQ to SQL template under 'Add new Item to Project', but I won't be going into that way in this article.

Open a command prompt and go to your project directory and type:

SQLMETAL /SERVER:ORCASBETA2_VSTS\SQLEXPRESS /DATABASE:NORTHWIND /CODE:NWIND.CS

This will generate a class file that you can add to you project by right clicking Project->Add->Existing Items and selecting the nwind.cs for the file list.  You will next need to add a reference to System.Data.Linq to your project and then your will be ready to add your code. The following code queries the customer table for all records and adds the CustomerName to a listbox on the screen.

   1: namespace Linq001
   2: {
   3:     /// <summary>
   4:     /// Interaction logic for Window1.xaml
   5:     /// </summary>
   6:     public partial class Window1 : Window
   7:     {
   8:         public Window1()
   9:         {
  10:             InitializeComponent();
  11:         }
  12:  
  13:         private void LoadButton_Click(object sender, RoutedEventArgs e)
  14:         {
  15:          
  16:             Northwind nw = new Northwind(@Properties.Settings.Default.NorthwindConnectionString );
  17:  
  18:             var CustomerList = from Customers in nw.Customers
  19:                                select Customers;   
  20:  
  21:             foreach(Customers c in CustomerList)
  22:             {
  23:                 CustomerListBox.Items.Add(c.CompanyName); 
  24:             }
  25:             
  26:         }
  27:     }
  28: }

As you can see, this process is pretty straight forward. Notice the reverse SQL statement order. The from clause comes before the select statement. The result is put into a anonymous type that can be iterated through with a for each loop and added to the listbox.

image

This a extremely simple first example. I will delve into this subject much deeper in the coming weeks.

 

kick it on DotNetKicks.com

posted on Tuesday, August 21, 2007 3:35:51 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Monday, August 20, 2007

This video was played before the keynote at TechEd 2007.  Funny Stuff.


If you have problem with the above video, you can try here.

posted on Monday, August 20, 2007 12:03:42 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]