• Wriju's BLOG

    VB.NET 9.0: XML Literal

    • 8 Comments

    This is the one feature which can make VB.NET developers feel better than C# folks. I have seen people complaining about MS saying that MS has done lot for C# but not equally for VB.NET. One of the biggest was Refractoring. There are so many such. But this feature is just “SPELLBOUND” when I first experienced it.

     

    Today, people handle XML from .NET in many ways. One approach is they simply concatenate the string to create XML string and end up writing to a file. Another is they generate DataSet/DataTable and uses WriteXml() method to write Xml to a file. More sophisticated way is to use System.Xml namespace and build Xml step by step in strongly typed manner. But this one is something which is simply amazing.

     

    In Visual Studio 2008 if you write something using System.Xml.Linq

     

    Dim _xml2 = New XElement("ProcessList", _

                    New XElement("Process", _

                        New XAttribute("ThreadCount", "2"), "Some Process"))

     

    You can also write,

     

    Dim _xml = <Processes>

                   <Process ThreadCount="2">Some Name</Process>

               </Processes>

     

     

    These two statements are identical. Second one looks like an ASP.NET page but it is actually XElement object. But the feeling you will get as if you are writing an Xml in a XML Editor.

     

    Coolest ever.

    Today I found an article with very detailed discussion http://geekswithblogs.net/Silverlight2/archive/2008/03/30/xml-literals-and-embedded-expressions.aspx

     

    Namoskar!!!

  • Wriju's BLOG

    VB.NET 9.0: Lambda Expression Function

    • 0 Comments

    If you want to use Lambda Expression as reusable function, you need to use Func. By using the Func we are actually calling in-build delegate.

     

    So if you write

     

    Dim sqr As Func(Of Double, Double) = Function(x) x * x

     

    Then you can use it in you application to get the square of a number.

     

    Console.WriteLine(sqr(2))

    Console.WriteLine(sqr(8))

     

    This could be used in multiple places with different parameter as you generally do with any function.

     

    Namoskar!!!

  • Wriju's BLOG

    VB.NET 9.0: Lambda Expression

    • 5 Comments

    In VB.NET 9.0 Lambda is one of the features we have here. Lambda expression is just another way to call Anonymous method/delegate.

     

    Let’s look into a generic list of integers, and play with it,

     

    Dim arrInt As New List(Of Integer)

     

    For i As Integer = 1 To 10

        arrInt.Add(i)

    Next

     

    When you need to get the even numbers out of this List, you can call delegate,

     

    Dim even1 As New List(Of Integer)

     

    even1 = arrInt.FindAll(New Predicate(Of Integer)(AddressOf EvenGetter))

     

    Then for this approach you need a method,

     

    Public Function EvenGetter(ByVal i2 As Integer) As Boolean

        Return i2 Mod 2 = 0

    End Function

     

    Using VB.NET 9.0 you can also implement Lambda Expression,

     

    even1 = arrInt.FindAll(Function(i2 As Integer) i2 Mod 2 = 0)

     

    Ask expert for more.

     

    Namoskar!!!

  • Wriju's BLOG

    VB.NET 9.0: Object and Array Initializers

    • 6 Comments

    Last week I was exploring VB.NET for the ISV demo delivery. Some findings I want to share with you. First the object and Array Initializers

     

    Let’s suppose we have a class called Customer

     

    Public Class Customer

        Public Id As Integer

        Public Name As String

    End Class

     

    Now when you initialize this object in conventional VB.NET, this could be your approach,

     

    Dim cust As New Customer()

     

    With cust

        .Id = 1

        .Name = "VB.NET"

    End With

     

    Now in VB.NET 9.0 we do things in little differently,

     

    Dim cust = New Customer() With {.Id = 2, .Name = "VB.NET 9.0"}

     

    Also for array initialization in VB.NET we go for,

     

    Dim objCusts(1) As Customer

    objCusts(0) = New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}

    objCusts(1) = New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}

     

    In VB.NET 9.0 we write,

     

    Dim objCusts() As Customer = { _

        New Customer() With {.Id = 3, .Name = "VB.NET 10.0"}, _

        New Customer() With {.Id = 4, .Name = "VB.NET 11.0"}}

     

    It is small (to me simple), it is sweet.

     

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET : OleDbCommand Parameterized Query Sequence Rule

    • 9 Comments

    While working with MS Access database with OleDbCommand you might have faced issue that your parameterized update statement is not working. The most frustrating part is that it also does not throw any runtime error. So ideally you paralyzedJ.

     

    Golden rule is that you need to maintain the exact sequence of parameters you have specified in the sql statement. So while adding the parameter value sequence is very important.

     

    Command parameter collection addition sequence has to match with the sql statement sequence.

     

    String sSQL = "UPDATE PHONEDB SET [NAMES] = @pNames WHERE [ID] = @pID";

     

    OleDbConnection conn = new OleDbConnection("ConnectionString");

    OleDbCommand cmd = new OleDbCommand();

     

    cmd.Connection = conn;

    cmd.CommandType = CommandType.Text;

    cmd.CommandText = sb.ToString();

     

     

    cmd.Parameters.AddWithValue("@pNames", "Your Name");

    cmd.Parameters.AddWithValue("@pID", 12345);

     

     

    Now if you alter the sequence like,

     

    cmd.Parameters.AddWithValue("@pID", 12345);

    cmd.Parameters.AddWithValue("@pNames", "Your Name");

     

    Things would not work as expected.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Understanding Mapping

    • 6 Comments

    In LINQ to SQL you play with pure .NET objects and write your LINQ on top of that. But question might arise how this magic happens. Though we say that it is object, the question might arise in our mind that there has to be a mechanism through which it connects. Yes, there is. That is DataContext which controls the background transaction. But again how it understands that your class is actually representing a database object, is only though Attribute magic.

     

    There could be different database components,

     

    Database Æ DataContect

    Table Æ Class

    Column Æ Property/Field

    Relationship Æ Property/Field

    View Æ Class

    Stored Procedure Æ Function

     

    Now when we write code for that how we define them?

     

    Let us have a database TestDB and a table Emp.

     

    CREATE TABLE [dbo].[Emp](

          [Id] [int] IDENTITY(1,1) NOT NULL,

          [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

          CONSTRAINT [PK_Emp] PRIMARY KEY CLUSTERED

    (

          [Id] ASC

    )WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

    ) ON [PRIMARY]

     

    Step 1:

    ++++

    Create a table representation,

    public class Employee

    {

        public int Id { get; set; }

     

        public string Name { get; set; }

    }

     

    Now map this class for dbo.Emp table through attribute.

     

    [Table(Name="dbo.Emp")]

    public class Employee

    {

    public int Id { get; set; }

     

    public string Name { get; set; }

    }

     

     

    Step 2:

    ++++

    Now you need to map columns,

     

    [Column(IsDbGenerated=true, IsPrimaryKey=true)]

    public int Id { get; set; }

     

    Now this is because the Id column is Primary Key and automatically generated column.

     

    [Column]

    public string Name { get; set; }

     

    Notice here I am not specifying the “Name=” is because the property name and the column names are identical.

     

    Step 3

    ++++

    You have Database which ideally DataContext should be able to handle, so if you do not want to create class for that, you can very well do that. Like

     

    DataContext db = new DataContext(@"Connection String");

    var query = db.GetTable<Employee>();

     

    But if you really would like to get the strongly typed behavior with statement completion then the approach would be little different.

     

    public class TestDB : DataContext

    {

        public TestDB(string sConn): base(sConn){}

     

        public Table<Employee> Emps;

    }

     

    Now if you start writing the same code this will give you the itellisense and statement completion,

     

    TestDB db = new TestDB(@"Connection String");

    var query = db.Emps;

     

    var query1 = from e in db.Emps

                 where e.Id == 1

                 select e;

     

    Hope you liked this.

     

     

    Namoskar!!!

  • Wriju's BLOG

    MSDN Tech Posters

    • 1 Comments

    I found an article at http://blogs.msdn.com/cbowen/archive/2007/12/09/got-tech-posters.aspx for Tech Posters.

    Namoskar!!!

  • Wriju's BLOG

    Funny but real SDLC

    • 2 Comments

    I was browsing http://blechie.com/WPierce/archive/2007/12/03/The-Way-Things-Work-in-the-Software-Business.aspx

    A nice view which is self explanatory reality

    TheWayThingsWork_thumb

    Namoskar!!!

  • Wriju's BLOG

    IIS 7 : First Experience

    • 0 Comments

    Today I created my first test ASP.NET application in IIS 7 in Windows 2008. It is amazing, now in IIS manager you can configure the ASP.NET with nice panel,

    image

    I will explore more on this. A very happy 2008 ahead.

    Namoskar!!!

  • Wriju's BLOG

    MS Press Free E Book on LINQ

    • 3 Comments

    http://csna01.libredigital.com/

    Namoskar!!!

  • Wriju's BLOG

    Visual Basic LINQ Hands On Labs for Visual Studio 2008

    • 1 Comments

    Download available for Hand On Labs for

    Ø       LINQ

    Ø       LINQ to SQL

     

    http://www.microsoft.com/downloads/details.aspx?FamilyID=e7fa5e3a-f8b2-4f77-bbcd-b5b978402dd1&DisplayLang=en

     

    Namoskar!!!

     

  • Wriju's BLOG

    Sharing “var” across the method

    • 5 Comments

    One of the biggest limitation in “var” is that it cannot be shared across the methods. So if you are doing something using that keyword then you have to stick to the local. I was reading Alex’s Blog where he explained it very nicely,

     

    Here is my implementation,

     

    Create an Extension method

     

    static class MyClass

    {

        //Create Extension Method to covert the var

        public static T CastVar<T>(this object obj, T anyType)

        {

            return (T)obj;

        }

    }

     

     

    Now suppose you want to get output of type “var” from any method,

     

    public static object GetVAR()

    {

        var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        return (object)list;

    }

     

    Retrieve it to an object.

    object o = GetVAR();

     

    Next is the tricky part, as per Alex

     

    This works because when an anonymous type is used the compiler first checks that one with the same signature (i.e. all fields are the same name and type) hasn't already been used. If one has the same CLR type is used.”

     

    You need to know the shape of the object to put it again back to “var” type.

    var o1 = o.CastVar(new List<int>{1});

     

    Now this iteration will work perfectly fine as if you are working with any other local “var”.

     

    foreach (int i in o1)

    {

        Console.WriteLine(i);   

    }

     

    I have tested this for LINQ to SQL where we use “var” very frequently,

     

    static void Main(string[] args)

    {

        object o = GetVAR();

                   

        var query = o.CastVar(new[] {new {CID = "", Company = ""}});

     

        foreach (var c in query)

        {

             Console.WriteLine("{0} - {1}", c.CID, c.Company);

        }

    }

     

    public static object GetVAR()

    {

        NWDataContext db = new NWDataContext();

     

        var q = from c in db.Customers

                where c.City == "London"

                select new

                {

                    CID = c.CustomerID,

                    Company = c.CompanyName

                };

     

        return (object)q.ToArray();

    }

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL and ADO.NET

    • 3 Comments

    Here I am going to compare the two technologies and point some missing areas.

     

    Let us use the Northwind database and get the list of Customers from city London. The ADO.NET approach would be,

     

    static void Main(string[] args)

    {

        string sConn = @"ConnectionString";

        using (SqlConnection conn = new SqlConnection(sConn))

        {

            using (SqlCommand comm = new SqlCommand

                 ("SELECT CustomerId, CompanyName FROM " +

                       " Customers WHERE City = @City", conn))

            {

                conn.Open();

                comm.Parameters.AddWithValue("@City", "London");

     

                SqlDataReader reader = comm.ExecuteReader();

     

                while (reader.Read())

                {

                    string sCID = reader[0].ToString();

                    string sCompanyName = reader[1].ToString();

                }

            }

        }               

    }

     

    Now this code will compile and execute perfectly. But if I change this code a bit the compiler will not throw any error but runtime errors will be there.

     

    using (SqlConnection conn = new SqlConnection(sConn))

    {

        using (SqlCommand comm = new SqlCommand

                    ("SELECTBlah CustomerId, CompanyName FROM " +

                     " Customers WHERE City = @City", conn))

        {

            conn.Open();

            comm.Parameters.AddWithValue("@City", 12.4);

     

            SqlDataReader reader = comm.ExecuteReader();

     

            while (reader.Read())

            {

                string sCID = reader[0].ToString();

                string sCompanyName = reader[1].ToString();

                string sXYZ = reader[2].ToString();

            }

        }

    } 

     

    Highlighted areas will throw me runtime error.

     

    Ø       Not only the SQL keywords (SELECTBlah) but any problem there will throw error at runtime.

    Ø       Adding parameter with value which is not supported (float)

    Ø       Reading the third column value which I am actually not retrieving through my SQL query.

    Ø       I am converting everything to String but there might be null values and moreover this is not strongly typed.

     

    Now with this approach people already have developed lot of projects. ADO.NET is powerful but these are the commonly faced drawbacks. To avoid all the errors we need to invest in Testing. This increases the product cost in the market.

     

    In LINQ to SQL how this can be achieved easily,

     

    Create mapping class for the customer Table

    [Table(Name="Customers")]

    class Customer

    {

        [Column]

        public string CustomerId { get; set; }

        [Column]

        public string CompanyName { get; set; }

    }

     

    Now directly using the DataContext I can get the output.

     

    DataContext db = new DataContext(sConn);

     

    var q = from c in db.GetTable<Customer>()

            where c.City == "London"

            select new

            {

                CustomerId = c.CustomerId,

                CompanyName = c.CompanyName

            };

     

    foreach (var k in q)

    {

        Console.WriteLine(k.CustomerId + " : " + k.CompanyName);

    }

     

    Here things I cannot do,

    Ø       Cannot mistype any query keyword as it is native statement (not in “”)

    Ø       Cannot pass type to condition which is not supported

    Ø       Cannot project the output with any value

    Ø       Moreover the output is IEnumerable of some type so the output is strongly typed

     

    There are lot of other benefits like, you will get intellisense and the statement completion. Moreover all the previous ADO.NET runtime errors will become compile time errors.

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : Execution Architecture

    • 8 Comments

    In L2S query execution can be separated in two major areas. One is to fetching the data another is manipulating the data (update, delete and insert). I use one slide during my L2S demo and here it is,

     

    clip_image001

     

    Fetching data from database

     

    LINQ is only from fetching the data from database. LINQ does not have any query operator for delete, update or insert. When you send LINQ to your L2S layer then L2S translates that to SQL understandable query (T-SQL). This is obvious because as per one of the major design specifications we have decided to make the LINQ independent of any existing API. T-SQL is standard and works for any version of SQL Server database and will continue to work with upcoming releases. Now as usual SQL executes that query and gives the result back to our L2S layer. Then L2S gives us the result back to us in form of IEnumerable<T>.

     

     

    clip_image001[5]

     

    Manipulating data

     

    When it comes to data manipulation you can go for DML statements or Stored Procedure. If you have Stored Proc then dbml designer allows us to modify the update, delete and insert accordingly. This manipulation happens purely through object model.

     

    For insert

    You create an object and add the necessary properties. Then add to the existing collection. Once done call SubmitChanges() method.

     

    For delete

    You get the object(s) and using the method Remove(), remove it from the existing collection. Then call SubmitChanges() method.

     

    For update

    You get the object(s) to modify. Then call SubmitChanges() method.

     

     

    Namoskar!!!

  • Wriju's BLOG

    LINQ to SQL : What is DataContext.Translate Method

    • 4 Comments

    DataContext’s Translate method converts existing IDataReader to an IEnumerable<T>. This is very useful when you may need to run raw SQL Query though System.Data.Linq. I am getting few similarities with DataContext’s ExecuteQuery.

     

    How Translate works

    +++++++++++++

    Assuming I am using Northwind database.

     

     

    using (NWDataContext db = new NWDataContext())

    {

        DbConnection conn = db.Connection;

        conn.Open();

     

        DbCommand comm = conn.CreateCommand();

        comm.CommandText = "SELECT * FROM Customers";

     

        DbDataReader reader = comm.ExecuteReader();

     

        var q = db.Translate<Customer>(reader);

     

        ObjectDumper.Write(q);

    }       

     

    Now since my dbml has Customer class defined and I am running SELECT * query this can map with existing Customer class. But if I want to retrieve only the selected columns from the result set then one of the drawbacks is that I cannot project the output using Anonymous Type, rather I need to define a class in my app to project it to IEnumerable<T>. One of the reasons is that the Anonymous Type does not create any default public constructor. It would have been nice to have this anonymous type projection with the Translate.

     

    So if you want to map it to your type then your approach would be little different.

     

    using (NWDataContext db = new NWDataContext())

    {

        DbConnection conn = db.Connection;

        conn.Open();

     

        DbCommand comm = conn.CreateCommand();

        comm.CommandText = "SELECT CustomerId, CompanyName FROM Customers";

     

        DbDataReader reader = comm.ExecuteReader();

     

        var q = db.Translate<CustomerSelect>(reader);

     

        ObjectDumper.Write(q);

    }   

     

    Extra things you need is that,

     

    class CustomerSelect

    {

        public int CustID { get; set; }

        public string CompanyName { get; set; }

    }

     

    Whereas in ExecuteQuery method you do things little differently,

     

    using (NWDataContext db = new NWDataContext())

    {

        var q = db.ExecuteQuery<Customer>("SELECT * FROM Customers", "");

     

        ObjectDumper.Write(q);

    }

     

     

    Namoskar!!!

  • Wriju's BLOG

    ASP.NET 3.5 Extension Preview

    • 1 Comments

    What is that? Know more on http://quickstarts.asp.net/3-5-extensions/

     

    Other related resources,

     

    ASP.NET 3.5 Extensions Preview Download

    ASP.NET 3.5 Extensions Preview Forums

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Useful keyword “var”

    • 6 Comments

    People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of Language INtegrated Query (LINQ). Can you initialize Anonymous Type without “var”? There are so many no-nos. Let’s appreciate it and start use. I already have explained in one of my previous blogs,

     

    Scenario 1 (Anonymous Type)

    +++++++++++++++++++

    When you have no type defined but want to create that, we need “var”.

     

    var obj = new { ID = 1, Name = "Wriju" };

     

    You cannot assume the name created by compiler for this Anonymous Type. Please feel free to add comment to my blog if you have choice to add type in the above example while declaring the variable.

     

    Scenario 2 (Projecting it to IEnumerable<AnonymousType>)

    ++++++++++++++++++++++++++++++++++++++

    Suppose if you want to get the output containing only the selected column you have to project it to a type.

     

    IEnumerable<CustomerSelect> query =

        from c in db.Customers

        where c.City == "London"

        select new CustomerSelect

        {

            CustID = c.CustomerID,

            CompanyName = c.CompanyName

        };

     

    As you cannot have “,” as you are used to for any T-SQL query. Here you need everything as strongly typed. So you need to create a class, here I have created one,

     

    class CustomerSelect

    {

        public int CustID { get; set; }

        public string CompanyName { get; set; }

    }

     

    So here boldly you can retrieve the result like, IEnumerable<CustomerSelect>

    in case if you do not want to use var here. But if you are lazy developer like me then you might not be interested in creating class for every need. Rather you will use anonymous type and get the IEnumerable<AnounymousType> as query output. But how will be defining IEnumerable of some anonymous type (in fact no type). No wander you must appreciate the real power of “var” here.

     

    var query =

        from c in db.Customers

        where c.City == "London"

        select new

        {

            CustID = c.CustomerID,

            CompanyName = c.CompanyName

        };

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Joining two in-memory collection through LINQ

    • 4 Comments

    LINQ allows us to join different collection source provided we are mapping with two properties with the same type. It is easy, it is quick and it is concise.

     

     

    //Create Employee Class

    class Employee

    {

        public int ID { get; set; }

        public string Name { get; set; }

        public string ManagerId { get; set; }

    }

     

    //Create Manager Class

    class Manager

    {

        public string Id { get; set; }

        public string Name { get; set; }

    }

     

    class Program

    {

        //Create the List<Manager>

        static List<Manager> GetManagers()

        {

            return new List<Manager>

            {

                new Manager(){Id = "M1", Name = "Manager 1"},

                new Manager(){Id = "M2", Name = "Manager 2"}

            };

        }

     

        //Create the List<Employee>

        static List<Employee> GetEmployees()

        {

            return new List<Employee>

            {

                new Employee(){ID = 1, Name = "A", ManagerId = "M1"},

                new Employee(){ID = 2, Name = "B", ManagerId = "M1"},

                new Employee(){ID = 3, Name = "C", ManagerId = "M1"},

                new Employee(){ID = 4, Name = "D", ManagerId = "M1"},

                new Employee(){ID = 5, Name = "E", ManagerId = "M2"},

                new Employee(){ID = 6, Name = "F", ManagerId = "M2"},

                new Employee(){ID = 7, Name = "G", ManagerId = "M2"},

                new Employee(){ID = 9, Name = "H", ManagerId = "M5"}

            };

        }

     

        static void Main(string[] args)

        {

            /*Doing join between two sources

             *The record will be retieved only the mathched data

                 * Output will give values from both the collection

                 */

                var query = from e in GetEmployees()

                            join m in GetManagers() on e.ManagerId equals m.Id

                            select new

                            {

                                EmployeeId = e.ID,

                                EmployeeName = e.Name,

                                Manager = m.Name

                            };

     

                foreach (var o in query)

                {

                    Console.WriteLine("{0}-{1} [{2}]",

                        o.EmployeeId,

                        o.EmployeeName,

                        o.Manager);

                }           

            }       

        }

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 Feature Articles

    • 0 Comments

    With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding with you. Here I am compiling all of them together for indexing,

     

    C# 3.0: Vote for the keyword “var”

     

    C# 3.0 Features: Automatic Property

    C# 3.0 Features: Automatic Property (Part 2)

    C# 3.0 Features: Automatic Property (Part 3)

     

    C# 3.0 Enhancements: Lambda Expression

    C# 3.0 : Evaluation of Lambda Expression to Language INtegrated Query (LINQ)

    C# 3.0 : Exploring Lambda Expression

     

    C# 3.0 Enhancements: Expression Trees

     

    C# 3.0 Enhancements: Object Initializers

    C# 3.0 Enhancements: Collection Initializers

     

    C# 3.0 Enhancements: Extension Methods

     

    C# 3.0 : Anonymous Type and .NET Reflection Hand-in-Hand

    C# 3.0 : Anonymous Types

     

    C# 3.0 : Partial Methods

     

    C# 3.0 is 100% backward compatible with C# 2.0

     

     

    Namoskar!!!

  • Wriju's BLOG

    C# 3.0 : Partial Methods

    • 1 Comments

    C# 2.0 and Partial class, in one of the amazing features to work with one class separated in multiple physical files. Not only that, it also helps us to extend designer generated code such as Typed DataSet, Designer generated code etc.

     

    With this C# 3.0, we can now have partial method. Partial methods are the code block which reside inside a partial type and gets executed only when it has definition. This gives us the extensibility and if user wants to implement the rule, they can go ahead and define the body but if they do not want it will not. This improves the performance as you are not loading/creating unwanted methods.

     

    Here I am going to explain what is that? People already have documented about this feature in so many places, here I am,

     

    Let us consider this piece of code,

     

    public partial class MyClass

    {

        //Public Constructor

        public MyClass(int iInput)

        {

            //Calling Partial Method

            GetMessage(iInput);

        }

     

        //Public Property

        public string Messgae { get; set; }

     

        //Partial Method

        partial void GetMessage(int iVal);

    }

     

    In the partial method declaration I cannot have any body. So, where we need to define the body of our method?

     

    Should be in another partial class (I will explain that later). But since there is no body, the method actually will have no existence in IL.

     

    clip_image001

    Notice no existence for the method GetMessage(int iVal)

     

    Calling block,

    static void Main(string[] args)

    {

        MyClass obj = new MyClass(10);

     

        Console.WriteLine(obj.Messgae);

    }

     

    Now if you define the body of the function in a partial class the IL will look different as well as the Console.WriteLine()will print the value.

     

    PartialMethod2

     

    Notice this IL, this has got the definition for GetMessage in it.

     

    How the definition would look like,

     

    public partial class MyClass

    {

        partial void GetMessage(int iVal)

        {

            this.Messgae =

    "The value entered by you is : " + iVal.ToString();

        }

    }

     

    Some golden rules on Partial Methods, (these are the typical errors you will get from Visual Studio if anything is missing)

     

    You must visit wesdyer’s blog for more detailed specification.

     

    Ø       A partial method must be declared within a partial class or partial struct

    Ø       A partial method cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern modifiers

    Ø       Partial methods must have a void return type

    Ø       A partial method cannot have out parameters

    Ø       Definition has to end with “;” No {} is allowed in this scope.

     

     

    Some good resources,

     

    http://community.bartdesmet.net/blogs/bart/archive/2007/07/28/c-3-0-partial-methods-what-why-and-how.aspx

     

    Namoskar!!!

  • Wriju's BLOG

    Architecture Journal Reader (Beta) is available for download

    • 2 Comments

    Another Windows Presentation Foundation implementation for the popular Architecture Journal is now available for download. So know about Ray Ozzie the Chief Software Architect of Microsoft – the most prestigious position in Microsoft which was captured by Bill Gates.

     

    Project Astoria, S+S and many more. All the 13 published journals are available in nice readable format.

     

    So go ahead and download Just Released: Architecture Journal Reader (Beta)

     

    Let’s check what I am reading,

     

    image

     

    Namoskar!!!

  • Wriju's BLOG

    MSDN Virtual Labs : C# 3.0, Visual Basic 9.0, ASP.NET 3.5

    • 1 Comments

    Learn and for installation-free mode and get started with Visual Studio 2008.

     

    MSDN Virtual Lab: Building Web Applications with Visual Studio 2008

    MSDN Virtual Lab: What's new in C# 3.0

    MSDN Virtual Lab: What's new in Visual Basic 9

     

    Namoskar!!!

  • Wriju's BLOG

    ADO.NET Entity Framework 3.5 Beta 3 Released today

    • 3 Comments

    Beta 3 of the ADO.NET Entity Framework, and a preview of ASP.NET 3.5 Extensions. Designed to make it even easier for developers to build data-centric applications and services regardless of the underlying data source, the ADO.NET Entity Framework is already gaining significant support from multiple database vendors and third-party providers, including Core Lab, Data Direct Technologies, Firebird, IBM, MySQL AB, Npgsql, OpenLink Software, Phoenix Software, Sybase and VistaDB.

     

    Microsoft also announced today a preview of ASP.NET 3.5 Extensions, which leverages the Entity Framework to make it easier for developers to build rich, interactive data-centric applications on the Web. The ASP.NET 3.5 Extensions Preview includes:

    • ADO.NET Entity Framework
    • ASP.NET MVC
    • ADO.NET Data Services
    • ASP.NET Dynamic Data
    • New additions to ASP.NET AJAX
    • Silverlight controls for ASP.NET

     

    Downloads

    +++++++

    ·         Entity Framework Beta 3 runtime

     

    ·         Entity Framework Tools CTP 2

     

    ·         ASP.NET 3.5 Extensions preview

     

    Enjoy.

     

    Namoskar!!!

     

  • Wriju's BLOG

    LINQ to SQL and C# 3.0 Hands on Labs

    • 1 Comments

    Hands on labs are available online and this is the best HOL till date for LINQ and C# 3.0.

     

    LINQ Hands On Labs

    LINQ to SQL Hands on Lab

    C# 3.0 Language Enhancements Hands On Lab

     

    Namoskar!!!

     

  • Wriju's BLOG

    C# 3.0 : Exploring Lambda Expression

    • 10 Comments

    I started playing with Lambda expression after the TechEd demo by Anders Hejlsberg. Couple of nice things I would like to share with you.

     

    As there might be many definitions for Lambda expression but to me Lambda Expression is the concise way to write functional implementation for Anonymous Method. This is been used by compiler to translate LINQ to method calls. This also allows us to maintain 100% backward compatibility with any managed version of C#.

     

    Lambda function can be created using the Generic delegate Func. Func<A,R> (represents a function taking an argument of type A and returning a value of type R) is the predefined .NET call to a delegate for n number of parameters with any type. Life is easy for us. Func is defined inside System.Linq namespace. So being developer we do not have to bother about the number of variable and there types. We can simply go ahead and create any function using Func.

     

    Now if you have an anonymous method for a List of Integers which finds the even numbers from the list.

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using delegate (anonymous method) get the even numbers

    List<int> even1 = arrInt.FindAll(delegate(int i2) { return i2 % 2 == 0; });

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    Now, if I want to implement Lambda Expression there the code will look like,

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using Lambda Expression get the even numbers

    List<int> even1 = arrInt.FindAll(i => i % 2 ==0);

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    Now, if you want to create the same list by using Lambda Expression and Func

    //This means I am creating a function which

    //takes an argument integer and returns bool.

    Func<int, bool> EvenGetter = x => x % 2 == 0;

     

    //Generic List of Integers

    List<int> arrInt = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     

    //Using Lambda Expression get the even numbers

    IEnumerable<int> even1 = arrInt.Where(EvenGetter);

     

    //dump them in the console

    foreach (int j in even1)

    {

        Console.WriteLine(j);

    }

     

    So here we are reusing a Function with the name EvenGetter and this is like any other function not in embedded.

     

    Func is very powerful, we can create List of Lambda Expression Functions and iterate through the list and check one input through multiple functions,

     

    Let us assume that I need to pass one integer and get some four out puts. I will create Generic List of Func’s which takes one argument as double and returns double.

     

    List<Func<double, double>> funcs = new List<Func<double,double>>();

     

    //Add function to the list

    funcs.Add(x => x * x); //Get the square

    funcs.Add(x => 1 / x);

    funcs.Add(x => Math.Sqrt(x)); //Sqr root of x

     

    //iterate through the list

    foreach (var f in funcs)

    {

        //Execute the functions one by one with the value 100

        Console.WriteLine(f(100));   

    }

     

     

    Output

    ---------

    10000

    0.01

    10

    Press any key to continue . . .

     This is pure functional programming.


    Namoskar!!!

Page 19 of 25 (609 items) «1718192021»