Wednesday, September 15, 2010

How to create a WCF service without Visual Studio

WCF is the first step in building a truly service oriented application for you. It is the most important when working with distributed architecture. The sophisticated design of WCF made me think of using it always when I need any Web service to be installed in the server. Visual Studio is capable of creating its own configuration settings that helps in developing our application with ease. But what if you don’t have Visual Studio? In this post I am going to implement one of the most basic WCF service without using Visual Studio and show you how to interact with the service. Lets do it step by step:

Server Side

Steps to create the Service definition (Contract):

  1. Open Notepad and add namespace System and System.ServiceModel. We need ServiceModel to specify a WCF service
  2. For WCF service we need to create an interface which will act as a proxy to the client.  From the client, we need to replicate the proxy object and build the same interface again. After we declare the Interface we mark the Interface with ServiceContract, and the method to be exposed to outside using OperationContract.
  3. Next we create a concrete class for the same to define the class implementing the interface.
So our server is Ready.

[ServiceContract]
public interface IOperationSimpleWCF
{
    [OperationContract]
    string MySimpleMethod(string inputText);
}

public class OperationSampleWCF : IOperationSimpleWCF
{
    public string MySimpleMethod(string inputText)
    {
        Console.WriteLine("Message Received : {0}", inputText);
        Console.WriteLine(OperationContext.Current.RequestContext.RequestMessage.ToString());
        return string.Format("Message from Server {0}", inputText);
    }
}


Steps to host the service (Address , Binding):

To host the service in the server you need to know three inputs:

  1. Binding : This indicates how the service will be hosted.  For  basic soap operation with no security we need HttpBinding. We can also use other bindings as well.
  2. Address : Represents the location to host the service. When the service is hosted you can specify the qualified service path where the service will be hosted.
  3. Host the service using ServiceHost and Open the connection.
Download Sample Code - 47KB


Tuesday, September 14, 2010

Partial Methods - An Uncommon Note

I think most of the people working in C# must know how Partial classes work. Partial classes allows you to divide your own class in one or more files but during runtime the files would be merged to produce a single coherent object. By this way the classes could be made very small and also easily maintainable.

The most important part of a Partial class is with designers. While you work in Visual Studio, you must have found a portion of code that is generated automatically by the designer. Designers creates a class which keeps on refreshing itself when certain modifications are made in the Designer itself. Partial classes allows you to create an alternate implementation of the same class so that the code you add to the class does not goes out when the Designer is refreshed.

Partial Methods are another new addition to .NET languages that allows you to declare / define the same method more than once. Generally Microsoft introduced the concept of Partial method to deal with Designer generated code and to allow reserving the name of a method that one needed to be implemented later in original classes. By this way, the Designer will not produce any warning without implementing the actual method, but will allow future developers to implement or write their own logic on the same method that is defined.


partial class MyPartialClass
{
    public void MyNormalMethod()
    {
        Console.WriteLine("Inside first Normal Method");
    }
    partial void MyPartialMethod(); //It is declared and will be defined later in another partial class
}

Let us suppose the MyPartialClass is generated by the designer. It declares the method MyPartialMethod which I have not been defined yet.

partial class MyPartialClass
{
    //public void MyNormalMethod()
    //{
    //    Console.WriteLine("Inside second Normal Method");
    //}
    partial void MyPartialMethod()
    {
        Console.WriteLine("Inside second Partial Method");
    }
}

In another implementation of MyPartialClass, I have defined the method MyPartialMethod which holds the actual implementation of the code. So if I create an object of MyPartialClass, it will hold both method MyNormalMethod and MyPartialMethod and when it is called it calls appropriately.

Another thing to note, the implementation of Partial method is not mandatory.  If you do not define the partial method in another partial class, it will eventually be eliminated completely in runtime IL.

Limitations of a Partial Method :

  1. Partial Method is by default private. Hence you can only call a partial method from within the partial class. 


    partial class MyPartialClass
    {
        public void MyNormalMethod()
        {
            Console.WriteLine("Inside first Normal Method");
            this.MyPartialMethod();
        }
        partial void MyPartialMethod(); //It is declared and will be defined later in another partial class
    }
    Thus even if you do not declare the method MyPartialMethod, you can even call it from within the class. During runtime, CLR will automatically call if it is implemented or will eliminate the call completely from the system.
  2. Partial Method needed to be declared inside a Partial class. A partial class is only capable of redefining the part later in another file. So it is essential to mark the class as partial as well when it have a partial method.
  3. Cannot be marked as extern.
  4. Must have a void return type and also cannot use out parameter as argument.
  5. Partial method does not allow to write as virtual, sealed, new, override or extern.

Since partial method is created to generate methods in designer, most of the designer highly using partial methods. Even though it  is very rarely used in real life, it would be worth if you know about it.  

For further reference:

C# 3.0 Partial Method - What Why and How

Thank you for reading my post.

    Sunday, September 12, 2010

    Marble Diagrams and Rx

    Today I am going to discuss how to draw Marble Diagrams. I just came across with it in Reactive Framework. In Channel 9 videos, Jeffrey Van Gogh shows how to get started with Rx. Ever since I look deep into it, I find it very interesting, and perhaps a new way of thinking or understanding for Asynchronous programming structure. Reactive Framework introduces a few operators, which you might apply to an Observable to get the resultant observable. The way to represent each of these attributes can be done using Marble Diagrams. 


    Before you start dealing with Reactive Framework, it is good to start with IObservable and IObserver. I have already introduced with these two interfaces which are the building block for the Reactive Framework. You can read these articles before going through with Marble Diagrams.




    How to create Marble Diagram. 


    Marble diagram is basically a way to represent the Rx operations. You may think a marble diagram to be a pictorial representation of different operators that is defined with Reactive Framework. Lets look how to create a Marble Diagram : 








    So in the sample image you can see we measure Time in X-Axis while operations on Y-axis. Say for instance, you have an Observable which is represented by the first horizontal line. The small circles represents OnNext calls of IObserver. If you know already read about Observable and Observer, you might already know that each Observer has OnNext method, which gets invoked whenever the observer changes its state.  Hence, in our case the observer invokes a function f() to get to the new State.  The | represents the OnComplete for the Observer. So after OnComplete, the Observer will stop observing states.





    We represents OnError using X in a marble diagram. In case of an Observable, OnError and OnComplete produces the end  point for the observer. So Here after executing the two OnNext if the Observer encounters with an Exception, OnError gets invoked and the Observer will terminate. 


    So on the first image, we execute the function f() to get the new state with the Buttom Line. Now on, I am going to create a few Marble Diagrams, to make your understanding clear. 

    SelectMany



    SelectMany is very easy to explain. Say you have two or more Observers. In this case, SelectMany will eventually invoke all the OnNext of each observer. 




     So if you have 3 observers, the SelectMany will produce Observer which aggregates all of them. 





    int[] collection = { 2, 5, 5, 6, 2, 4 };
    int[] collection2 = { 1, 4, 2, 1, 5, 6 };
    var ob1 = Observable.ToObservable(collection);
    var ob2 = Observable.ToObservable(collection2);
    
    
    var ob3 = ob1.SelectMany(ob2);
    
    //var ob3 = ob1.Select(r => r + 2);
    var disp = ob3.Subscribe(r => Console.WriteLine("OnNext : {0}", r.ToString()), 
                                r => Console.WriteLine("Error : {0}", r.ToString()), 
                                () => Console.WriteLine("Completed"));
                
    disp.Dispose();
    So the Observer will select from each of the Observer and get you the output.

    In case of an error, the final Observer will stop when first error of any Observer is encountered.

    SkipUntil / SkipWhile

    SkipWhile and SkipUntil works in opposite. Say for instance, you have two Observable. SkipUntil gives you OnNext for each of them until the OnNext from the other observer is received. On the contrary, SkipWhile will produce OnNext for the Observer while the OnNext from the second observer is Received. When the second observer is Complete or gives an error, the final observer will terminate in case of SkipWhile.






    So in the above diagrams, you can see While will bypass all the values until the second observer receives an entry.


    Further Reference

    To learn the operators of Marble Diagrams, you can see the latest Videos on Channel 9. Here is a few more Operators :
    I hope this will help you to understand the Marble Diagrams, and hope these will describe you some more operators of Rx Framework.

    Tuesday, September 7, 2010

    Taskbar with Window Maximized and WindowState to None in WPF

    Say you want your WPF  application to have no Title bar, and will maximized to Full Screen, what you first think of. Its the most easiest to do.

    1. Set WindowStyle to Maximized : By this the Window will not show up any title bar. The window style will be transformed to a Box with border in it. 
    2. Set WindowState to None :  By this the window will be maximized to the whole screen and will show only the window and nothing else..

    Oh.. Hold on ..Hold on... As I say, it hides the whole screen, it means it even will not show up the Taskbar or any external gadgets applied to your desktop if it is not set to Always on Top attribute to it.

    Yes, this is the problem that I faced recently, when people wanted me to show the TaskBar even though the application should be Maximized.

    Is it a Bug ? 

    If I am not wrong, WPF builds application based on the Screen Resolution. It produces DPI independent pixels. If you specify it to be full screen, it first gets the Resolution of the screen, and draws the pixel based on its own algorithm. Hence, when you specify it to Maximized, it takes up the whole screen, as otherwise some portion of the screen will be hidden outside the range of the boundary.

    When you restore a WPF screen, it will also recalculate the work area based on the distance between the resolution boundaries and resize itself accordingly. No do you think Microsoft should really have an alternative state which show up the Taskbar as it does with normal windows ? I think yes.

    The Solution

    As I needed to do this, I have just tried out few workarounds to this myself.

    Following Lester's Blog on this issue, I have to use

    private static System.IntPtr WindowProc(
            System.IntPtr hwnd,
            int msg,
            System.IntPtr wParam,
            System.IntPtr lParam,
            ref bool handled)
    {
        switch (msg)
        {
            case 0x0024:
                WmGetMinMaxInfo(hwnd, lParam);
                handled = true;
                break;
        }
    
        return (System.IntPtr)0;
    }
    
    private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
    {
                
        MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
    
        // Adjust the maximized size and position to fit the work area of the correct monitor
        int MONITOR_DEFAULTTONEAREST =0x00000002;
        System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
    
        if (monitor != System.IntPtr.Zero)
        {
                    
            MONITORINFO monitorInfo = new MONITORINFO();
            GetMonitorInfo(monitor, monitorInfo);
            RECT rcWorkArea = monitorInfo.rcWork;
            RECT rcMonitorArea = monitorInfo.rcMonitor;
            mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
            mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
            mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
            mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
        }
    
        Marshal.StructureToPtr(mmi, lParam, true);
    }

    The call to API WmGetMinMaxInfo gets you the size of Maximize window for the current desktop.

    [DllImport("user32")]
    internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO   lpmi);
    [DllImport("User32")]
    internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

    The call to GetMonitorInfo gets you a MONITORINFO object and if you see the code carefully it actually position the window in such a way that it absolutely resize itself to the height and width of the rectangular area.

    To call this method, I can use SourceInitialized event which will eventually be called whenever the WindowState is modified.

    void win_SourceInitialized(object sender, EventArgs e)
    {
        System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
        WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
    }

    Sounds good ?
    Oh.. Lets give another easier solution that I have used. Its very simple.

    Set properties for your window :

    WindowStyle="None"
    WindowState="Maximized"
    ResizeMode="NoResize"

    And go to your code and just resize your window based on PrimaryScreen width and height. Also make sure you do set the Left and Top of the window as well.

    this.Width = System.Windows.SystemParameters.WorkArea.Width;
    this.Height = System.Windows.SystemParameters.WorkArea.Height;
    this.Left = 0;
    this.Top = 0;
    this.WindowState = WindowState.Normal;

    Making WindowState.Normal will ensure that the default behaviour of the window is overridden and also makes the Taskbar Reappear.

    I have included my sample application :

    Have fun.

    Download Sample - 38KB

    .NET Community Session : ASP.NET 4.0 In - Depth

    I am going to speak on a Community Session Organized by DotNetFunda on ASP.NET 4.0 with Abhijit Jana.

    ASP.NET 4.0 comes with lots of new features that enhance the developers to deal with ASP.NET applications easily and also core functionality to deal with both server side and client side of an ASP.NET application. These changes makes ASP.NET 4.0 applications more effective than the existing ASP.NET applications.

    The Agenda for the Session :
    (Click to enlarge to Full Size)

    • What’s New in ASP.NET 4.0
    • Improvement in Visual Studio 2010 for web development
    • Empty Website project and Cleaner Web.Config
    • MetaKeyword and MetaDescription enhancements
    • Controlling ViewState mechanism 
    • Controlling ClientID generation for asp.net controls
    • CompressionEnabled Session
    • CSS Improvements and CSS Friendly Menu Control
    • ListView rendering mechanism, Enhancement in Listview control
    • Enhancement in RadioButtonList and CheckBoxList
    • SEO Friendly URL (Web Form Routing)
    • Permanent Redirection mechanism
    • Improvements in Code Expressions
    • Overview of Dynamic data
    • Caching mechanism (Output Caching, Object caching etc.)
    • ASP.NET Applications / Database deployment.
    • Q & A
    • Summary
    Speakers: Abhishek Sur & Abhijit Jana

    Scheduled Date: 19-Sep-2010 (Sunday )

    Scheduled Time: 2.00 PM to 4.30 PM

    Live meeting URL:  https://www.livemeeting.com/cc/mvp/

    Meeting ID:  Will be sent to your email id before the session scheduled date and time.

    Is Paid?: No, It’s FREE Session

    Is Registration required ? Yes . Please register here http://bit.ly/d6aVYM .

    Disclaimer : http://www.abhisheksur.com/p/disclaimer.html

    Monday, September 6, 2010

    Use of Expression Trees in .NET for Lambda Decomposition

    Expressions are the building block of any Lambda Expression. In C# 3.0, .NET framework has introduced a new technique to make use of Anonymous methods a better way. The "Little Gem" LINQ, uses Lambda expression extensively to invoke filter statements to IEnumerable objects and hence making the life for a programmer very easy. Simple lambda expressions like

    x => x<5 

    may come very handy as we do not need to define a method extensively for such a small purpose. C# also introduced a couple of Generic delegates like Func<...>, Action<...> etc. in Base Class Library which lets you to pass any type of argument to a method body. The one with Func are for methods which require something to return while ones with Action dont need to return anything.

    To learn more about LINQ please have a quick pick on my article on LINQ and Lambda Expressions.But if you have already read about the basics of LINQ, it is not all that is needed. Lambda expressions are cool and extensive use of Anonymous methods are truly awesome, but basically when I think of using Lambda Expression in my own application, I always think of extending the Lambda expressions a bit further so that I could use it dynamically during runtime and later on compile them to produce the actual anonymous delegates. In this article I will put forward the story of Linq and Lambda Expressions further and introduce you with Expression Trees and also show you to create Expression Trees dynamically during runtime.

    What is an Expression Tree?

    Simply speaking, an expression tree is nothing but the representation of a Lambda Expression in terms of .NET objects. The Expression is the main class that holds any expression in it and it lets us to divide the whole body of the Expression into smaller individual units. For instance : 

    Func<int, bool> mydelegate = x => x < 5;
    Expression<Func<int, bool>> myexpressiondelegate = x => x < 5;

    In the above code the delegate Func can take the expression x=>x<5 which represents an anonymous method that takes an integer argument and returns if the value is less than 5.
    Download Sample - 38 KB


    Saturday, September 4, 2010

    Notion of System.Nullable - A Look

    I love C# as a language. It has lots of flexibilities and hooks to turn around things that was impossible for other languages. One of such thing is the introduction of Nullable Types. In this post,  I will discuss how you could use Nullable to make sure your code works well for null values in Value Types.

    Why System.Nullable?

    You must already know, System.Nullable is the only structure that supports the storage of Null as a valid range of values. Generally in case of structures it cannot store null values in it. Say for instance :

    Int32 is a structure. When you specify
    int x;

    It will automatically assign 0 to x. This is same as
    int x = default(int);

    Generally structures always recursively call default to initialize the value of it. Say for instance :

    struct MyCustomStructure
    {
         public int m;
         public int n;
     }

    I have defined a custom structure MyCustomStructure. If you declare an object of it like :
    MyCustomStructure myobj;

    It will assign myobj to its default. You cannot assign null to myobj. The only way out to this situation is Nullable.

    MyCustomStructure myobj = null; //throws exception
    Nullable<MyCustomStructure> myobj = null; //works fine

    Hence you can see, you should always use Nullable for a structure if you want to store the value of null to a structure. For data centric applications, we generally need to keep a variable out of the scope of valid values so that the variable can have a value which might identify the value as nothing. Null is taken as nothing, but in case of normal structures it does not allow us to do that. If you store nothing to an integer, it will automatically initialize to 0. But for any application 0 might be a valid value. So you cannot exclude the 0 from the range of data. Hence you need Nullable to workaround this issue.

    Author's new book

    Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
    Grab it now !!!