Monday, November 28, 2011

Simplest Way to Implement Multilingual WPF Application


Introduction

Globalization is one of the concepts that comes to mind when we create applications that might run in different geographical locations. Based on the Culture code, we need to modify our application. This is a very common case for many developers. I thought let's discuss what I implemented as the most cunning way to deal with this in your WPF application.

Points of Interest

Globalization is the most common issue to every application. Many of us might have searched over time to find out the easiest way to do a Multilingual Application. Believe me, I did the same thing like you. After doing that, I found a lots of articles on the internet. For instance, you can see one from MSDN:
If you have already read the article, you might have found that there is no such actual implementation that clearly demonstrates the concept. That is why I thought of writing a concrete article for you to easily implement a truly Multilingual Application.

Using the Code

language.JPG
If you have downloaded the sample application, you can see that I have created a login screen, just to show how it works. To try, just run the application you will find a screen just like the one shown above.
Put Username and Password Same, and press login button. You will see the screen below:
language2.JPG
Next, go to Control Panel - > Regional & Language Option and change the Language to French(Canada), and Re run the application.
language3.JPG
You will find a different screen as below:
language1.JPG
And if you put credentials and press "connexion" (Login) button, you will see "Échec de l'authentification"(Authentication Failed).
Now I will discuss how can you implement this type of application yourself.

The Implementation

To start implementing this application, I have added one window. I have also designed the window with some look and feel. You can see them, but this is nothing to deal with our application, so I left out their implementation.
After creating the initial look and feel, which suits me, I added a folder named "Resources" (the name of which can be anything). I added two resource Dictionary to define my resource keys which I will use for my application.
language5.JPG

1. Creating the Resource File

The resource files are named as StringResources.xamlStringResource.fr-CA.xaml, etc. You can add as many resource files as you want, each of which corresponds to its own Culture.
Inside the resource files, you must declare the ResourceKeys. I have used system:String to define the Resources.
<ResourceDictionary 
      xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns: x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns: system="clr-namespace:System;assembly=mscorlib">

<system:String x:Key="close">Close</system:String>
<system:String x:Key="login">Login</system:String>

</ResourceDictionary> 
Thus you can see, in addition to adding the ResourceDictionary to the Resources Folder, I have added one namespace which points to mscorlib, and named it as system. I have then added the string references likecloselogin, etc. which are defined to be replaced in the UI.
Similar to this, I have added another file for fr-CA, and named it as StringResource.fr-CA.xaml. This will hold all the keys that corresponds to the Resourcekeys for a machine set up with French Canadian.
<ResourceDictionary 
        xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String x:Key="close">Fermer</system:String>
<system:String x:Key="login">connexion</system:String>
</ResourceDictionary>
Thus you can see that I kept the same name for the keys to ensure everything works perfectly. If you have used ASP.NET Globalization, this is almost similar to it.

2. Adding a Resource

After you create the Resource file, it's time to add it to the window. To add, I have just implemented a method which you can place in some utility class. For simplicity, I left it in my window. The method looks like:
private void SetLanguageDictionary()
{
ResourceDictionary dict = new ResourceDictionary();
switch (Thread.CurrentThread.CurrentCulture.ToString())
{
  case "en-US":
       dict.Source = new Uri("..\\Resources\\StringResources.xaml",  
                     UriKind.Relative);
       break;
case "fr-CA":
        dict.Source = new Uri("..\\Resources\\StringResources.fr-CA.xaml", 
                           UriKind.Relative);
        break;
default :
        dict.Source = new Uri("..\\Resources\\StringResources.xaml", 
                          UriKind.Relative);
        break;
}
this.Resources.MergedDictionaries.Add(dict);
} 
This is the most simple implementation. I have added the dictionaries directly to the window resources. I have created an object of ResourceDictionary and pointed to the file that is created for resource to its Source property. This will load the external file directly to the object. And finally added to Window.Resources usingthis.Resources.MergedDirectories.Add(). As you know, after compiling, WPF holds the relative path intact, so it will not create any errors during runtime.

3. Using the Resource

Finally, it's now time to point ResourceKeys to your XAML to ensure it picks up the appropriate key from theResourceDictionary. Let us add some controls:
<Button      x:Name="btnLogin"
             Click="btnLogin_Click"
             Content="{DynamicResource login}"
             Grid.Row="3"
             Grid.Column="0" 
             Padding="10" 
/>
<Button x:Name="btnClose"
        Content="{DynamicResource close}"
        Click="btnClose_Click"
        Grid.Row="3"
        Grid.Column="1" 
        Padding="10" 
/> 
You should note that I have always put the Content of the Button using DynamicResource. This is important to define, because we want the content to be replaced with the appropriate key defined to the Resource will be added later.
Hence, your application is ready.

Points of Interest

You should note that you must define the key to the resource file before you use as DynamicResource. Otherwise, you will end up displaying nothing in the UI.
This implementation is totally based on UI elements, there is nothing to deal with translation of dynamic UI text. I will discuss about Translation of Language for dynamic User elements later in another article.

Conclusion

Thus, it is really fun to play with WPF, and as Multilingual application is most likely a common issue, I hope this article will help you in the long run. Try the sample application and see the actual implementation.


DOWNLOAD SOURCE CODE

Do you need the source code of the project for your reference? Yes, you can download it from here:

Wednesday, November 23, 2011

MVVM Pattern in WPF: A Simple Tutorial for Absolute Beginners


Introduction

As part of learning the MVVM pattern, I tried to search many sites and blogs and found most of them explained the pattern in a complicated way. After some research, I cracked the very basic steps in MVVM pattern, and here I am trying to write an MVVM tutorial for absolute beginners.
I don’t think much more time or words need to be spent for explaining the various parts of MVVM and the relationship between MVVM and WPF. If you travel to the depths of WPF, you will realize that MVVM is the best suitable pattern for WPF (you might not understand the difference between these two).
As a formal procedure, I am giving a simple diagram and definition for MVVM:
I start this tutorial with two examples: WpfSimple.csproj and WpfMvvmTest.csproj.
For the sake of simplicity, in the first project (WpfSimple.csproj), we are avoiding the Model object (an example with Model will come later).
In the example WpfSimple, the View contains just a Button and no code-behind, but the button click event is loosely bound with the ViewModel. The bindings between the View and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a View. If property values in the ViewModelchange, those new values automatically propagate to the View via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action.

The View

The following code snippets are from the WpfSimple application (available with the tutorial):
<Window x:Class="WpfSimple.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfSimple"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click" 
                Height="23" 
                HorizontalAlignment="Left" 
                Margin="77,45,0,0" 
                Name="btnClick" 
                VerticalAlignment="Top" 
                Width="203"
                Command="{Binding ButtonCommand}" 
                CommandParameter="Hai" />
    </Grid>
</Window>
The ViewModel class used here is MainWindowViewModel, the object set as the DataContext of the View.

The ViewModel

The ViewModel class used over here is MainWindowViewModel.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace WpfSimple
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }

        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action(ShowMessage));
        }

        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}
You can see an empty code-behind file here. If you click on the button, it will prompt a message box, despite the lack of event handling methods in the Views. When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object act as an adapter that makes it easy to consume a ViewModel's functionality from a View declared in XAML.

RelayCommand

RelayCommand is the custom class which is implemented in the ICommand interface. You can use any name instead of RelayCommand. Its usage is as follows:

Tuesday, November 15, 2011

Lambda Expressions with Multiple Parameters


Lambda Expressions are getting good recognition among developers and it would be nice to have the next level of information regarding it.

Summary

As you know, Lambda Expressions is an anonymous function that can contain expression or statements. The lambda expression uses the => (goes to) operator.

Example of One Parameter Lambda
var result = list.Where(i => i == 100);

Example of Two Parameter Lambda
var result = list.Where((i, ix) => i == ix);

Code Explained

In the above case the Where() method is having two overloads and we were using the second overloaded method which takes Func as argument.

Lamba1.gif

The first argument is the element itself and second would be the index. The value of index will be passed by the caller.

Applications of Index Parameters

It could be of rare applications where we needed the lambda index parameter. I have seen in many interviews they ask scenarios based on it. Some of the scenarios are given below.

Scenario 1
You have got a list of random integers. We need to find the numbers whose value equals to the index. How to achieve this in one line?

Setup Code

The following code can be used for creating the main list.
IList<int> list = new List<int>();
list.Add(0); // Value = Indexlist.Add(2);
list.Add(2); // Value = Indexlist.Add(1);
list.Add(4); // Value = Index

One Line Lambda Solution
var sublist = list.Where((i, ix) => i == ix);

The Lengthy Solution
var newList = new List<int>();
int jx = 0;
foreach (int j in list)
    if (jx++ == j) // Check index and increment index        newList.Add(j);

From the above code we can see without lambda expressions the solution will be taking more than 1 lines.

Result

We can see the associated result of the console application. The source code is attached with the article.

Lamba2.gif

Using Auto Intelligence Using C# Code Snippet for Faster Coding in C#.Net


Introduction

What is a C# Code Snippet?

The code block, which is wrapped inside a CDATA section of a XML file and the Microsoft IDE provides a mechanism to explore this code block, which is written in the XML data to insert into a page we are working on. On a large project, this is common usage some senior level people does the common code block which reusable is shared across the project will make available in the Code Snippet form. While we create module you can put you patterns and practices in code snippets and do an easy development. Remember the code Snippet always gives a base template hides in XML CDATA Section Where As you need to change this according to your need.

Background

It is a developer's tendency to achieve functionality and forget the basic structure required in the project. Later we need to add region, try blocks and copyright information to make it professional. I myself have done many of these reworks, so my current project inspired me to think of different directions to implement an Auto Intelligence to avoid such situations.

Using the code

Code1.gif
Code2.gif
Code3.gif

Example With Scenario.

I have created A Silverlight business application like this and added a Class file in the Project like this:

AutoInteC1.gif

Step 1: Adding the Copyright InfoWhen I press 'co', I got my code snippet like this.

AutoInteC2.gif

In addition, when I press the tab key 3 times I got all copyright information like this:

AutoInteC3.gif

Step 2: Adding the Class Structure

I have revoked auto class template come then it look like this.

AutoInteC4.gif

When I type "Simpleclass", then I press the tab key 3 times then I get all Class information like this:

AutoInteC5.gif

Step 3: Adding the private and public class

Go to API Public Methods or Private Methods

The type "SimplePublicMethods" or "MySimplePrivateMethod" ", then I press the tab key 3 times and I get all Method information like this:

AutoInteC6.gif

AutoInteC7.gif

Finally, your page looks like this:
#region CopyRightsAiropse//Comments
//Sonata
//Sonataian
//MM-DD-YY
//MM-DD-YY
//MM-DD-YY
//

Enter Summary
#endregion
using System;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Ink;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;
namespace BusinessApplication2
{
    public class SimpleClass    {
 
        #region Consts
        #endregion
        #region Members
        #endregion
        #region Properties
        #endregion
        #region Ctor
        #endregion
        #region Methods
        #region API Public Methods
        #region SimplePublicMethods
        /// 


        /// My Simple Method Which created By Auto IntelliSense         /// 

        ///          ///          ///         public string SimplePublicMethods(int Value1, int Value2)
        {
            string Value = string.Empty;
            try            {

            }
            catch (Exception ex)
            {

                ErrorWindow.CreateNew(ex.Message);
            }
            return Value;
        }
        #endregion
        #endregion         #region Private Methods
        #region MySimplePrivateMethod
        /// 


        /// My Simple Method Which created By Auto IntelliSense         /// 

        ///          ///          ///         private string MySimplePrivateMethod(int Value1, int Value2)
        {
            string Value = string.Empty;
            try            {

            }
            catch (Exception ex)
            {
                ErrorWindow.CreateNew(ex.Message);
            }
            return Value;
        }
        #endregion
        #endregion         #endregion    }
}
I hardly took a few seconds to complete this much of code; this is the beauty of code snippets.

How we can create code snippets and integrate to IDE

Creation

Step 1: Please go to the you "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#" if you are using windows 7 other wise search for "\Snippets\1033" or "\1033" under you VS root directory installation.

Step 2: Once you reach there you will get all code snippet file like this.


AutoInteC8.gif

Step 3: Please take one code snippet and copy to your desktop and Edit that

CDATA SECTION with the code block you want to see when the code injects.
public class SimpleClass{
#region Consts
#endregion
#region Members
#endregion
#region Properties
#endregion
#region Ctor
#endregion
#region Methods
#region API Public Methods
#endregion
#region Private Methods
#endregion
#endregion}
]]>


2. Edit the title part For giving the name.

<br>SimpleClass<br>

3. Change the author name

Fijo Francis T

4. Give a nice description


Class Structure DEFAULT


5. Give a shortcut key

SimpleClass

6. Inside Snippet Section you give the language you are targeting.

or

That's it; you are pretty much finished; the final file looks like this:
xml version="1.0" encoding="utf-8"?><CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">  <CodeSnippet Format="1.0.0">    <Header>
      <
Title>        SimpleClass      Title>
      <
Author>Fijo Francis TAuthor>      <Description>        Class Structure DEFAULT      Description>
      <
Shortcut>SimpleClassShortcut>    Header>
    <
Snippet>
      <
Code Language="CSharp">        public class SimpleClass
{
#region Consts
#endregion
#region Members
#endregion
#region Properties
#endregion
#region Ctor
#endregion
#region Methods
#region API Public Methods
#endregion
#region Private Methods
#endregion
#endregion
}
]]>
     
Code>
   
Snippet>
 
CodeSnippet>CodeSnippets>
Please DO not forget your edited Code snippet in the same name as Title in desktop or any hard drive you copy.

Integration to IDE

Step 1:

PRESS cntl+K && cntl+B in IDE , then it pops up the following window:

AutoInteC9.gif

Step 2:

Press the import button it and redirect to the code snippet we have saved in drive. And select snippet you created and press open save dialogue window.

AutoInteC10.gif

Then you get this view:

AutoInteC12.gif

AutoInteC12.gif

Please select my code snippet part or you can add under the Visual Studio C# part. What this location is simple. And press Finish you are ready to use code snippet.

Go to IDE type your Title name you and TAB 3 times, there you got your code snippet.

Example

AutoInteC13.gif

TIP:

Please right on you page and go to insert snippets part it will look like this, so arrange where we need to put our code snippet.

AutoInteC14.gif

AutoInteC15.gif

Courtesy -  Fijo Francis