Wednesday, May 29, 2013

WPF: TemplateBinding with ControlTemplate

Today I'll try to write bit on TemplateBinding and how to use it inside a ControlTemplate. TemplateBinding is a type of binding used mainly for template scenarios. Here I am not going to write more on it's theoretical aspect as what is TemplateBinding, when to use, blah blah blah, as lot of content is readily available on net.  So, let's start quickly onto coding part:

First of all, let's create a new project using WPF template and place a button in it as below:
Now, what I am going to do is, I am going to replace this content template for this button. So, in order to do this, open up the Button tag and add Button.Template markup tag with a new ControlTemplate as:

Now as soon as you will add ControlTemplate tag, you will notice that the content of the button is gone and button is shown as a transparent rectangle. This is happened because here I told WPF to replace the default ControlTemplate with the one, which I defined. But at this point, our ControlTemplate is blank, so there is no visualization and we can see only a transparent rectangle.

Now go ahead and customize our ControlTemplate by putting Ellipse inside it as:

Now we can see that, we get a visualization for a button in form of ellipse. At this point of time, it works OK, but there are scenarios where this struct breaks down.

For example, Let's increase the height of button, from 35 to 105 as:

In above image, you will notice that button height is increased but the ellipse size is still the same, which is a bad UI design. And the reason this is happening is, inside a ControlTemplate, the height of an ellipse is hard coding. So, no matter, whatever height is set at parent (i.e. Button), it will not get inherited to child control (i.e. Ellipse).

So, now we have to fix this problem by using a special type of binding called TemplateBinding inside ControlTemplate. So, instead of hard coding the height, we will use TemplateBinding as shown below:

By setting the TargetType property of ControlTemplate, we are telling Ellipse that, any property of  Button can be set to ellipse. Now, whatever the height of button will be, it will automatically be the height of ellipse also. Isn't it interesting?

Moving forward, let's do something more interesting with Fill property of ellipse.

In above snippet, I am trying to set the Fill property of an ellipse using TemplateBinding. But now problem here is, a button doesn't have a Fill property. So, there is no one-to-one mapping for Fill property. Now, what to do ?

No need to worry that much because button does has a Background property as:

In above image, you might have notice that as soon as ellipse's Fill property is set to Background, ellipse becomes transparent as button's background. Now if we set button's Background property to Red, the same will be applied to ellipse too.

So, one can understand that how much magic we can do with TemplateBinding.
Now, let's work little bit on code cleanup.

ControlTemplate inside resource dictionary:
For better code readability, we will move out our ControlTemplate code and put it inside a resource dictionary as:

So, now we can see as earlier that whatever visual property for button is set, all get applied to ellipse also.

Hope this article was useful and gave you the basic idea on how to use TemplateBinding.

Sunday, May 26, 2013

ReLive TechEd

This weekend, I got a chance to attend an event 'ReLive TechEd' organised by very talented folks of B.Net and Microsoft community. This event goes for close to 5 hours and gives us the glance of latest Microsoft technologies. The most effective thing was that all the sessions were given by the professionals who actually presented in Microsoft TechEd 2013. This year I missed the TechEd, but I am very happy and thankful to B.Net team, who organized it back and that is also totally free of cost :) 

Friday, May 17, 2013

Windows Phone App Design Principles

Hope most of you might have heard DOUGLAS MARTIN's quote:
         "Questions about whether design is  necessary or affordable are quite beside the point: Design is inevitable. The alternative to good design is bad design, not no design at all."

       "Design is the conscious effort to impose meaningful order"

So, if designing is that much important then one has to be very much stern about it. Going forward, today I am pointing out some design principles for Windows Phone App. So, let's gear up.

  • Clutter free UI - Information should be well organized and user should not get congestion like feel. Make best use of typography
  • Focus should be on content and it should be in a way that it attracts the user's attention from the beginning itself
  • Try to keep only the most pertinent content on the screen because when it comes to WP design, content matters more than a chrome
  • Try to provide seamless UX from dedicated device buttons
  • Tiles should be soulful and alive, in order to achieve the better responsiveness
  • Accentuate more on enhanced touch and gesture information
  • Try to keep the smart screen updated with only the latest and germane information
  • Use proper icon/text to introduce your app
  • Always create UI mockups, before proceeding towards actual implementation
  • Once mockups are ready, never hesitate to do usability testing
  • Provide app uniformity by providing similar meaning to similar images, color, symbols, etc
  • Do spend time in branding your app - it includes logo, color, copyright info, etc.
Hope above tips were useful :)

Wednesday, May 15, 2013

Windows Phone App' s Tip - Image consideration

Images play a very significant role in any Windows Phone application. So, one should be very careful while dealing with images. As of now, Windows Phone supports only two image formats named JPG/JPEG and PNG. Now before concluding on which image format to choose, let's get into bit more depth of it.

PNG format images are non-lossy and need very little CPU effort to display because those are pixel perfect. But at the same time, huge PNG images take too much longer to read from storage and ultimately lead to slower display.
On the other hand, JPEG format images are lossy, smaller to store  and based on the compression level much more complicated decoding algorithm is required to display them.

Another point regarding image is about opacity and transparency - All the images that use transparency should be stored as PNG format because JPEG doesn’t support transparency and JPEG format should be used for all the images that are fully opaque.

Now when coming to Windows Phone apps, performance matters a lot...Isn’t it?
Well, now some best tips to make our Windows Phone app much more performant:
  • Choosing proper image format: Use JPEG for anything large and PNG for anything small, i.e. use PNG for small icons. If image transparency is not a concern then it is always recommended to use JPEG.
  • Compiling images with Build Action=Content: Whenever a new image is added to the project, the default "Build Action" is set to Resource. It is always recommended to change this "Build Action" property to Content as it will reduce the size of our DLL, resulting in speedy image and app loading.

Note: Resources are included in an assembly whereas content is included in deployment package.
  • Image size: One of the limitations of Windows Phone is the limited screen resolution. So one has to consider proper image size, in order to gain better performance

 I'll keep updating this post as and when I'll get to know about more interesting facts. I would be very happy, if you can add more on to it.

Thursday, March 21, 2013

Silly but useful stuff - Part 3 (UI)

Importance of UI in performance
Simple UI tricks, such as progress bars, redirecting user's attention using animation, or placing slower loading sections at the bottom of a page or off-screen, can often ‘fix’ a performance problem without the need to tune the underlying code.
These UI tricks are an important tool to have in your performance tuning toolbox and can be much quicker and easier than addressing the underlying issue. They can act as a holdover until you have the time to devote to the core problem. So, one should never underestimate the UI while tackling performance issues.

Isn't it interesting :)

Saturday, March 2, 2013

StringBuilder is NOT the answer for all string concatenation scenarios; String.Join could be

Yes, if you are in a loop and adding to a string, then a StringBuilder *could* be most appropriate. However, the overhead of spinning up a StringBuilder instance makes the following pretty dumb:     

var sb = new StringBuilder(); 
sb.Append("This is ");
sb.Append("not more efficient");
sb.Append(" solution.");
var str= sb.ToString();
 Instead, use String.Join, which is typically more performant than spinning up a StringBuilder instance for a limited number of strings. It’s my go-to concat option:  

        string myString = String.Join(" ", new String[] { "This", "is", "a", "much", "better", solution, "."}); 

The first variable of " " can just be set to "" when you don’t want a delimiter.
For loops that do a lot of looping, sure, use a StringBuilder. But just don’t assume it’s the de facto solution in all, or even the majority of cases. My rule of thumb is to add strings together when I’ve got one to five of them (likewise with String.Format if it helps with legibility). For most other cases, I tend towards String.Join. Only when dealing with a loop that isn’t limited to about 10 iterations, especially one that really lets rip, I do spin up a StringBuilder.

Thursday, February 21, 2013

Starting with Prism - Part 3 of n


Continuing to my Prism 2 of n series, in this article I am going to talk about how a communication happens between various application components, following Prism framework.


In earlier articles of this series, I already mentioned that Prism is all about loose coupling and modularity. So, in order to achieve both these aspects we divide our application into multiple modules. Now, when we are talking about modularity, first thing which strikes to our mind is communication. How will these module going to talk with each other, how they are going to communicate with each other, etc, etc. So, when we have a need of communication between modules, there are couple of approaches which we can take like Commanding, Event Aggregation, Shared Services, Region Context and probably there are many more. In this article, mainly I'll be taking these four concepts:   
  • Commanding  
  • Event Aggregation  
  • Region Context 
  • Shared Services   
Now let's take one-by-one and see, how they make our application loose coupled 

Commands/Commanding Overview 

This is the most common method of communication in Prism application. Now again, commanding is not specific to Prism library. It is similar to what we have in WPF and Silverlight. Main purpose of commanding is to bind a UI gesture (i.e. a button click) to an action which needs to be performed. Each command has an Execute method and this method is called whenever a command is to be execute. Apart from  Execute method, command also has an CanExecute method, which determines whether or not a command can be execute. An element that is bind to the command can be either enable or disable based on the result of CanExecute method.
Most common ways to create command is either to use the RoutedCommand or Custom Command. RoutedCommand delivers the command messages to UI element. On the other hand, Custom Command can be implemented by creating a custom class, which in turns inherits an ICommand interface. Using custom command needs a lot of extra work and one has to provide command handlers to hook off and then do the routing, when the command is on board.
Please note, in Prism application, command handlers doesn't have any association with any elements in the visual tree. But don't get panic. Fortunately, Prism provides us with two classes that makes commanding more easier and provides more functionality. It provides DelegateCommand and CompositeCommand.  
A DelegateCommand is a command that allows you to call a delegate when the command is executed whereas CompositeCommand allows us to combine multiple commands.  


A DelegateCommand is a command that allows you to supply methods as delegates and will be invoked when the command is invoked. So, this means that event handler is not at all required in the code behind. Another good thing is DelegateCommands are normally stored locally means that are created in ViewModel and the concerns of the delegate methods are within the context of that ViewModel.  Now agian, Prism has something for these DelegateCommands. Prism actually provide you with two DelegateCommand as DelegateCommand andDelegateCommand<T>. The difference is the Execute and CanExecute delegate methods for DelegateCommand will not accept the parameter whereas the DelegateCommand<T> allows you to specify the type of parameter that Execute and CanExecute  parameter can be. Now, let's jump into some code:  

Using the code  

Before getting into much depth, first I want to tell you about what I want to achieve here.

Now what I want is, whenever I click on Calculate button, interest amount should be calculated. So, let's go ahead and implement this. 
We know that calculate command should be executed on button click. So, we have to add below line of code forButton as 
<Button Content="Calculate" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Command="{Binding CalculateInterestCommand}" /> 
As of now this command doesn't exist in our ViewModel. So, let's go ahead and add this in our ViewModel as: 
public ICommand CalculateInterestCommand { get; private set; } 
Now we need to create an instance of this command. So, in the constructor add this line: 
public InterestCalculatorViewModel()
            CalculateInterestCommand = new DelegateCommand(Calculate, () => CanCalculate);
In the above command, first parameter will be the Execute method(in our case, it is Calculate method) which will be called when a command will execute and the next parameter will be  CanExecute(in our case, it is CanCalculate), which will tell whether a command can execute. 
Now go ahead and create your Execute and CanExecute parts as:  
private void Calculate()
     InterestAmount = PrincipalAmount * InterestRate / 100;
private bool CanCalculate 
           // you can add your condition to enable or disable the button
           return true;
Run the application and you are all done. Isn't it very easy ??? Well, now quickly move on to the CompositeCommand.   


These are the commands which are globally scoped and exists in the common portion(in our case it will be in Infrastructure project) of our app and contains multiple child commands. These commands can be used where we have a requirement to perform same logic on multiple views with single command (in our case, let's assume we have a tab control and on each tab I am calculating interest amount). In that case, each view will have the local command bind in the ViewModel registered with a CompositeCommand. So, whenever CalculateAll command is invoked, all the child commands will also be invoked. Similarly even if single child's CanExecute returns false, CalculateAll will not be invoked.
For the demonstration of CompositeCommand, first let's open Shell.xaml. In Shell, I have added a another region, which contains CalculateAll button. We also added a TabControl, in order to inject the multiple instances of a view. Your Shell.xaml will look like this:
Then I've modified InterestCalculatorModule.cs to create multiple instances of view as:
At this point of time, if you will launch your application and click on CalculateAll button, you need to click the button three times, as one more each view. So, to make CalculateAll work in proper manner, let's add a new class named CompositeCommands as:
public class CompositeCommands
        public static readonly CompositeCommand CalculateAllCommand = new CompositeCommand();
Now go to CalculateAllModule and open CalculateAllView.xaml and add the reference of Infrastructure project as:
<UserControl x:Class="CalculateAllModule.Views.CalculateAllView"
           d:DesignHeight="300" d:DesignWidth="300">
    <Button Command="{x:Static cc:CompositeCommands.CalculateAllCommand}" Content="Calculate All"/> 
Now next step is to register our ViewModel for this CompositeCommand. Open the constructor of our ViewModel and add below line:

Now launch the application and it will work as expected. Just clicking the button CalculateAll button, all the view will get their calculation done.  
EventAggregation Overview 
This is the one of the common pattern, which is specific to Prism. EventAggregation provides event based communication in a very loosely coupled manner. It is made up of Publishers and Subscribers. Here a publisher will execute an event and a subscriber will listen to the event. Please note, subscribers do not need have any strong references to publishers. 
Prism has built-in support for EventAggregation as it provides a core service by IEventAggregator interface. EventAggregator is responsible for locating and loading the events. It is also responsible for keeping the collection of events in the system. Please remember, publisher and subscribers will need an instance of an EventAggregator and to get that event and for performing this, they need help of container. EventAggregator also provides multicast Pub/Sub functionality means there can be multiple publishers which raise the same event  and multiple  subscribers listening to that event.
Events created using Prism library are typed events, which means compile time checking is possible, before we launch an application. Prism provides a class named CompositePresentationEvent<T> to  create such events. This class maintains the list of all the subscribers and handles everything related to dispatching events. Please note, this is a generic class, so we need to mention the payload type T. Here T is what we want to send to subsciber, when a event is published. EventAggregator provides us with few services as:
  • Publication of events - by using Publish method
  • Subscribing events - by using Subscribe method
  • Subscribe using a strong reference - by using keepSubscriberReferenceAlive parameter on subscribe method. Please be cautious while using this because while using this you manually have to unsubscribe from the event, when closing the subscriber 
  •  Filtering events - by using filter delegate while subscribing 
  •  Unsubscribing events - by using UnSubscribe method 
Now, let's jump back to code once again. Here our requirement is, whenever a calculation is completed, user should get a message on statusbar indicating completetion of a calculation. Now to accomplish this, let's add a new class named UpdateCalculationStatusEvent as:

public class UpdateCalculationStatusEvent:CompositePresentationEvent<String>
{   } 
Now we need to write a publisher event in our ViewModel. So, add an instance of IEventAggregator and pass it to the constructor of our ViewModel as:
IEventAggregator mEventAggregator;
public InterestCalculatorViewModel(IInterestCalculatorView view,IEventAggregator eventAggregator)
Now when a Calculate button is clicked, we want to send a message to the statusbar. So, in order to achieve that, we need to modify our Calculate method as: 
private void Calculate()  { 
    InterestAmount = PrincipalAmount * InterestRate / 100;
    mEventAggregator.GetEvent<UpdateCalculationStatusEvent>().Publish(String.Format("Interest amount is {0}", InterestAmount));        
As per the above line of code, whenever the Calculate method is executed, result will be published as 'Interest amount is so and so'. 
Now, next we need to create a subscriber for this event and here subscriber is going to be a StatusBar. So, let's open up our StatusBar ViewModel as follows:   
   public class StatusBarViewModel : ViewModelBase,IStatusBarViewModel
        IEventAggregator mEventAggregator;
        public StatusBarViewModel(IStatusBarViewModel view, IEventAggregator eventAggregator)
            mEventAggregator = eventAggregator;
        private string message;
        public string Message
            get { return message; }
                message = value;
        private void CalculationCompleted(Object obj)
            Message = "Updated";
Now let's go ahead and run our application and you are done Smile | <img src= " />  

Shared Servcies  

Shared services is the another way of communication in Prism application. It is a custom class that provides functionality to other modules in a very loosely coupled way. This service is generally placed in a separate module and can be registered using a Service Locator. When we register our service, it is registered as a common interface. This allows other modules to use our service with acquiring a static reference to the module.But there is a side effect of using this common interface is that the concrete implementation don't have to be shared. Registering your service as a shared service is very easy and can be done by ContainerControlledLifetimeManager.  

Region Context  

Sometimes there are scenarios where we have to share contextual information between a view that is hosting a region  and a view that is inside the region. For example, you may have a master detail type scenario where you have an orders view, which exposes a region to show the order detail information. To support this scenario, Prism provides  Region Context. By using Region Context one can  share an object between the parent view and the child view that are hosted in the region. 
Please note, Prism only supports consuming the Region Context from a view inside a region only if the view is a dependency object. So, if your view is not a dependency object, then you need to create a custom region behavior. One important thing to note here is do not use datacontext here, because datacontext is mainly use to bind viewmodel to a view. So, this means, that datacontext is storing view's entire viewmodel. So, until and unless, we have very simple view, it is not recommended to use datacontext for cummunicating loosely coupled views. 

Thursday, January 31, 2013

Const and Readonly keyword

Both these words play a very important role in defining constants in an application (C#). At one sight, it seems like, both are same but exactly it is not he case. Let's understand one by one to get the clear picture.

The word const itself means, it will never change. If you are specifying any variable as a const that means the value of the variable is never going to change inside the application.

How we declare a constant is, by using a const keyword. Basically, one can define const only on the primitive types, like int, double, etc. One should make sure that the value should be assigned at the time of declaration itself and another important thing is whatever value is set for const variable, that value will be set at the compile time itself and this value will get stored inside a .dll or an .exe. In later part, I'll show u on how we can see this value inside a dll or an exe using an Ildasm. Sample code to define const variable is as:

Another keyword is the readonly. The readonly word also sounds like a const but for the readonly variable you cannot change the value, once it is assigned. Means it is restricting us to a value assignment. Sample code to define readonly is as follows:

Please note, readonly  variables can be assigned either at the time of declaration or can be assigned value inside a constructor. These two are the only places, where one can assign the value of a readonly ariable. For readonly alue assignment is done at run-time and there is no difference between a regular variable and a readonly variable in terms of memory allocation.

Combined sample code with bit more depth:

In above code, let’s change value PI and age variable inside the Main function as:

Here one can notice that, reassigning both the variables named age and PI is giving an error and on mouse hover, we can get the complete description of error as:

Now question is, if both are having the same qualities then what’s the point in creating two different things. Well, this is not the case because const is a compile time constant and readonly is a run-time constant. Most of us might be aware that the value of compile-time constants are set at the time of declaration itself and this can be seen in ildasm also. Coming to the run-time constants, these are set at run-time and that’s the reason that it is not mandatory to assign readonly variables at the time of declaration itself as one can assign them in a constructor also as:

Now question is when to use what:
If the value is going to fix throughout the program and is never going to change in any circumstances, then one should choose const.
But on the other hand, if assignment of initial value depends on some parameter/conditions and value needs to be decide at run-time, then one can opt for readonly and based on that initial value of a readonly variable can be set. But please note, once the value is assigned, further modification is not at all possible till the lifetime of the application.

ILDASM and constants:
Now, let's jump quickly on ildasm to prove the value assignment for both of these.

As I told earlier, that const are compile time constants and are assigned at the time of declaration itself. So, same can be proved via ildasm using IL code. In ildasm, one can see the value of const variable in hexa but for readonly variable, there is no such value assigned in PI variable in ildasm.

Hope above article was useful :) 

Wednesday, January 23, 2013

Silly but useful stuff - Part 2 (ASP.Net)

Using StartMode Attribute
Every time we update our site, IIS must recompile it during the first request, so the initial request takes significantly longer than subsequent ones. An easy solution for this is to tell IIS to automatically recompile our site as part of the update process. And this can be achieved using the startMode attribute in the ApplicationHost.config file.

In essence, we can say, by using startMode attribe, one can reduce the initial load time of an ASP.Net site. Hope it helps :)

Sunday, December 23, 2012

Silly but useful stuff - Part 1 (.Net)

Collection and List
Let's have a look at this snippet:

In first sight, most of you might feel that both List and Collection will contain print numbers from 1 to 6. Am I right?

But Alas! There is a hidden gotcha in it ;)
Because the actual output is:

What happen surprised???

If you have ever tried to get in depth of Collection and List, then you might know the answer. Well, the answer is pretty simple. MSDNdocumentation clearly states that "Initializes a new instance of the Collection class as a wrapper for the specified list".

And on the other hand, MSDN documentation states that "Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied."

Hope now it is clear to you.

So, the moral of the story is, one should be very cautious while using List and Collection else it can bite you really very-very hard.