Jan 17 2008

101 LINQ Samples

Category: C# 3.0Bil@l @ 09:33

Here is a very interesting link on LINQ!

http://msdn2.microsoft.com/en-us/vcsharp/aa336746.aspx

 

Regards

Tags:

Aug 14 2007

Extension Methods in C# 3.0 and ASP.NET Code-Inline

Category: C# 3.0 | LinqBil@l @ 00:14

I was customizing a ListView today to show a small key gif beside each article listed to indicate that the article requires a login to be viewed based on whether the user is authenticated or not. So I decided to use inline checking to see if the current user is logged in or not and accordingly show/hide the Image. The code is like this:

                <asp:Image runat="server" ID="imgKey" ImageUrl="~/Images/key.gif" AlternateText="Requires login"
                    Visible='<%# (bool)Eval("OnlyForMembers") && !Page.IsAuthenticated() %>' />

Notice the Page.IsAuthenticated() method. I have added this as an extension method that targets the Page class as follows:

        /// <summary>
        /// A Method that returns whether the user checkin the webpage
        /// is currently authenticated or not.
        /// </summary> 
        /// <param name="page">A <see cref="System.Web.UI.Page"/> instance</param>
        /// <returns>A <see cref="System.Boolean"/> that specifies whether the user is currently authenticated or not</returns>
        public static bool IsAuthenticated(this System.Web.UI.Page page)
        {
            HttpContext context = HttpContext.Current;

            if (context.User != null && context.User.Identity != null && !String.IsNullOrEmpty(context.User.Identity.Name))
            {
                return true;
            }

            return false;
        }

When using this extension method inside the code-behind, you should import the class library that holds the class that adds an extension method. What I discovered today was that, even if you had imported the class library in the code behind, if you want to use any extension method inside the HTML you should add another import to the page header using the Import tag.

Hope this helps,
Regards

Tags: ,

Aug 7 2007

Extend System.Web.HttpResponse with a WriteLine method

Category: C# 3.0Bil@l @ 11:50

While working with Console applications, you always use Console.WriteLine. I always got bothered why the HttpResponse has only Write or WriteFile. Why can't we have WriteLine? Many times you need to print something on a web page and also print a break line, and you always had to append a "<br>".

Now, with the Extension Methods that ship as part of C# 3.0, we can add the WriteLine method as follows. Create a new Class Library and place this code inside it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.CodeDom;
using System.Reflection;
using System.IO;

namespace Utils
{
    public static class CodeSuiteExtensionMethods
    {
        #region HttpResponse Extension Methods
        /// <summary>
        /// This method prints the contents of a string s followed
        /// by a new line.
        /// </summary>
        /// <param name="response">An <see cref="System.Web.HttpResponse" object/></param>
        /// <param name="s">A <see cref="=System.String"/> to be printed</param>
        public static void WriteLine(this System.Web.HttpResponse response, string s)
        {
            // Call default Write method
            System.Web.HttpContext.Current.Response.Write(s);
           
            // Add a new line
            System.Web.HttpContext.Current.Response.Write("<br>");
        }
        /// <summary>
        /// This method prints the contents of a character ch followed
        /// by a new line.
        /// </summary>
        /// <param name="response">An <see cref="System.Web.HttpResponse" object/></param>
        /// <param name="ch">A <see cref="=System.char"/> to be printed</param>
        public static void WriteLine(this System.Web.HttpResponse response, char ch)
        {
            // Call default Write method
            System.Web.HttpContext.Current.Response.Write(ch);
           
            // Add a new line
            System.Web.HttpContext.Current.Response.Write("<br>");
        }
        /// <summary>
        /// This method prints the contents of a buffer of characters followed
        /// by a new line.
        /// </summary>
        /// <param name="response">An <see cref="System.Web.HttpResponse" object/></param>
        /// <param name="buffer">An array of characters</param>
        /// <param name="index">An <see cref="System.Integer"/> to start printing from</param>
        /// <param name="count">An <see cref="=System.Integer"/> that states number of characters to print</param>
        /// <param name="s">A <see cref="=System.String" to be printed/></param>
        public static void WriteLine(this System.Web.HttpResponse response, char[] buffer, int index, int count)
        {
            // Call default Write method
            System.Web.HttpContext.Current.Response.Write(buffer, index, count);
           
            // Add a new line
            System.Web.HttpContext.Current.Response.Write("<br>");
        }
        /// <summary>
        /// This method prints the ToString of an object obj followed
        /// by a new line.
        /// </summary>
        /// <param name="response">An <see cref="System.Web.HttpResponse" object/></param>
        /// <param name="obj">A <see cref="=System.Object"/> to be printed</param>
        public static void WriteLine(this System.Web.HttpResponse response, object obj)
        {
            // Call default Write method
            System.Web.HttpContext.Current.Response.Write(obj);
           
            // Add a new line
            System.Web.HttpContext.Current.Response.Write("<br>");
        }
        #endregion
    }
}

I have create Extension Methods for all the overloads of the Write method. What I do is simply call the original Write method, then add another call to write a break line.

How to use it? Add this namespace to your current page:

using Utils; // name of the namespace containing the extension methods.

Before importing the namespace make sure you Add a Reference to that namespace.

Now, in your code you can do something:

Response.WriteLine("Hello world"); // This will print the statement Hello world with a break line!!

Even if you wanted to use the Response.WriteLine same as Console.WriteLine to customize it with parameters, you can do something as:

Response.WriteLine(string.Format("Hello {0}", "Bilal"));

 

Hope this helps,
Regards

 

Tags:

Aug 1 2007

LEFT OUTER JOIN in LINQ To SQL

Category: C# 3.0 | DLinq | LinqBil@l @ 11:06

I was practicing a little bit on using Linq to Sql, and had this scenario:

Customers and Orders tables in Northwind Database. I added a new customer with no records, I wanted to apply a left outer join to get customers whose CustomerID starts with letter B such that, even if the Customer had no record in the Orders table, I wanted his/record to be present in the result.

The easiest way to go is to use LEFT OUTER JOIN between Customers' table and Orders' table so that I get all Customers that pass the filter expression and even have no records in the Order table, here is the Query Expression:

        NorthwindDataContext db= new NorthwindDataContext();
        var query=  from c in db.Customers
                    where c.CustomerID.StartsWith("B")
                    join o in db.Orders on c.CustomerID equals o.CustomerID into sr
                    from x in sr.DefaultIfEmpty()
                    select new {CustomerID= c.CustomerID, ContactName=c.ContactName, OrderID = x.OrderID == null ? -1 : x.OrderID};   

As you can see I used the join into operator in Query Expression which results in the LEFT OUTER JOIN, I added my filter expression in the where clause and finally, I returned an anonymous type containing CustomerID, ContactName, and OrderID which is -1 in case there is a null Order record for the Customer otherwise returns the OrderID.

The T-SQL representation of the above is as follows:

SELECT [t0].[CustomerID], [t0].[ContactName],
    (CASE
        WHEN [t1].[OrderID] IS NULL THEN @p1
        ELSE [t1].[OrderID]
     END) AS [value]
FROM [dbo].[Customers] AS [t0]
LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]
WHERE [t0].[CustomerID] LIKE @p0

Notice how the LEFT OUTER JOIN appears, notice how the CASE appears which reflect the if/else that I have added in the above Query Expression.

Hope this helps you!
Regards

 


You can make your own ringtones, for your cell phones; if those already set on your phones doesn’t suite you. You can download handy soft wares from electronics websites that help you make customized ringtones. These procedures carry very simple instructions still if you find some difficulty, you can use printers to print the instructions.

Tags: , ,

Aug 1 2007

Automatic Proeprties

Category: C# 3.0Bil@l @ 08:06

In every 3-tier application we develop, there is always a need for model objects, which are nothing but classes we use to pass between DataAccess, Business, and UI layers. These classes contain only
simple properties that represent the columns of a Data Table that are retrieved from the database. As you can see, those objects need not any validation logic, dummy proeprties! We can use code
generation tools like CodeSmith, or even develop ower own tools too. But with C# 3.0, no need for any code generation tools anymore!!

A new feature of C# 3.0 is the Automatic Properties, you can write model classes in a more compact way and with less code! And the rest is left to the C# 3.0 compiler!

An example makes things clear:

  public class Customer {
  public int ID {get; set;}
  public string Name {get; set;}
  public Address Address {get; set;}
    }

 public class Address {
         public string City {get; set;}
         public string Building {get; set;}
         public string Phone {get; set;}
 }

As you can see I have written a class with minimal code. What happens at compile time is that, the C# 3.0 compiler will generate a full class including private fields and this way you can use the
Customer/Address classes are any normal class with one exception, we have written fewer lines of code and the rest was on C# 3.0 compiler that generates the full class for us!

Hope this helps,
Regards

Tags:

Jul 29 2007

Implicitly Typed Local Variables

Category: C# 3.0Bil@l @ 14:56

Implicitly Typed Local Variables is a general prupose way of declaring variables without the need to specify the data type. The data type will be infered implicitly from the initializer data. It is strongly typed variable
that cannot take as input a data type other than the one used on initialization time. This proves that "var" is not the same as "Dim" in VB/.NET. Dim can take different data types, however, "var" only takes values of the same data type that was used upon initialization.


 Things you cannot do with Implicitly Typed Local Variables
  You cannot declare an ITLV without specifying an initializer.
  You cannot set the value of a VAR to NULL.
  You cannot change the data type of an already defined VAR variable.
  
 Things you cannot do with Implicitly Typed Local Variables
  You can assign one VAR to another.
 
 An example of using a "var" is as follows:

 // Simple string
 var intValue= 5;

 // Array of integers
 var arrInt= new[] {1, 2, 3, 4};

 // Array of objects
 var arrObject= new[] {new Point(), new Point()};


 "var" is mainly used to shape the results of a Query Expression because sometimes you might return a result that cannot be used explicitly as follows:

 var results=  from c in db.customers
   select new MyCustomer {
    ID= c.ID,
    Name= c.Name
   };

 Now, we can navigate through the results as follows
 foreach (MyCustomer cust in results) {
  Console.WriteLine("{0}, {1}", cust.ID, cust.Name);
 }
 
 
Hope this helps you,
Regards

Tags:

Jul 29 2007

Extension Methods

Category: C# 3.0Bil@l @ 14:50

Extension methods are a way to extend the functionality of existing types by defining methods that can be invoked either by using the normal instance method syntax or in a static way. They are
defined in a static class, and each extension method should be a static one. The first parameter for the extension method should be preceeded by "this", which denotes the type being extended.
If there are any requried parameters, they can be placed infront of the first one.  

An example will show you how to extend the string class to add a method to check if a string week day is a valid weekday. For instance, Monday is a valid week day, while Mondy is not a valid week day!

First of all we define the static class that should contain the extension methods:

 public static class MyExtendedMethods
    {
        public static bool IsValidWeekDay(this string s) {
            Regex regEx= new Regex(@"^(Sun|Mon|(T(ues|hurs))|Fri)(day|\.)?$|Wed(\.|nesday)?$|Sat(\.|urday)?$|T((ue?)|(hu?r?))\.?$");
            return regEx.IsMatch(s);
        }
    }

As you can see the extension method should be placed inside a static class. Even the extension method should be designated with static keyword.

The static method, IsValidWeekDay, has no parameters and through the use of "this string s" this means this method will operate on the string class. The method returns a boolean value whether the string it is operating on returns true which means it is a valid weekday or false which means the string operating on is not a valid weekday.

Here is a sampel code on how to use the above extension method.

            string currDay= "Monday";
            if (currDay.IsValidWeekDay())
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

The above shows how to access the extension method as an instance method, if you want, you can also access this method through the use of static method:

            string currDay= "Monday";
            if (MyExtendedMethods.IsValidWeekDay(currDay))
                Console.Write("{0} is a valid day!", currDay);
            else
                Console.Write("{0} is not a valid day!", currDay);

Hope this helps you!
Rergards

Tags:

Jul 29 2007

Anonymous Types

Category: C# 3.0Bil@l @ 13:42

Anonymous types is a new feature of C# 3.0. It allows developers to creat local objects without the need to have a real signature of a class. This is helpful sometimes, when you have methods that take as input a large number of input parameters. What you can do is simply create a new anonymous type and use it through out the local body of the method. This way, you will be dealing with a strongly type class containing all input parameters instead of dealing with seperate fields.

 1.
 Anonymous types allows grouping data into a class that is created
 automatically at compile-time.

 2.
 var x= new {a=1, b=2, c="Bilal"};
 
 The above statement is compiled and the following is created:
 class __Anonymous1
 {
  private int _a= 3;
  private int _b= 5;
  private int _c= "some text";

  public int a { get{ return _a; } set{ _a = value;} };
  public int b { get{ return _b; } set{ _b = value;} };
  public int c { get{ return _c; } set{ _c = value;} };
 }

 3.
 When we define a subset of a class as an anonymous type,
 we declare the anonymous type without the need to specify
 properties names, this is called Projection Initializer.

Hope this helps,
Regards

Tags:

Jul 29 2007

Lambda Expressions

Category: C# 3.0Bil@l @ 13:37

 1.
 Lambda Expressions have been introduced as an improvement
 to the anonymous methods in C# 2.0 as a way to make them
 more compact.

 2.
 Lambda expression consists of:
  . Parameter List
  . =>
  . Expression

 3.
 Parameters of Lambda Expression can be implicitly
 or explicitly typed. Ex:
  . (int i) => (i+1)
  . (i) => (i+1)

 4. You can have single or multiple parameters Ex:
  . (x,y) => return x*y

 5. If you want to pass a lambda expression with no parameters:
  . () => return "Empty Parameters";


Think of Lambda expressions as an anonymous method in a more compact style. Take this example:

Suppose we have a list of employees named "customers". You want to query this list using a System defined Extension method called "WHERE" as follows:

var query= customers.Where( c => c.Country == "Lebanon"; );

As you can see the above lambda expression is composed of:

1- c: Which is the input parameter
2- => token
3- c.Country == "Lebanon": this is the expression that will be applied to every record retrieved from the customers list. So, while the query is looping through the records of customers,
it will apply the lambda expression, if the result of the expression is true, then it will include the current record in the result of the query.

We could have done the same using Anonymous methods as in C# 2.0:

var query= customers.Where(
  delegate (Customer c) {
   return c => c.Country == "Lebanon";
  }
 );


Notice also that the lambda expression can be a series of statements and not only a single simple statement.

(x) => { Console.WriteLine("Hello World"); return 0; }

All of the above expressions could have been placed with the { and } too!

Hope this helps,
Regards

Tags: