Wednesday, September 29, 2010

5 things I would like to see in C# 5.0

C# 4.0 is out with a lots of new specs this year. Few of them are really good, like the support of Task level Parallelism, Dynamic behavior of objects etc. So C# is very rich now in all respect. But this is not the end of everything. As I did introduced few old but Unknown C# topics, I would also love to explore new things that comes up with C#. So lets discuss a few things which I would love to have.

There is already a buzz around on C# 5.0 specifications in forums. A notable discussion around should be some threads like

What features you want to see in C# 5.0
C# language speculation 4.5 /5.0

etc. These community links are really great where a lots of people voted for new language specs, while quite a few things are already would be in process like :

Binding Operators

Binding Operators may be C# 5.0. The support for Binding on .net objects are awesome. I came to know this from Chris on his post where he speaks how Binding operators looks like long ago. The delphi assignment operator := is now been used in this purpose. :=:  would be used for two way binding.  Thus

comboBox1.Text :=: textBox1.Text; 

means there would be two way binding between the properties so that when ComboBox1.Text changes its Text it will automatically change the value of Textbox1.Text.
Binding is actually not a new thing to the system. In WPF we already have Binding in place, but for that we need the properties to have implemented from INotifyPropertyChanged. So it is not in the language, the WPF objects are doing this internally by handling the PropertyChanged event on the object. But if that is included as an operator it would be a cool feature to add on.

Monday, September 27, 2010

WPF Tutorial : Styles, Triggers and Animations : 7

Introduction

Perhaps the most interesting and most important feature for any WPF application is Styling. Styling means defining styles for controls, and store in reusable ResourceDictionaries and hence forth, it could be used later on by calling its name. Styles in WPF could be well compared with CSS styles. They are both similar in most of the cases, while the former extends the feature allowing most of the features which WPF have. In this article I will discuss mostly how you could use Style in your WPF application to enhance the Rich experience of your UI.

Style

WPF exposes a property Style for every Control. If you look into the object Hierarchy, the Style is basically a property which exposes an object of Style in FrameworkElement. So each object can associate it and define custom setters to manipulate the basic look and feel of a control.



Clearly, the above diagram shows the association of Style in FrameworkElement and from the object hierarchy every control somehow inherits from FrameworkElement and hence style will be available to it. Style is also a WPF object which is inherited form DispatcherObject which helps in setting different properties of your UI Element.


How Style differs from Theme  ?


Before we move further into Styles lets talk about Themes. Theme is totally different from Styles. Themes are defined at OS level, or more precisely a Theme can take part of delivering styles all over the Desktop while Styles are restricted to the contextual area of a WPF window. WPF are capable of retrieving the color scheme which is defined in OS level. Say for instance, if you do not define style for your application, the elements in the screen will automatically get styles from external environment. Say for instance, in XP if you change the theme to something else you would see that the buttons, TextBox on your WPF window will change its color instantly. You can even set the Theme which the application would use programmatically from your code.

What about Templates ?


Every control defines a ControlTemplate. A ControlTemplate defines the overall structure of the control. As I have already told you, say for instance you have a Button. Button is a control that is made up of more than one control. It would have a ContentPresenter which writes the Text over the control, it would have a Rectangle which keeps the boundary of the Button etc. So Template is a special property associated with a Control which specifies how the control will look like structurally. We can easily define our Template and change the overall structure of a control.

Templates are basically of 2 types :
  1. ControlTemplate
  2. DataTemplate

ControlTemplate defines the structure of the Control. It means say for instance, you define the ControlTemplate for a ComboBox. So from ControlTemplate you can easily change the Button associated with the ComboBox which opens the DropDown, you can change the structure of the TextBox, the Popup etc. So ControlTemplate allows you to change the overall structure of the Control.



Click To Read Entire Article

Saturday, September 25, 2010

Progress Streamed File download and Upload with Resume facility


For distributed applications, WCF is the most easy and rich component.I like to use WCF as it is very easy to implement and also provides built in functions to handle with Complex problems. One of such interesting thing that I found in WCF is the support for Streaming while sending data from the service.

WCF allows you to send Byte streams through the communication channel or even allows you to implement a service that might take the stream start location from the service call and send the stream from a certain location. It allows you to use normal HttpBinding to support streams which is capable download or upload in connected Client - Server architecture. Hence there will be not timeouts for sending or receiving large files. In this article I will show you how you could use Streaming to ensure your files are downloaded or uploaded correctly.

Once I read Demitris solution for File upload and download it made me very easy to adjust the code and enhance it further with more flexibilities.

Lets first create the service step by step :

Service

  1. Create a Service Application and name it as WCFCommunicationService
  2. The first thing that you need to do in order to create a service is ServiceContract. So once you create a Service Library, you need to delete the existing Service1 and IService1 files from the solution and add a new Interface. 
  3. Create Two method, one for FileDownload and another for FileUpload. Lets see how the service definition looks like :
Contract

[ServiceContract]
public interface IFileTransferLibrary
{

    [OperationContract()]
    void UploadFile(ResponseFile request);

    [OperationContract]
    ResponseFile DownloadFile(RequestFile request);
}

The Contract defines the methods that are exposed to outside. The ServiceContract defines the interface which will have the members which are available to outside. The OperationContract identifies the exposed members. In the above contract the IFileTransferLibrary has two methods, UploadFile which takes an object of ResponseFile and DownloadFile which returns an object of ResponseFile.

[MessageContract]
public class ResponseFile : IDisposable
{
    [MessageHeader]
    public string FileName;

    [MessageHeader]
    public long Length;

    [MessageBodyMember]
    public System.IO.Stream FileByteStream;

    [MessageHeader]
    public long byteStart = 0;

    public void Dispose()
    {
        if (FileByteStream != null)
        {
            FileByteStream.Close();
            FileByteStream = null;
        }
    }
}

[MessageContract]
public class RequestFile
{
    [MessageBodyMember]
    public string FileName;

    [MessageBodyMember]
    public long byteStart = 0;
}

If you see the classes RequestFile and ResponseFile, you will see that I have used MessageContract instead of DataContract for my complex types. It is important. AS I am going to send the data streamed to the client, I need to send the data into packets. DataContract will send the whole object at a time while Messagecontract sends them into small Messages.It is also important to note that I have used IDisposable for ResponseFile to ensure that the Stream is closed whenever the connection is terminated.

Another important note is you need to use Stream as MessageBodyMember. The stream data will always transferred in MessageBody and you cannot add any other member into it. Thus you can see I have put all other members as MessageHeader.

For Both UploadFile and DownloadFile the Stream is taken from the ResponseFile object. The byteStart element of RequestFile ensures from where the the downloading should start and hence helps in Resuming a half downloaded file.  Lets see how to implement this :

public ResponseFile DownloadFile(RequestFile request)
{
    ResponseFile result = new ResponseFile();

    FileStream stream = this.GetFileStream(Path.GetFullPath(request.FileName));
    stream.Seek(request.byteStart, SeekOrigin.Begin);
    result.FileName = request.FileName;
    result.Length = stream.Length;
    result.FileByteStream = stream;
    return result;

}
private FileStream GetFileStream(string filePath)
{
    FileInfo fileInfo = new FileInfo(filePath);

    if (!fileInfo.Exists)
        throw new FileNotFoundException("File not found");

    return new FileStream(filePath, FileMode.Open, FileAccess.Read);
}
public void UploadFile(ResponseFile request)
{
           
    string filePath = Path.GetFullPath(request.FileName);
            
    int chunkSize = 2048;
    byte[] buffer = new byte[chunkSize];

    using (FileStream stream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
    {
        do
        {
            int readbyte = request.FileByteStream.Read(buffer, 0, chunkSize);
            if (readbyte == 0) break;

            stream.Write(buffer, 0, readbyte);
        } while (true);
        stream.Close();
    }
}

If you see the code, you can see how I have used byteStart to start sending Bytes for the file. This ensures the file download to have resume facility. You can also implement the same for UploadFile too.

Download FileTransfer Sample - 161KB

Sunday, September 19, 2010

Online Session on ASP.NET

I have just covered an Online session on "ASP.NET 4.0 in depth features" with Abhijit Jana for DotNetFunda.Com. If you were already there for the session, I hearty congratulate you people for your co-operation and also like you to join us in the concluding part of the session which will be declared later in the day.

In the session :

Things that we have covered already :
  1. Basic Introduction of ASP.NET 4.0 Features
  2. Visual Studio Enhancement Session
  3. Server Control Enhancements
  4. Search Engine Optimization
The session is not an end, We have lots of things to cover and probably we will fix a time later in the next week and update you the same. Stay Tune.

You can download Sample Applications that I showed : 

1. Routing Demo Application
2. Meta Tags and Parmanent Redirections

The sample video :

Download PPT, Sample Code & Video1
Download PPT, Sample Code & Video2

You can download the sample application and also run the PPT and Video from the link above. (Let me know if the link goes down.)

The Grayed items are already discussed, while others will be taken in the next session which will be announced shortly.


For reference Reading :

ASP.NET 4.0 WhitePapers

Thanks for being a part of the session.
Hope to see you soon.

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.

    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 !!!