Perfil de ambatiProgramming Myself.. Amb...FotosBlogListasMás Herramientas Ayuda

Blog


29 junio

MVP vs MVC

http://ameleta.spaces.live.com/blog/cns!5F6316345A821420!163.entry

MVP vs MVC

Model View Presenter vs Model View Controller 

Intro
In my work I often deal with the situation when people use MVС/MVP patters without clear understanding the really difference between them. In this article I will try to explain my view on the issue.

 It’s important to understand that in n-tier systems MVP/C patterns are responsible for the presentation layer only. It’s not about how you build data or services layers, it’s about separating the data (model) and the user interface(view), telling you how the user interface communicates with data. Using these patterns gives your application independence on changing presentation without depending on data and controlling logic.

 Generally:

1.       Model means data & business logic model. It’s not always a DataSet, DataTable or such stuff. It’s kind of components or classes which can provide data and can receive the data to store it somewhere else. To simplify understanding of Model just think about it as “Façade” class.
2.
       View represents data for the user. Generally it’s just the UI, and not always UI logic. For example in ASP.NET the page with controls is View.  The View can receive data directly from Model, but View never updates Model.
3.
       The Presenter/Controller contains the logic to update Model regarding the user’s actions into the View. View only notifies Controller about user’s actions. Controller extracts data from View and sends it to Model. 

The main point of the MVC/P pattern is to split Model from View/Controller to make Model independent from them. So, Model cannot contain the references to the V/C.

 What is the MVC (model-view-controller)?
1.
       Controller initializes the events of View interface to interact with model and controller.
2.
       The user interacts with View (UI).
3.
       Controller handles user’s events (can be the “observer” pattern) and asks Model to update.
4.
       Model raises events, informing subscribers (View) about changes.
5.
       View (UI) (subscribes to model events) handles Model’s evens and shows new Model’s data.
6.
       The User Interface waits for the further user actions.

Primary points are:

1.       View does not use Controller to update Model. Controller handles the events from View to manage user’s interaction and data (via interaction with Model)
2.
       Controller can be combined with the View. It’s what the Visual Studio do for the Windows Forms by default. The primary point is logical separation of Model from the View.
3.
       The Controller do not contains the rendering logic.

The example below illustrates the “Active-MVC” pattern, also known as “the original MVC pattern”.
                                                                                                                    

 There is also the “Passive-MVC” pattern.

 The differences are that:
-
         Model knows nothing about Controller and View, it only used by them both.
-
         Controller uses View asking it to render new data.
-
         View uses Model to get the data only when Controller ask View about it (no subscription between View and Model).
-
         Controller handle Model data changes.
-
         Controller may contain the rendering logic for the View.

And now we are close to MVP pattern.
MVP is like an MVC, but View doesn’t use Model.

In the MVP View and Model are utterly separated from each other using the Presenter. Any interaction between View and Model take place in Presenter. 

Presenter is like the Controller, but which:
1.
       handles the user events from View (in MVC View handles this events);
2.
       updates Model using updated data from View (MVC passive just informs View to get/set new data from Model and MVC active takes no role in it, because Model informs View);
3.
       examines Model for changes (like the MVC passive);
4.
       (the main difference from MVC) gets Model data and stores them into View;
5.
       (the main difference from MVC active) notifies View about updates;
6.
       (difference from MVC) renders View using the Presenter

So, MVP has following pros:
1.
       Model is separated from View and we can change View independently from Model
2.
       We using Model more effective, because all interactions are now in one place –in the Presenter(Controller)
3.
       We can use one Presenter(Controller) for many Views without changing the Presenter(Controller) logic, it’s can be useful because View changes more often than the Presenter(Controller)
4.
       If we are storing View logic in the Presenter(Controller) we can test the logic independent of user interaction (Unit Testing)

But there are cons:
1.
       Too many interactions between View and Presenter because rendering View data is in the Presenter;

Also you need to understand that if you render too much data for View you are tied up on the particular View. So if  View needs to be changed you need to update the Presenter either, For example, if you rendered html and need to render the pdf, there is a big possibility that View need to be changed too. 

Do Windows speak

http://ameleta.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&_c=BlogPart&partqs=amonth%3d4%26ayear%3d2007

Do Windows speak


Some years ago I spend much time on integrating a voice support into user help module - there was much code to integrate windows speech system. But now the .NET 3 can solve it in just of 1-2 lines of code:


using

System.Speech.Synthesis;

namespace TestConsoleApplication1
{
     class Program

     {
          
static void Main(string[] args)
           {
                  
SpeechSynthesizer mySpokenWords = new SpeechSynthesizer();
                   mySpokenWords.Speak(
"Hi World!");
           }
     }
}

 

And that's all what you are need to hear a nice Hi World message!


To be more precisely - it's almost all. To do this you need:

·         .NET Framework 3.0

·         Visual Studio 2005

·         Visual Studio 2005 extensions for .NET Framework 3.0 http://www.microsoft.com/downloads/details.aspx?familyid=5D61409E-1FA3-48CF-8023-E8F38E709BA6&displaylang=en#Overview to be able to add .NET 3.0 references to a project.

·         Speech SDK (which is also included into Windows Vista SDK (http://www.microsoft.com/downloads/details.aspx?familyid=4377f86d-c913-4b5c-b87e-ef72e5b4e065&displaylang=en)

28 junio

Endpoints .. Expose a stored procedure as webservice(Part I)

Yesterday I spoke with my friend (RaviKumar Palanivel) and colleague in Caritor(now Keane).

After general discussions we discussed about the project NewCastle.

 We used WCF extensively there.And it is becoming as complex ntier application.

So they thought of using Endpoints that came newly in sqlserver 2005.

How to expose a sqlserver stored procedure as webservice and consuming it in a windows application?

 By using Enpoints in sqlserver 2005 we can achieve this easily.

Its a nice discussion with him.

Then I started some R&D and done a sample application.

Result is this:

For Creating EndPoints:
/****** Object:  Endpoint [Goals]    Script Date: 06/28/2007 10:14:19 ******/

CREATE ENDPOINT [Goals]
       AUTHORIZATION [sa]

       STATE=STARTED

       AS HTTP (PATH=N'/newcastle/Goals', PORTS = (CLEAR), AUTHENTICATION = (NTLM, KERBEROS, INTEGRATED), SITE=N'+', CLEAR_PORT = 8080, COMPRESSION=DISABLED)

       FOR SOAP (

WEBMETHOD 'CreateGoal'( NAME=N'[newcastle].[dbo].[csp_Goal_Create]'

, SCHEMA=DEFAULT

, FORMAT=ALL_RESULTS),
BATCHES=DISABLED, WSDL=N'[master].[sys].[sp_http_generate_wsdl_defaultcomplexorsimple]', SESSIONS=ENABLED, SESSION_TIMEOUT=60, DATABASE=N'newcastle', NAMESPACE=N'http://tempuri.org', SCHEMA=STANDARD, CHARACTER_SET=XML)


Above code

CreateGoal
-Webmothod
[dbo].[csp_Goal_Create]-
linked stored procedure
after creating

type

http://localhost:8080/newcastle/Goals?wsdl in webbrowser

type wsdl.exe "http://localhost:8080/newcastle/Goals?wsdl" in visual studio command prompt.

then you will be getting Goals.cs file as a output.

This Goals class will be having the method 'CreateGoal' with parameters equivalent to the stored procedure [dbo].[csp_Goal_Create].



 

 

Coming Articles

1. How to expose a sqlserver stored procedure as webservice and consuming it in a windows application?

2. Sqlserver Notification services

3. MARS

4. SMO

 

 

27 junio

Yellow Screen of Death

What is "Yellow Screen of Death "? 
 
 
The yellow screen of death is the screen displayed by Mozilla-based applications
when it meets XML parsing error. This happens when the XML document is not well-
formed, such as missing closing tag.
santhosh says:
The yellow screen of death is the colloquial name given to an Exception report
screen generated by ASP.NET.
The screen displays the exception message and a stack trace with a yellow
background. If the application was running in debug mode it also displays source
-code locations in the stack-trace. If the website employed inline server code
then it also displays the source code causing the error.

Anonymous Delegates Part2

 (Suggested By Gaurav)
  1. Basics of anonymous methods
  2. Static data member usage with anonymous methods
  3. Instance data member usage with anonymous methods
  4. Local variable usage with anonymous methods
  5. Scoping and local variable usage with anonymous methods
  6. Local variable usage with anonymous methods within loop control structures
  7. Summary

1. Basics of anonymous methods

Anonymous methods is a new language feature in C# 2.0. The focus of this article is to provide the readers with a better understanding of the internal implementation and working of anonymous methods. This article is not intended to be a complete language feature reference for anonymous methods.

Anonymous methods allow us to define a code block where a delegate object is acceptable. This facility saves us an extra step of creating a delegate for small code blocks that we want to pass to a delegate. It also removes the cluttering of small methods in the class code. Let us say, for instance, that we have a string collection class named MyCollection. This class has a method that retrieves all the items in the collection that satisfies a user supplied criteria, i.e., the caller decides whether a particular item in the collection qualifies for being retrieved as part of the return array from this method.

public class MyCollection
{
    public delegate bool SelectItem(string sItem);

    public string[] GetFilteredItemArray(SelectItem itemFilter)
    {
        List<string> sList = new List<string>();
        foreach(string sItem in m_sList)
        {
            if (itemFilter(sItem) == true) sList.Add(sItem);
        }
        return sList.ToArray();
    }
    
    public List<string> ItemList
    {
        get
        {
            return m_sList;
        }
    }

    private List<string> m_sList = new List<string>();
}

We can write code as shown below to use the above defined class:

Collapse
public class Program
{
    public static void Main(string[] args)
    {
        MyCollection objMyCol = new MyCollection();
        objMyCol.ItemList.Add("Aditya");
        objMyCol.ItemList.Add("Tanu");
        objMyCol.ItemList.Add("Manoj");
        objMyCol.ItemList.Add("Ahan");
        objMyCol.ItemList.Add("Hasi");
        
        // get an array of string items in the collection that start
        // with letter 'A'
        //
        string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA);
        Console.WriteLine("----- Strings starting with letter 'A' -----");
        foreach(string s in AStrings)
        {
            Console.WriteLine(s);
        }

        // get an array of string items in the collection that start
        // with letter 'T'
        //
        string[] TStrings = objMyCol.GetFilteredItemArray(FilterStringWithT);
        Console.WriteLine("----- Strings starting with letter 'T' -----");
        foreach(string s in TStrings)
        {
            Console.WriteLine(s);
        }
    }
    
    public static bool FilterStringWithA(string sItem)
    {
        if (sItem[0] == 'A')
            return true;
        else
            return false;
    }

    public static bool FilterStringWithT(string sItem)
    {
        if (sItem[0] == 'T')
            return true;
        else
            return false;
    }
}

One can see that for each simple criteria we want to provide, we should define a method (static or instance). This soon clutters the class code. With anonymous methods, the code becomes much natural. Below is the class Program re-written using anonymous methods.

Collapse
public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        MyCollection objMyCol = new MyCollection();
        objMyCol.ItemList.Add("Aditya");
        objMyCol.ItemList.Add("Tanu");
        objMyCol.ItemList.Add("Manoj");
        objMyCol.ItemList.Add("Ahan");
        objMyCol.ItemList.Add("Hasi");

        // get an array of string items in the collection that start
        // with letter 'A'
        //
        string[] AStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
        {
            if (sItem[0] == 'A')
                return true;
            else
                return false;
        });
        Console.WriteLine("----- Strings starting with letter 'A' -----");
        foreach (string s in AStrings)
        {
            Console.WriteLine(s);
        }

        // get an array of string items in the collection that start
        // with letter 'T'
        //
        string[] TStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
        {
            if (sItem[0] == 'T')
                return true;
            else
                return false;
        });
        Console.WriteLine("----- Strings starting with letter 'T' -----");
        foreach (string s in TStrings)
        {
            Console.WriteLine(s);
        }
    }
}

As shown in the above sample, we were able to define the criteria with in-line code blocks instead of defining a new method to represent each criteria. Truly speaking, using such inline code may look natural and avoid defining new methods, but if this technique is used for larger inline code blocks, then the code soon becomes unmanageable and may lead to duplications. So, be selective in using methods vs. inline anonymous methods as delegates/event handlers.

Now, this is the basics of anonymous methods. The rest of the article deals with how anonymous methods work internally in different scenarios. Understanding how anonymous methods are implemented and work internally is important for their correct usage. Else, the results of your code using anonymous methods will look unpredictable.

2. Static data member usage with anonymous methods

Anonymous methods always start with a delegate keyword, followed by parameters to be used inside the method and the method body itself. As seen from the above code sample, users need not specify the return type of the anonymous method. It is inferred from the return statement within the method body. The .NET CLR cannot execute free flowing code blocks like anonymous methods. CLR requires that every method it executes is part of a type and should be a static method or instance method. So when you write anonymous methods in a class code and compile the code, the C# compiler silently creates a static or instance method within the same class where you defined the anonymous method. So anonymous methods are just a convenient syntax for defining your own methods inside the class to pass to delegates (delegate handlers/event handlers).

When you compile the above sample, the C# compiler creates two private static methods inside the class 'Program', where we defined the anonymous methods. It then replaces the anonymous methods with the address of those static methods. How the compiler decides to create static methods or instance methods depends on the usage of the static or instance data members of the class within which the anonymous methods are defined. In our sample, we are not using any data member of the class 'Program', so the C# compiler creates a static method to encapsulate the code of our anonymous methods as it would be efficient to invoke a static method over an instance method. Below is the ILDASM view of the 'Program' class for the sample assembly. The highlighted portions show the new static methods that are added silently by the C# compiler to the 'Program' class.

Anonymous Methods wrapped in static methods

If we had used any static data of the 'Program' class within the anonymous methods, the C# compiler would still create a static method within the 'Program' class to wrap the anonymous method.

3. Instance data member usage with anonymous methods

Let us define a new instance method in the 'Program' class of our sample that uses one of its instance data members. The code below shows the modifications to the sample:

public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
      // Instance Data Member test
        //
        Program p = new Program();
        for(int i=1;i<=5;i++)
            p.TestInstanceDataMembers();
    }

    public void TestInstanceDataMembers()
    {
        MyDelegate d = delegate 
    { 
        Console.WriteLine("Count: {0}",++m_iCount); 
    };
        d();
    }

    public int m_iCount = 0;
}

We defined a new instance method, TestInstanceDataMembers, in the 'Program' class that defines an anonymous method, which uses the instance data member, m_iCount, of the 'Program' class. When the sample is compiled, the C# compiler will create a private instance method to wrap the anonymous method defined within TestInstanceDataMembers. The C# compiler has to create an instance method because the method needs access to the instance data member of the 'Program' class. Below is the ILDASM view of the 'Program' class for the sample assembly. The selection in the image below shows the new private instance method that is added silently by the C# compiler to the 'Program' class.

Anonymous Methods wrapped in instance methods

4. Local variable usage with anonymous methods

By now, we have a basic understanding of how anonymous methods work and are internally implemented. Ultimately, C# creates private methods to wrap anonymous methods. And these method signatures match that of the delegate that they are being assigned to. Now, let's take a look at the code below:

public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        int iTemp = 100;
        MyDelegate dlg = delegate
        {
            Console.WriteLine(iTemp);
        };
        dlg();
    }
}

According to what we have learned about anonymous method till now, this code should not compile. Because we are not using any instance data members, the C# compiler should create a private static method in the 'Program' class to wrap this anonymous method. But how will the new method access the local variable? This leads us to believe that this code will not compile. But surprisingly, the C# compiler compiles this code without any errors or warnings. Also, when you execute this sample, the output prints the correct value of the variable iTemp on the console screen.

Let us enter the advanced world of anonymous methods. An anonymous method has the capability of encapsulating the values of the surrounding variables that are used inside its method body. This encapsulation applies to all the variables that are local to the method in which the anonymous method is defined. When the C# compiler identifies the usage of a local variable within the body of an anonymous method, it does the following:

  1. Create a new private class that is an inner class of the class where the anonymous method is defined.
  2. Create a public data member within the new class, with the same type and name as the local variable that is used in the anonymous method body.
  3. Create a public instance method within the new class that wraps the anonymous method.
  4. Replace the declaration of the local variable with the declaration of the new class. Create an instance of this new class in place of the declaration of the local variable.
  5. Replace the use of the local variable within the anonymous method body and outside the anonymous method, with the data member of the new class instance.
  6. Replace the anonymous method definition with the address of the instance method defined in the new class.

So during compilation, the code above will be transformed by the C# compiler as shown below:

public class Program
{
    private class InnerClass 
    { 
        private void InstanceMethod() 
        { 
            Console.WriteLine(iTemp);
        } 
        public int iTemp; 
    }
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        InnerClass localObject = new InnerClass();
        localObject.iTemp = 100;
        MyDelegate dlg = new MyDelegate(localObject.InstanceMethod);
    dlg();
    }
}

As shown in the above pseudo-code, the C# compiler generates a private inner class for the 'Program' class. The local variable used in the anonymous method is captured as an instance data member in the newly created inner class. And the anonymous method itself is wrapped in the instance method of the inner class. Finally, the instance method is used as a delegate handler in the Main method. This way, when the delegate is invoked, it will have the correct value for the local variable that is encapsulated in its anonymous method. The selection in the image below shows the new private inner class that is added silently by the C# compiler to the 'Program' class.

Anonymous Methods wrapped in instance methods

The local variables that are used in the anonymous methods have life outside the regular method in which they are used. This technique, in other languages, is popularly known as closures. Apart from the simple syntax convenience that anonymous methods provide, closures is one powerful technique that anonymous methods provide a developer. This technique allows the delegate handler code (anonymous method) access to the local variables within the regular method scope in which it is being defined. This allows out-of-band data, data other than the delegate parameters, to be passed on to the delegate, which can be used during its method execution. Without this technique, each delegate and its corresponding handler method has to declare parameters that represent the local contextual data, which may become un-manageable over time.

5. Scoping and local variable usage with anonymous methods

We discussed about the implementation of anonymous methods within the main scope of a method. When an anonymous method is defined within a nested scope, and individual scope level local variables are used inside the anonymous method, C# creates a private inner class for each scope. For instance, let scope 1 has local variable iTemp, and scope 2, which is the nested scope of scope 1, has a local variable jTemp. Let us define an anonymous method within scope 2 that uses local variables iTemp and jTemp from scope 1 and scope 2. The code below shows the sample as described above:

public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        MyDelegate dlg = null;
        int iTemp = 100;
        if (iTemp > 50)
        {
            int jTemp = 200;
            dlg = delegate
            {
                Console.WriteLine("iTemp: {0}, jTemp: {1}",iTemp,jTemp);
            };
        }
        dlg();
    }
}

When the above code is compiled, the C# compiler creates two inner classes within the 'Program' class. One inner class wraps the local variable iTemp as a public data member. The second inner class wraps the local variable in the nested scope, jTemp, as a public data member, and wraps the anonymous method within the same nested scope as the public instance method. Below is the pseudo-code generated by the C# compiler for the above code:

Collapse
public class Program
{
    // Class wrapping local variable 'iTemp' from the
    // outer scope
    //
    private class InnerClassScope1 
    { 
        public int iTemp; 
    }
    // Class wrapping local variable 'jTemp' from the
    // inner scope and anonymous method
    //
    private class InnerClassScope2
    {
        public void InstanceMethod()
        {
            Console.WriteLine("iTemp: {0}, jTemp: {1}", 
                              localObjectScope1.iTemp, jTemp);
        }
        public InnerClassScope1 localObjectScope1;
        public int jTemp;
    }

    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        MyDelegate dlg = null;
        InnerClassScope1 localObject1 = new InnerClassScope1();
        localObject1.iTemp = 100;
        if (localObject1.iTemp > 50)
        {
            InnerClassScope2 localObject2 = new InnerClassScope2();
            localObject2.localObjectScope1 = localObject1;
            localObject2.jTemp = 200;
            dlg = new MyDelegate(localObject2.InstanceMethod);
        }
        dlg();
    }
}

As shown in the above code, the inner class that wraps the anonymous method will have objects for all the inner classes that represent the outer scope local variables, which are used in its anonymous method, as public data members. The below image shows the ILDASM view of the inner classes that are silently created by the C# compiler:

6. Local variable usage with anonymous methods within loop control structures

The encapsulation of local variables into class data members has an interesting but dangerous side effect when dealing with loop control structures. Let us take a look at the code shown below:

public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        MyDelegate d = null;
        for (int i = 1; i <= 5; i++)
        {
            MyDelegate tempD = delegate
            {
                Console.WriteLine(i);
            };
            d += tempD;
        }
        d();
    }
}

What will be the output when the above code is run? Our intention is to capture the loop counter variable 'i' in our anonymous method and display it. Our expected output should be as shown below:

1
2
3
4
5

But if you run the above code, the output will be as follows:

6
6
6
6
6

If we carefully recall our knowledge of the inner workings of anonymous methods, I mentioned that any local variable captured within the anonymous method would be replaced by an instance data member of a newly created inner class for that scope. For the loop control variable, the scope is the scope containing the for loop, which is the main method body shown in the above sample code. So when this code is compiled, the C# compiler generates the code that creates an instance of the inner class, wrapping the anonymous method and the loop counter variable, outside the for loop. And the data member of this inner class instance, representing the loop counter variable, will be used in-place of the original loop counter variable used for looping and also within the anonymous method. So the data member from the same instance of the inner class is used for looping and also within the instance method that wraps the anonymous method. As a result when the loop is completed, the instance data member would have incremented six times. A very important note here is that, though the loop ends after five iterations, the loop counter variable is incremented six times by the time it comes out of the loop control structure. Since this loop control variable is an instance data member, the sixth increment that triggers the loop termination condition is preserved within the loop counter variable. Since a method of the same instance is used as a delegate handler for the anonymous method, when finally the delegate is invoked, all the instances of the delegate will be pointing to the same instance, and will display the same value for the data member, which is 6. This is the dangerous side effect that I mentioned in the beginning of this section.

To overcome this issue and achieve the expected results, the anonymous method should capture a local variable within the scope of the for loop, which will have the same value of the loop counter variable. This can be achieved by changing the sample code as shown below:

public class Program
{
    public delegate void MyDelegate();
    public static void Main(string[] args)
    {
        MyDelegate d = null;
        for (int i = 1; i <= 5; i++)
        {
            int k = i;
            MyDelegate tempD = delegate
            {
                Console.WriteLine(k);
            };
            d += tempD;
        }
        d();
    }
}

When you run the above code sample, the output would be as expected, i.e.:

1
2
3
4
5

The reason is that, the C# compiler would create the instance of the inner class wrapping the local variable 'k' for each iteration of the for loop. And the method wrapping the anonymous method on this per loop iteration instance is used as a delegate handler.

7. Summary

Anonymous methods are a very useful and powerful addition to C# 2.0 language. Apart from introducing some syntactic sugar to the delegate declaration and usage, Microsoft has gone to great lengths in making the anonymous method code mix naturally into the containing method body, including access to the local variables within the scope of the containing method definition.

Finally, I hope that this article provides C# developers with insight required to utilize anonymous methods correctly and intelligently.

Anonymous Methods Part I

 

The implementation of anonymous methods in C# and its consequences (part 1)

You may not even have realized that there are two types of anonymous methods. I'll call them the easy kind and the hard kind, not because they're actually easy and hard for you the programmer, but because they are easy and hard for the compiler.

The easy kind is the anonymous method that doesn't use any local variables from its lexically-enclosing method. These are anonymous methods that could have been their own separate member functions; all the anonymization does is save you the trouble of coming up with names for them:

class MyClass1 {
 int v = 0;
 delegate void MyDelegate(string s);

 MyDelegate MemberFunc()
 {
  int i = 1;
  return delegate(string s) {
          System.Console.WriteLine(s);
         };
  }
}

This particular anonymous method doesn't access any MyClass1 members, nor does it access the local variables of the MemberFunc function; therefore, it can be converted to a static method of the MyClass1 class:

class MyClass1_converted {
 int v = 0;
 delegate void MyDelegate(string s);

 // Autogenerated by the compiler
 static void __AnonymousMethod$0(string s)
 {
  System.Console.WriteLine(s);
 }

 MyDelegate MemberFunc()
 {
  int i = 1;
  return __AnonymousMethod$0;
  // which is in turn shorthand for
  // return new MyDelegate(MyClass1.__AnonymousMethod$0);
  }
}

All the compiler did was give your anonymous methods a name and use that name in place of the "delegate (...) { ... }". (Note that all compiler-generated names I use here are purely illustrative. The actual compiler-generated name will be something different.)

On the other hand, if your anonymous method used the this parameter, then that makes it an instance method instead of a static method:

class MyClass2 {
 int v = 0;
 delegate void MyDelegate(string s);

 MyDelegate MemberFunc()
 {
  int i = 1;
  return delegate(string s) {
          System.Console.WriteLine("{0} {1}", v, s);
         };
  }
}

The anonymous method in MyClass2 uses the this keyword implicitly (to access the member variable v). Therefore, the conversion is to an instance member rather than to a static member.

class MyClass2_converted {
 int v = 0;
 delegate void MyDelegate(string s);

 // Autogenerated by the compiler
 void __AnonymousMethod$0(string s)
 {
  System.Console.WriteLine("{0} {1}", v, s);
 }

 MyDelegate MemberFunc()
 {
  int i = 1;
  return this.__AnonymousMethod$0;
  // which is in turn shorthand for
  // return new MyDelegate(this.__AnonymousMethod$0);
  }
}

So far, we've only dealt with the easy cases. The transformation is local and not particularly complicated. These are the sorts of transformations you could make yourself without too much difficulty in the absence of anonymous methods.

The hard case is where things get interesting. The body of an anonymous method is permitted to access the local variables of its lexically-enclosing method, in which case the compiler needs to keep those variables alive so that the body of your anonymous method can access them. Here's a sample anonymous method that accesses local variables from its lexically-enclosing method:

class MyClass3 {
 int v = 0;
 delegate void MyDelegate(string s);

 MyDelegate MemberFunc()
 {
  int i = 1;
  return delegate(string s) {
          System.Console.WriteLine("{0} {1} {2}", i++, v, s);
         };
  }
}

In this example, the anonymous method prints "1 v s" the first time it is called, then "2 v s" the second time it is called, and so on, with the integer increasing by one. (And where v s are the current values of v and s, of course.) This happens because the i variable that the anonymous method is accessing is the same one each time, and it's the same i that the MemberFunc method was using, too. If the function were rewritten as

class MyClass4 {
 int v = 0;
 delegate void MyDelegate(string s);

 MyDelegate MemberFunc()
 {
  int i = 0;
  MyDelegate d = delegate(string s) {
          System.Console.WriteLine("{0} {1} {2}", i++, v, s);
         };
  i = 1;
  return d;
  }
}

the behavior would be the same as in MyClass3. The creation of the delegate from the anonymous method does not make a copy of the i variable; changes to the i variable in the MemberFunc are visible to the anonymous method because both are accessing the same variable.

When faced with this "hard" type of anonymous method, wherein variables are shared with the lexically-enclosing method, the compiler generates a helper class:

class MyClass3_converted {
 int v = 0;
 delegate void MyDelegate(string s);

 // Autogenerated by the compiler
 class __AnonymousClass$0 {
  MyClass this$0;
  int i;
  public void __AnonymousMethod$0(string s)
  {
    System.Console.WriteLine("{0} {1} {2}", i++, this$0.v, s);
  }
 }

 MyDelegate MemberFunc()
 {
  __AnonymousClass$0 locals$ = new __AnonymousClass$0();
  locals$.this$0 = this;
  locals$.i = 0;
  return locals$.__AnonymousMethod$0;
  // which is in turn shorthand for
  // return new MyDelegate(locals$.__AnonymousMethod$0);
  }
}

Wow, there was a lot of rewriting this time. A helper class was created to contain the local variables that were shared between the MemberFunc function and the anonymous method (in this case, just the variable i), as well as the hidden this parameter (which I have called this$). In the MemberFunc function, access to that shared variable is done through this anonymous class, and the anonymous method that you wrote is an anonymous method on the anonymous class.

Notice that the assignment to i in MemberFunc modifies the copy inside locals$, which is the same object that the anonymous method will be using when it runs. That's why it prints "1 v s" the first time: The value had already been changed to 1 by the time the delegate ran for the first time.

Those who have done a good amount of C++ programming (or C# 1.0 programming) are well familiar with this technique, since C++ callbacks typically are given only one context variable; that context variable is usually a pointer to a larger structure that contains all the complex context you really want to operate on. C# 1.0 programmers went through a similar exercise. The "hard" type of anonymous method provides syntactic sugar that saves you the hassle of having to declare and manage the helper class.

If you thought about it some, you'd have realized that the way it's done is pretty much the only way it could have been done. It turns out that most computer programming doesn't consist of being clever or making hard decisions. You just have one kernel of an idea ("hey let's have anonymous methods") and then the rest is just doing what has to be done, no actual decisions needed. You just do the obvious thing. Most programming consists of just doing the obvious thing.

Okay, so that's a quick introduction to the implementation of anonymous methods in C#. Mind you, this information isn't just for your personal edification. It's actually important that you understand how these works (and not just treat it as "magic"), because lack of said understanding can lead to subtle programming errors. We'll look at those types of errors over the next few days.

22 junio

What is SCRUM

·         Scrum is an iterative, incremental process for developing any product or managing any work. It produces a potentially shippable set of functionality at the end of every sprint (iteration). It's attributes are:

a)      Scrum is an agile process to manage and control development work.

b)      Scrum is a team-based approach to iteratively, incrementally develop systems and products when requirements are rapidly changing

c)      Scrum is a process that controls the chaos of conflicting interests and needs.

d)     Scrum is a way to improve communications and maximize co-operation.

e)      Scrum is a way to detect and cause the removal of anything that gets in the way of developing and delivering products.

f)       Scrum is a way to maximize productivity.

g)      Scrum is scalable from single projects to entire organizations. Scrum has controlled and organized development and implementation for multiple interrelated products and projects with over a thousand developers and implementers.

Scrum is a way for everyone to feel good about their job, their contributions, and that they have done the very best they possibly could.

 

Referenced from Prakash J webblog

Videos & Podcasts on Microsoft technologies

Videos, Podcasts on Microsoft Technologies

I have recently prepared a list of Videos, Podcasts sites on Microsoft Technologies known to me. Add up the sites you know

.NET Rocks - .NET Rocks! is twice a week talk show for anyone interested in programming on the Microsoft .NET platform. The shows range from introductory information to hardcore geekiness. The show is hosted by CarlFranklin & Richard Campbell. The best show by far in the .NET World. Check out the shows Archive.

DNRTV - Once again the show is hosted by Carl Franklin dnrTv is a fusion of a training video and an interview show. Every week carl interviews a guest on technology, while the guest acutually demonstrating(Coding live) on the technology. Great show which helps you to kickstart new technologies. Check out the Archive page for list of shows.

HanselMinutes - Hanselminutes is a weekly audio talk show with noted web developer and technologist Scott Hanselman and hosted by once again Carl Franklin. Scott discusses utilities and tools, gives practical how-to advice, and discusses ASP.NET or Windows issues and workarounds. Scott Hanselman's has an excellent blog which is very resourceful to any one in .NET World. Check out the previous shows.

Channel9 - Channel9 is a great place where microsoft host videos with its employees about the coolest things they are working on inside Microsoft. The interviews are in converstion style, with great hosts like charles, Rory they are very interesting too. Its always interesting to hear about the technology, from some one who is actually part of developing it. Check this place regularly to know whats new from microsoft.

ArCast.net & ArCast.TV - Hosted by RonJacobs, the shows discuss about latest trends in architecture, with new products and technologies evolving. Ron interviews guests from product teams, Microsoft customers and partners to through light on what's happening around and how software architecture is evovling. Ron has great blog and website

Microsoft Webcasts - This is central repository of webcasts on microsoft technologies. Microsoft provides tons of webcasts on different technologies which are a great place to start if you want to learn any new technology. You can view them online and most of them are downloadable too. The content available here covers most of the topics in microsoft world.
Update: Microsoft has also added virtual labs under this section. Users can browse, download/listen to on-demand webcasts and can also try the same on virtual labs.

The .NET show - The original .NET show hosted by Robert Hess and produced by microsoft. The show primarly focuses on whats new and what would be the next big thing in .NET world. The show is usually monthly, though sometimes the gap between shows is even wider. The show has a great list of archives which would be of interest to .NET world.

ASPNet PodCast - Asp Net podcast is targeted at developers in ASP.NET and SQLServer the show is hosted by asp.net. Contains some good podcasts on various topics in ASP.NET. Check out Wally's Blog for previous shows

SqlDownUnder - Hosted by GregLow, this show is all about SQL Server. It has some interesting shows with Dr Jim Gray, Bob Beauchemin, Kimberly Tripp

Polymorphic Podcast - Hosted by Craig Shoemaker, This is one of the good shows around on .NET platform. The show priamraly focus on Object Oriented Development, Architecture, Best Practices in .NET

RunAsRadio - Hosted by Richard Campbell, Greg Hughes RunAsRadio is launched recently on April 11, 2007. RunAs Radio is a weekly Internet Audio Talk Show for IT Professionals working with Microsoft products. The full range of IT topics is covered from a Microsoft-centric viewpoint.

Grok Talks - This contains a list of 36 videos each done by a Microsoft Regional Director shot during tech-ed 2005. These talks are typically 10-15 minutes and are fun to watch. Go check out the cools stuff.

MSDN TV - MSDN TV was a a show with short video, appearing weekly, featuring useful technology tips and insights from the folks behind the scenes at Microsoft. The last episode of the show was posted on 14th September 2006. Though the show is no longer active, check out the archive the great shows.

 

18 junio

Bdotnet Session 16th Jun 2007

Security Session:

 

1.       For input and data validation use regular expressions .One can get good help from http://regexlib.com/default.aspx

 

2.      For protecting viewstate use HMACs. Referred article : http://channel9.msdn.com/wiki/default.aspx/Channel9.ASPNET2SecurityFAQ0029

 

3.       He gave session by referring this article:

http://msdn2.microsoft.com/en-us/library/ms998258.aspx

 

4.    Microsoft Anti-Cross Site Scripting Library V1.0

 

http://www.microsoft.com/downloads/details.aspx?familyid=9a2b9c92-7ad9-496c-9a89-af08de2e5982&displaylang=en

 

DataBase migration tool:

 

Microsoft SQL Server Migration Assistant (SSMA)

 

15 junio

Microsoft ESrum

"Many development teams inside Microsoft are now using the agile methodology for software development and had been looking for a way to track their daily progress. http://blogs.msdn.com/somasegar/archive/2007/06/13/escrum-1-0.aspx

eScrum 1.0 ( updated June 23,2007)  download it from here - 
http://www.microsoft.com/downloads/details.aspx?FamilyID=55a4bde6-10a7-4c41-9938-f388c1ed15e9&displaylang=en

14 junio

c# 3.5 new features

http://dotnetwithme.blogspot.com/2007/05/what-new-in-net-35.html

What's New in .NET 3.5

ASP.NET

  • Support for enabling existing ASP.NET 2.0 pages for AJAX
  • Creation of ASMX & WCF based web services and consuming them from AJAX Library
  • ASP.NET server side application services like authentication, roles management exposed as web services
  • ASP.NET Merge Tool - a new tool for merging pre-compiled assemblies
  • New ListView control which supports edit, insert, delete, sorting & paging
  • ASP.NET integrated with core IIS 7.0 which makes ASP.NET services like authentication & caching available for other content types also.
  • Microsoft AJAX Library to support AJAX based web development

Base Classes & CLR

  • Support for CSharp 3.0 including LINQ.
  • HashSet : A high performance collection of type set.
  • Time Zone Improvements : to develop applications which operate in multiple time zones
  • Minor Improvements in Threading, Reflection and controlling the GC behavior

Others

  • Client Application Services : All windows based application to use ASP.NET login, roles and profile services hosted on central server.
  • Occasionally Connected Services (OCS) : keeps windows application's local and remote data in sync.
  • 'Silver' : code name for a new technology which unifies WF and WCF
  • WCF Syndication : WCF services exposing syndication feeds. Supports Atom 1.0 and RSS 2.0

C#3.0 features

* What's New in CSharp 3.0

Here is a point wise summary of features introduced newly in C# 3.0

http://dotnetwithme.blogspot.com/2007/05/what-new-in-csharp-30.html

Implicitly Typed Local Variables

  • Local variables can be declared as type ‘var’ which means compiler to determine the actual type based on the data by which its is initialized.
  • var i = 10; // i is created of type int
  • var name = “MyName” ; // name is created of type string
  • can only be used when declared and initialized in same statement.
  • Cannot be initialized to null.
  • Cannot be used as class members.
  • Mostly used to store anonymous types as in LINQ based programming.

Object & Collection Initializers

  • Allow assigning values to any accessible members or properties of a type at the time of initiation without invoking the constructor with parameters.
  • The default constructor gets executed before assigning the values.
  • E.g. Coordinate c1 = new Coordinate {x=1 , y=2};
  • Used in LINQ query expressions along with anonymous types.
  • Collection Initializers use Object Initializers to specify multiple elements of collection without calling Add method multiple times.

Extension Methods

  • Allows adding new methods to existing types without modifying the existing type.
  • Are special kind of static methods but are called as if they are instance methods.
  • The first parameter passed to Extension methods specifies to which type they operate on preceded by ‘this’ keyword.
  • They cannot access the private variables of type which they are extending.
  • Extension Methods need to defined in a non-nested and non-generic static class.
  • Instance methods take priority over extension methods in case they have same signature.

Anonymous Types

  • Are of class types which can have only public read-only properties as their members. No other class members like methods are allowed.
  • They are of reference types and are derived from ‘Object’ class.
  • Internally compiler gives them the name but its not accessible by application code.
  • They have a method scope.
  • Can be initiated directly e.g. new { property1=1, property2=”Hello World”};

Lambda Expressions

  • Very similar to anonymous methods introduced in C# 2.0.
  • Its an inline expression or statement block which can be used to pass arguments to method call or assign value to delegate.
  • All lambda expression use lambda operator => where the left side denotes result and right contains statement block or expression.

Auto-Implemented Properties

  • Helps in simplifying property declaration in cases where there is no custom logic required in accessors methods.
  • E.g. public int Price {get; set;};
  • Internally compiler creates an anonymous field for assigning values.

Hacking Site

http://www.iimi-iris.com/iris/irising/klueLESS

Getting master pages things in Content pages

Events in Master page / Content Pages

When you work with master pages and content pages, both can use the same events (such as Page_Load).Be sure you know which events come before others. You are bringing two classes together to create a singlepage class, and a specific order is required. When an end user requests a content page in the browser, the event ordering is as follows:

Master page child controls initialization: All server controls contained within the master page are first initialized.
Content page child controls initialization: All server controls contained in the content page are initialized.
Master page initialization: The master page itself is initialized.
Content page initialization: The content page is initialized.
Content page load: The content page is loaded (this is the Page_Load event followed by the Page_LoadComplete event).
Master page load: The master page is loaded (this is also the Page_Load event).
Master page child controls load: The server controls on the master page are loaded onto the page.
Content page child controls load: The server controls on the content page are loaded onto the page.

How to access master page controls from content pages

Consider the following scenario

Master Page

<%@ master language="C#" %>
<html>
<head id="Head1" runat="server">
<title>Master Page</title>
</head>
<body>
<form id="Form1" runat="server">
<table id="header" style="WIDTH: 100%; HEIGHT:80px" cellspacing="1" cellpadding="1" border="1">
<tr>
<td width="100%" style="TEXT-ALIGN: center">
<asp:label runat="server" id="Header">
This is the default header in the MasterPage</asp:label>
</td>
</tr>
</table>
-------------------------------------------------------------------------------------

Content Page

<%@ page language="C#" master="~/ExposeHeader.master" %>
<script runat="server">
void Page_Load(object sender, System.EventArgs e)
{
Label headerLabel = (Label)
Master.FindControl("Header"); // Header is my master page label id.
headerLabel.Text = "This label content is set through the Page_Load event of the child page";
}

</script>

Here I am using Master.FindControl with the master page control's id (The identifier for the control to be found). Find control will search the current naming container for a server control with the specified id parameter. It returns the specified control or null if the specified control does not exist.