Wednesday, January 16, 2008

Have you ever wanted to be able to extend a sealed class like string? With Visual Studio 2008 and C# 3.0, you now can with Extension Methods. You create these new methods to add additional custom abilities to an existing type, even if you don't have access to it. These new methods need to be static methods contained in static classes, and the first parameter should be the keyword this and the hosting type. This is demonstrated in the example below on line 8. This example takes input from the console and validates it against a regex string.

   1:  using System;
   2:  using System.Text.RegularExpressions;
   3:   
   4:  namespace ExtensionMethods
   5:  {
   6:      public static class MyClass
   7:      {
   8:          public static bool ValidPhoneNumber(this string s)
   9:          {
  10:              string valid_phone = "^[\\(]{0,1}([0-9]){3}[\\)]{0,1}[ ]?([^0-1]){1}([0-9])" +
  11:                                   "{2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}$";
  12:   
  13:              Regex regex = new Regex(@valid_phone);
  14:              return regex.IsMatch(s);
  15:          }
  16:      }
  17:      
  18:      class Program
  19:      {
  20:          static void Main(string[] args)
  21:          {
  22:              Console.Write("Please Enter Phone Number: ");
  23:              string newPhone = Console.ReadLine();
  24:   
  25:              if (newPhone.ValidPhoneNumber()) 
  26:                  Console.WriteLine("Good Phone Number");
  27:              else    
  28:                  Console.WriteLine("Bad Phone Number");
  29:   
  30:              Console.ReadLine();
  31:          }
  32:      }
  33:  }

Once the class has been created, it can be used as an extension of the string class as simply as if it was originally part of the it.

Other examples can be found at the blogs for David Hayden, or Scott Guthrie.

kick it on DotNetKicks.com

posted on Wednesday, January 16, 2008 5:34:10 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Tuesday, January 15, 2008

Last week a co-worker let me know about these free E-books from Microsoft Press. It looks as if the LINQ book is in fact the full book while the other two on ASP.NET and SilverLight 1.0 are excerpts. More information can be found at the Microsoft Learning Portal.

 

MicrosoftLINQAJAXSilverlight

 

The free e-book includes content from three recent publications from Microsoft Press:

Introducing Microsoft LINQ by Paolo Pialorsi and Marco Russo (ISBN: 9780735623910)
This practical guide covers Language Integrated Query (LINQ) syntax fundamentals, LINQ to ADO.NET, and LINQ to XML. The e-book includes the entire contents of this printed book!

Introducing Microsoft ASP.NET AJAX by Dino Esposito (ISBN: 9780735624139)
Learn about the February 2007 release of ASP.NET AJAX Extensions 1.0, including an overview and the control toolkit.

Introducing Microsoft Silverlight 1.0 by Laurence Moroney (ISBN: 9780735625396)
Learn how to use Silverlight to simplify the way you implement compelling user experiences for the Web. Discover how to support an object-oriented program model with JavaScript.

kick it on DotNetKicks.com
posted on Tuesday, January 15, 2008 8:42:57 AM (Eastern Standard Time, UTC-05:00)  #    Comments [2]


 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]


 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]


 Friday, July 13, 2007

DevExpress is making Refactor for ASP.NET freely available to all ASP.NET 2.0 developers as an add-in to Visual Studio 2005 and Orcas, so if you don't have the Professional version yet, go download this free version of the product.

Included Refactorings

Add Validator
Create Overload
Encapsulate Field
Extract ContentPlaceHolder
Extract ContentPlaceHolder
Extract Method
Extract Property
Extract Style (Class)
Extract Style (id)
Extract to User Control
Flatten Conditional
Inline Temp
Introduce Constant
Introduce Local
Introduce Local (replace all)
Move Declaration Near Reference
Move Initialization to Declaration
Move Style Attributes to CSS
Move to Code-behind
Rename
Reorder Parameters
Replace Temp with Query
Reverse Conditional
Safe Rename
Simplify Expression
Split Initialization from Declaration
Split Temporary Variable
Surround with Update Panel
posted on Friday, July 13, 2007 1:58:27 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Monday, May 14, 2007

I'm not sure how I missed it, but the Internet Explorer Developer Toolbar version 1.00.2188.0 was released 5/7/2007. This is a free web page development tool by Microsoft. This is an add-on for Internet Explorer that enables the developer transverse and edit the page DOM, view object class names, match CSS selectors to page elements,  use a color picker and a pixel ruler. Other features include displaying image dimensions and table outlining.  

These tools are intended to help the developer diagnose and troubleshoot their web pages and doesn't including any script debugging at this time. I'll be adding this add-in a cool developer tool list that I have been working on.

posted on Monday, May 14, 2007 1:39:37 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]


 Sunday, February 25, 2007
 At work I decided to add Ajax 1.0 for ASP.NET to a few of my web pages. With not a lot of time to dig into it, I wanted something simple and fast to use at first. Later, I could dig into using the more sophisticated features of Ajax.  

The UpdatePanel along with the UpdateProgress control seemed to be the perfect solution. Both work just like a standard panel control that holds other web controls like a container.

These extensions are really slick, but I ran into a few issues with Response.Write

My code has a routine that spawns an java alert box to display any errors messages. This is pretty standard code and will display a small popup window to output your message. This is pretty much a standard way of displaying a quick message to the user.  Nothing very special about this, except that it doesn't work with the new Ajax extensions. smile_sad 

 

   1:  Protected Sub PopErrorWindow(ByVal ErrMsg As String) 
   2:   
   3:        Response.Write("<script language='javascript'>window.alert('" & ErrMsg & "');</script>") 
   4:   
   5:  End Sub

 

After embedding my controls within the update panel, I started getting the following error from the Response.Write in the code above. It seems that Ajax doesn't like the partial postback that I was doing.

I talked it over with a co-worker and after a bit of Internet searching and experimenting around with code, I was able to come up with the following code as a solution. Seems to work fine and I haven't found any other side effects.  smile_teeth

 

   1:  Protected Sub PopErrorWindow(ByVal ErrMsg As String)
   2:   
   3:          ScriptManager.RegisterClientScriptBlock(Me.UpdatePanel1, Me.GetType, "Alert", "alert('" + ErrMsg + "')", True)
   4:         
   5:   End Sub

 

I hope this helps anyone else out there having a similar problem.

posted on Sunday, February 25, 2007 9:39:09 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1]


 Monday, February 05, 2007

I was reading through my backlog of feeds ( which has gotten huge ) and ran across this little gem. It is a very cool feature of ASP.NET 2.0 that I had missed. In fact, I can't seem to find any reference to it in two of my ASP.NET 2.0 books. This feature is quite simple to use and extremely useful.

There are times when you may want to take your ASP.NET application offline. You may be doing a major upgrade to the code or need access to resources that may be tied up. You certainly don't want your customers seeing a "Page not Found" or some some other type of error due to upgrading code or maintenance of some sort. You want them to get a page with information on what is happening and maybe when to check back.

ASP.NET 2.0 has a special filename called app_offline.htm. This file is a standard html document and when present in the application root directory, will be shown in place of all other page requests. You can have this file on standby and when upgrade time rolls around you can simply drag the file into the application directory to be updated, update your files, and once finished you would delete the file from the directory. 

You should also note that Internet Explorer has a habit of showing "Friendly Http Errors" when the content is less than 512 bytes long. To work around this, you should either insure your page greater than 512 bytes or add some comments in the mark up to make up the difference.

The following is an example of a app_offline.htm file. The content is not limited, so you can pretty much make it say whatever you want.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Application Offline</title>
</head>
<style>
 
div {
    background-color:#ffffcc;
    padding-top:10px;
    padding-bottom:10px;
    padding-left:10px;
    padding-right:10px;
    border-style:solid;
    border-color:Black;
    border-width:1px;
}
 
</style>
<body>
    <div>
    This application is currently offline and under going maintenance. Please check back later.
    </div>
</html> 
 
This is a very simple example file. You can make yours nicely formatted with whatever graphics you require. 
 
posted on Monday, February 05, 2007 2:20:04 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0]