Thursday, December 16, 2010

What is My IP

I have created a simple application which will tell the user what is IP address of the user and also the country name and country is also displayed. For this I have used the free web service which you can find here they have other free services as well.
For this application I have used the Image and the TextBlock control in my application and the web service I have used from the here. The code is simple one I have used one class which is used as the view model for the main user control ( with the name MainPageViewModel and which has one property of MyIPAddress of type GeoIP type. which is available when you add the service reference) and the one converter class which is listed in the List 1.The code in the List 1 is simple one here I have passed the country code to the converter and then by concatenating path with the country code and the png extension I return the image path of the country flag. if the country code is empty the default image will be return which you can see in the Image 1.  And if the country code and the other information is successful then you can see the output as shown in the Image 2.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string strReturnValue = "Images/Default.png"; string strCountryCode = value as string; if (strCountryCode.Trim() != string.Empty) strReturnValue = "Images/" + strCountryCode.ToUpper() + ".png"; return strReturnValue; }
List 1

Image 1


Image 2

Note: If your country flag is not displayed please let me know with the country code so that I can update it on my example as well. 

I have only uploaded the web side not the Silverlight application.  You can download the source code from here and you can open the What Is MyIPTestPage page in IE or in your web browser to check the application.

All and any comments / bugs / suggestions are welcomed!

Saturday, November 13, 2010

Browser Information In Silverlight

In this post I will show you how to get the browser information.To get the browser information the namespace used for this is System.Windows.Browser. The BrowserInformation object contains properties such as the name, product name, product version , browser version etc. Let us start with the example which will use to get this information and display on the screen which I will share with you at the end of the post I will use two screen shot one for the Internet explorer and the second one for the Fire Fox.
For this Example I have create one class with the name BrowserInfo  which has the properties like BrowserName , BrowerVersion, Platform, ProductName, UserAgent of type string , IsCookiesEnabled of type Boolean to indicate whether Cookies are enabled or not , BrowserMinorVersion and BrowserMajorVersion are of type int.You can see the default constructor of the BrowserInfo class which is used to initialize all the properties of the class.

public BrowserInfo() { BrowserName = HtmlPage.BrowserInformation.Name; BrowserVersion = HtmlPage.BrowserInformation.BrowserVersion.ToString(); BrowserMajorVersion = HtmlPage.BrowserInformation.BrowserVersion.Major; BrowserMinorVersion = HtmlPage.BrowserInformation.BrowserVersion.Minor; IsCookiesEnabled = HtmlPage.BrowserInformation.CookiesEnabled; Platform = HtmlPage.BrowserInformation.Platform; ProductName = HtmlPage.BrowserInformation.ProductName; ProductVersion = HtmlPage.BrowserInformation.ProductVersion; UserAgent = HtmlPage.BrowserInformation.UserAgent; }
List 1

In the code you can see that BrowserName property is assigned the value of the Name in the BrowserInformation object which is the static member of the HtmlPage static class which is reside in the System.Windows.Browser namespace. The Name property of the BrowserInformation return the version of the browser technology that the current browser is based on.The browser technology name is typically different from the browser product name. CookiesEnabled property of BrowserInformation object indicate whether the browser supports cookies or not. The ProductName property of the BrowserInformation object get the product name of the browser.The browser product name is the familiar name of the browser, such as "FireFox".
You can see the output of the two different browser One for the internet explorer and second one is by using the Fire fox you can see the different properties of the two browsers.

Fire Fox
Internet Explorer
You can also see the Major and Minor version of the browser as shown in the screen shots. The UserAgent property will Gets the user agent string of the browser.The Platform property will return name of the operating system that the browser is running on. You can use these properties to developer application like the Google analysis or you can use them to show the trend of your site the user operation system the browser name etc.

All and any comments / bugs / suggestions are welcomed!

Tuesday, November 9, 2010

Reading And Writing Isolated Storage In Silverlight

In this post I will show you how you can create file on the Isolated Storage and also write on that file and also how can you check the size of the Isolated storage.Isolated storage is a mechanism that allows you to preserve data across browser sessions on a user’s machine. This storage area is tied to an individual user and helps you overcome the 4 KB limitation of a cookie. Unlike a cookie, isolated storage lies outside of the browser cache.
The code which is used to write in the Isolated Storage is listed in List 1.The class used for the Isolated Storage is IsolatedStorageFile which represents an isolated storage area containing files and directories. IsolatedStorageFile class has static method with the name GetUserStoreForApplication which is used to obtains user-scoped isolated storage corresponding to the calling code's application identity. After retrieving the user isolated storage object next step is to create the stream object which is used to write the contains.

using (IsolatedStorageFile isolatedStoragFile = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("MyFileName.txt", FileMode.Append, isolatedStoragFile)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write("Message Date And Time: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") +" -> "+ txtTextToWrite.Text + "\r"); } stream.Close(); } }
List 1

IsolatedStorageFileStream is the class which Exposes a file within isolated storage.IsolatedStorageFileStream is used to read, write and create files in isolated storage. So if you want to read , write or create new file in the Isolated Storage area you need the object of the IsolatedStorageFileStream. I have passed the file name which in this case is .txt extension the, second parameter is the FileMode enumeration which has one of the values as listed in the table given below.The last parameter to the IsolatedStorageFileStream constructor is the IsolatedStorageFile object which is created before.

FileModeDescription
CreateNewAttempts to create a new file If a file of the same name exists, an IsolatedStorageException will be thrown. If there isn’t a preexisting file with the same name, a new, empty file will be created.
CreateA brute-force approach to creating a new file If a file of the same name exists, it’ll be overwritten. Either way, a new, empty file with the specified name will be created.
OpenAttempts to open a file with the given name If the file exists, the IsolatedStorageFileStream will have access to the file. If the file doesn’t exist, an IsolatedStorageException will be thrown.
OpenOrCreateOpens a file if it exists. If the file doesn’t exist, a new one will be created with the given name.
TruncateOpen an existing file and removes all its contents. This FileMode doesn’t allow read operations.
AppendOpens an existing file and prepares to add content onto the end
Table 1

After the creation of the IsolatedStorageFileStream object next is to use the StreamWriter class which take the IsolatedStorageFileStream object in the constructor and use the StreamWriter object to write the text or binary to the file.  The Image 1 show the layout of the example which I have used for the Isolated Storage. Here you can see that I have used two text boxes one for the input which user entered and second one is to read from the Isolated storage area which is shown in the Image 2.
Image 1


Image 2
The IsolatedStorageFile class has some useful properties which can be use to check the available free space (Gets a value that represents the amount of free space available for isolated storage.the value is in bytes), used space (Gets a value that represents the amount of the space used for isolated storage. the value is  in  bytes)and total allocated space to the current user.If you look at the example you can see that I have also print out the available free space and used space as well to show you how much space is available and how much is used.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Sunday, November 7, 2010

Reading Web.Config to pass values to silverlight Application

In asp.net application we often use to save the connection string and some other information like user name , web service URL etc in the web.config and then in application read them and use in the application and even we can easily changes these value at later time.However, this scenario does not work out of the box from a Silverlight application, which doesn’t seem to even have access to web.config.The reason is simple: a Silverlight application runs on the client side. The XAP -just like the browser- cannot access server resources such as web.config. In this post I will show you how you can read the web.config and pass to the silverlight application and then on the silverlight application how can you read the passed parameters.
Passing Parameters :
To pass the web.config parameter or other parameter to the silverlight is very easy you can pass the web.config or other value by assigning the InitParam parameter. For this you have to read the web.config values and store these values in the key value format.The code listed in the  List 1 show how to read the value from the web.config and paired them in key value format. Here you can see that I have read two values from the web.config one is the connection string and the second one is the user name. You see that each key value pair has equal to (=) sign between them.

< script runat="server"> public string WebDotConfig { get; set; } protected void Page_Load(object sender, EventArgs e) { WebDotConfig = "ConnectionString=" + ConfigurationManager.AppSettings["ConnectionString"]; WebDotConfig += ",UserName=" + ConfigurationManager.AppSettings["UserName"]; } < /script> //passing value <param name="initParams" value="<% =WebDotConfig%>" />
List 1
And for second value which is the user name you can see that comma (,) sign. as the comma(,) sign indicate new key value pair.And at the last statement which is written in the html side to pass the parameter to the silverlight application. Here you can see I have used the InitParams InitParams is one of the param name of the Silverlight plug-in object. Generally it is a dictionary object of type string. It contains a set of user defined key/value pairs. By default it is set as null or empty string and initializes at the time of first instance.

Reading InitParams :
 In this post I will show you 2 ways to read the InitParams on the silverlight application.

1- Application_Startup :
you can read the passed value in the Application_Startup event handler which is written in the App.xaml.cs file. The code to read the passed values on the silverlight application at the Application_Startup event handler is listed in List 2. Here you can see that StartupEventArgs e has property InitParams which is ready only of type IDictionary which takes two value of type string. Here I have first check the key which is the connection string and the user name and then I have read these values in the WebDotConfig class which has two properties with the ConnectionString and the UserName which are static.

private void Application_Startup(object sender, StartupEventArgs e) { if (e.InitParams != null) { if (e.InitParams.ContainsKey("ConnectionString")) WebDotConfig.ConnectionString = e.InitParams["ConnectionString"]; if (e.InitParams.ContainsKey("UserName")) WebDotConfig.UserName = e.InitParams["UserName"]; } RootVisual = new MainPage(); }
List 2

The reason for reading the values in the Application Startup event handler is the some time you need to use the Web service URL in you application. It is better to read it here and store it in some class which is accessible later when you need to use same URL to authenticate the user name. As Connection string and user name are static so one there are read you can use them any where in you application.

1- SilverlightHost :
In you don't the the variable which are used at the application start up like the web service URL which is used in common scenario. You can also read the passed parameter to the silverlight application by using the SilverlightHost class which has the InitParams property which is discussed in the Application Startup event handler.


private void UserControl_Loaded(object sender, RoutedEventArgs e) { if (Application.Current.Host.InitParams.ContainsKey("ConnectionString")) txtConnectionString.Text = Application.Current.Host.InitParams["ConnectionString"]; if (Application.Current.Host.InitParams.ContainsKey("UserName")) txtUserName.Text = Application.Current.Host.InitParams["UserName"]; }
List 3

In List 3 you can see I have used the InitParams of the SilverlightHost class and read the key values and assign them to the control which are used to display the passed parameter values. The output can been see in the Image 1, here I have displayed values read from both way from the Application startup event and also from the SilverlightHost class.

Image 1

I have separated both the section and place the Header for Application Statrup (Which displays values read at the Application Startup event handler and save in the WebDotConfig class, I have used binding for this as I have class which contain properties and bind to the respective controls on the user control)and for Host InitParams (Which are set at the code behind as I am reading values in the User control loaded event handler). .You can download the source code from here.  

All and any comments / bugs / suggestions are welcomed!

Saturday, November 6, 2010

Full Screen Mode In Silverlight

In this post I will show you how to make the silverlight application to run in full screen mode which is provided by the silverlight. You can use the F11 key to run the silverlight application in full screen mode but the toolbar button are visible on the top of screen in case of the F11 key. To go back to the embedded mode you can use the Esc key to exit the full screen mode. But if you want to give this functionality in you application or by using the code here is the code which is used to run in the Full screen mode and also to go back to the embedded mode.
For the code listed in List 1, the code is used written in the click event handler for the toggle button which will check the text based on the IsChecked value, if true mean application is running in embedded mode will changed to the full screen and set the text on the toggle button to Exit Full screen and same is for the when application is running in full screen in the else case.

private void btnFullScreen_Click(object sender, RoutedEventArgs e) { if (btnFullScreen.IsChecked.Value) { Application.Current.Host.Content.IsFullScreen = true; btnFullScreen.Content = "Exit Full Screen"; } else { Application.Current.Host.Content.IsFullScreen = false; btnFullScreen.Content = "Full Screen"; } }
List 1

Now let me tell you about the IsFullScreen property which is of Boolean type and you can see in the code that when set this property to true the application will run in full screen mode and when the IsFullScreen is set to false the application will come back to the embedded mode. The IsFullScreen is property of the Content which is property of the SilverlightHost class. The Content Property also has the FullScreenChanged event which is triggered every time you set the true or false to the IsFullScreen property. This event is helpful when you need to change the size location or some other properties of the controls when application is running in full screen or in embedded mode.

Image 1
Image one shows the effect of running the application in full screen mode when you changed from the embedded to the full screen mode the prompt will display the message to the user to change to the embedded mode you can press Esc key. When running application in full screen mode you have some limitation like the openFileDialog and showFileDialog classes are not supported.
Hope that you get some idea of how to change the full screen and back to the embedded mode by using the code. as It is very easy to change the mode from full screen to embedded and from embedded mode to full screen.

All and any comments / bugs / suggestions are welcomed!

Sunday, October 31, 2010

DataPager Silverlight Control for Beginners

It was a long time when I have post on silverlight data grid control, at that time I was thinking of posting complete series of the post on the data grid control I have posted on the data grid grouping control but I didn't post on the paging of the data grid records. Now after long time I have time to see the silverlight and its paging control, I know there are lot of tutorial regarding data pager control But I have this for the absolute beginner who are just started  their journey of the Silverlight.
For this example I have two controls added in my xaml are one is the data grid control and the second one is the data pager control.
You can see the code for the data grid control and the data pager control in the List 1, Here you can see that I have set the properties of the data grid control like auto generate columns to false mean I will set the columns for the data grid control, IsReadOnly is set to false mean this grid is used for the display of data and the vertical and horizontal grid line brush and GridLinesVisibility is set to All to show both the horizontal and vertical lines.

<sdk:DataGrid Grid.Column="1" Grid.Row="1" AutoGenerateColumns="False" IsReadOnly="True" GridLinesVisibility="All" HorizontalGridLinesBrush="{StaticResource Brush_BorderOuter}" VerticalGridLinesBrush="{StaticResource Brush_BorderOuter}" x:Name="dgrdDataGrid" VerticalAlignment="Top" Height="296"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Binding="{Binding UserID}" Header="User ID"/> <sdk:DataGridTextColumn Binding="{Binding FirstName}" Header="First Name"/> <sdk:DataGridTextColumn Binding="{Binding LastName}" Header="Last Name"/> <sdk:DataGridTextColumn Binding="{Binding EmailID}" Header="Email"/> <sdk:DataGridTextColumn Binding="{Binding ContactNumber}" Header="Contact No."/> </sdk:DataGrid.Columns> </sdk:DataGrid> <sdk:DataPager x:Name="pgrPersons" PageSize="5" Grid.Column="1" Grid.Row="1" VerticalAlignment="Bottom" Background="#FF333333" Foreground="#FFE5E5E5" BorderBrush="Black" />
List 1

Next is the xaml for the data pager control which you can see in List 1.The properties which are set for the data pager control are the PageSize indicates the number of items displayed on a page which I have set for 5. Mean 5 records are shown per page as you can see in the output of the example code.
The second property which is important is the Display mode of the data pager control.The possible value of the Display and there look can be seen in the Image 1 which is taken from here. For my code I have used the FirsLastPreviouseNext display mode that is why the display mode property is not used as it has the default value.

Image 1

The code for the code behind used to set the ItemSource of the data grid control and the data pager control is listed in the List 2, here you can see that I have used the PagedCollectionView class because the data pager control take the PagedCollectionView as data source. The PagedCollectionView to provide grouping, sorting, filtering, and paging functionality for any collection that implements the IEnumerable interface.

dgrdDataGrid.ItemsSource =new PagedCollectionView(Persons.GetDataItems()); pgrPersons.Source = dgrdDataGrid.ItemsSource;
List 2

In the second statement which I have set the ItemSource Property of the data pager control to the Item source of the data grid control.These are the two lines of code which is placed at the user control loaded event handler . The output of the example code can be seen in the Image 2.


Image 2
The data pager control provide the user interface for paging through a collection of data. As you can seen that I have not right any code for the data pager control all the paging navigation to the next previous, and to first and last page is done by the control itself.The paged data is typically displayed in a control that represents a collection, such as a DataGrid or ListBox. To use a DataPager to page through data in another control, you assign the control's ItemsSource property and the DataPager.Source property to the same data collection.I hope you get starting point on how to use the data pager control and used it with the control like data grid.You can download the source code from here.  

All and any comments / bugs / suggestions are welcomed!

Saturday, October 30, 2010

TextBox Control WPF 4.0

I have used the Text Box control quite a lot in my project and I am sure many of you have also used it in your project as It is the basic control which is used to get user input.When reading details about the text box control I have found some of the new things which are in for the WPF 4 text box control and I have never used some of them in my project. Now I will share this with you some of the useful properties of the Text box control.

MultiLine :
    In many application you have used the text box control where you want to enter large in the text box control like the description is one of the example. For this case user can enter text in the text box control in multiple line. So in order to allow multiple line support use property AcceptsReturn which is used to entered the Enter key.

Image 1

TextBox always supports multiple lines of text programmatically. If  string which is assigned to the Text property of the text box containing NewLine characters like \n in C#, it displays the multiple lines regardless of the value of AcceptsReturn. Also, the multiline support is completely independent from text wrapping. Text wrapping applies only to individual lines of text that are wider than the TextBox.


Spell Checking :
         Spell checking can be enabled on the text box control by setting the SpellCheck.IsEnabled to true. When you set the SpellChek.IsEnabed to true then text box control will automatically detect the wrong word and underlined these words with red line as see in the Image 2, the similar kind of behavior you have seen while typing in the Microsoft Word. Now as you  have experience it  in Microsoft Word that you can right click on the red underlined word and it will give you suggestions of the word in list box. From the list of the suggested option for the wrong word you can choose the correct word.

Image 2

In the Image 2 you can see that I have entered wrong words like wrog entere and TextBox. You can place mouse on any of the word and select the correct word from the suggestion which are appears by right clicking on the word

All and any comments / bugs / suggestions are welcomed!


Wednesday, October 27, 2010

Changing DatePicker Label

To change the label of the date picker control in WPF is very easy. When you drag and drop the date picker control from the toolbox then it will show 15 as default, It will be nice to show current day is comfortable to show the current date.Image 1 shows the default date picker control when you drag and drop it from the toolbox here you can see that it display 15 which we want to change to show the current date.

Image 1

Here are the steps which are used to change the default 15 to the current date in the date picker control in style. First you have to open the project in the expression blend and then follow the step as describe below.
Step 1:
In the first step select the date picker control from the object and time line as we can see in the Image 1. and then right click on the control and from the Edit Template select the edit current. A dialog will open which will ask you for the name of the style or apply to the all the control of date picker in this case. I have used the default style name "DatePickerStyle1".
Image 2
Step 2:
Now the style is generated using the step 1. Now from the Resource Right click on the "DatePickerStyle1" as shown in the Image 3 and you can see the style in the Object and time line.
Image 3
Step 3 :
Now in object and time line right click on the style and select Edit Current from the edit Template option as you can see in the Image 4.
Image 4
Step 4 :
Now in the PART_ROOT select the PART_BUTTON by right clicking on the PART_BUTTON Select the Edit Current from the Edit Template and you will have the PART_Button Template as you can see in the Image 6.
Image 5
Step 5:
In last step locate the path which is show to display the 15 in the date picker as I have highlighted in the Image 6. The highlighted path is used to display 15 in the date picker control.
Image 6
Now replace the xaml of the select path with the xaml of the text block as show in the list 1 and add the mscorlib reference in the xaml as I have used the system namespace to get the current date and assign it to the text property of the text block control.

xmlns:System="clr-namespace:System;assembly=mscorlib" <TextBlock Margin="2,0" Grid.Row="1" Grid.RowSpan="3" Grid.ColumnSpan="4" Grid.Column="0" Text="{Binding Source={x:Static System:DateTime.Now}, StringFormat=dd}" HorizontalAlignment="Center" VerticalAlignment="Top" FontSize="10.667" FontFamily="Arial Bold" />
List 1

And final outpout of all the above steps are shown in the Image 7 which shows the current date on the date picker control.You can download the source code from here

Image 7


All and any comments / bugs / suggestions are welcomed!

Monday, October 25, 2010

Forcing View Validation On Save using MVVM Pattren

In this post I will show you how to force the validation rules when user click on the save button without entering any thing in the user input form.Simple scenario is when user open the form and without entering any thing in the input control he/she press save button, if you see the UpdateSourceTrigger it has the default (The default value for most dependency properties is PropertyChanged, while the Text property has a default value of LostFocus.), explicit (Updates the binding source only when you call the UpdateSource method.), lost focus (Updates the binding source whenever the binding target element loses focus.) and property changed (Updates the binding source immediately whenever the binding target property changes.). If you didn't set default focus on any of the control when form open then lost focus of any of the control will not be fired and user didn't entered any value in the user input control so the property changed will also not fired So you have to check the validation rules before saving the user input form.
You have to check the user input validation on view, mean when user click the save button without entering anything in the input control then view should check if there are required field on the which need to be check before saving the form.Let us start with  the example code to force the validation of the input control from the view. For this I have used same example code which is used in the Range Validation Rule post, I have made some modification in the view model and also in the view so that when user click on the save button then the view will check the required field validation which is asked by the view model. Let us discuss what need to be done in order to ask the view to validate the user input.

View Model :
         In view model I have made the changes which are listed in the List 1. Here you can see that I have used the delegate which return the Boolean type and then In the CammandExecute I have call the ValidateView function to check the validation of the view.

public delegate Boolean dlgValidateView(); public dlgValidateView ValidateView; private void CommandExecute() { if (ValidateView()) { MessageBox.Show(Person.FullName); IsDialogClose = true; } else MessageBox.Show("Some Error on the View"); }
List 1

If the view is free of error then I will display the full name of the person as first and the last name of the person are required and then close the dialog. In the else statement I have just shown the message that there are some error on the view end. The dialog will only close if there is no error else if will not closed.

View :
     The code for the view is listed in the List 2, Here you can see that I have two sample of code which is of window loaded function and for the ValidateView function ( I have write code for one user id text box the remain code in the ValidateView is same).
In the loaded function I have check for the DataContext for not null and then assign the function ValidateVeiw function to the ValidateView of the view model which is set as data context of the Person view.

// window loaded code if (DataContext != null) ((PersonViewModel)DataContext).ValidateView = ValidateView; //Code for the Validate View function Boolean blnIsValid = true; BindingExpression bindingExpression; bindingExpression = txtUserID.GetBindingExpression(TextBox.TextProperty); if (bindingExpression != null) { bindingExpression.UpdateSource(); if (bindingExpression.HasError) blnIsValid = false; }
List 2

In the ValidateView function I have simple code, starting with the blnIsValid variable of type Boolean which is return from the ValidateView function and if any of the control has some error then blnIsValid variable is set to false to indicate that error on the view and the message is shown in the tool tip of the control.
Next is the BindingExpression object which is used to save the binding expression of the binding object in this case the objects are the text box controls. Next is to call the GetBindnigExpression of the user id text box control which Returns the BindingExpression that represents the binding on the specified property. Next is to check the binding expression for null if there is no active binding for the specified property in this case is the Text property which is passed to the GetBindingExpression.
If the binding expression is not null , mean the binding object has active binding then its time to update it, I have used the UpdateSource method Sends the current binding target value to the binding source property in TwoWay or OneWayToSource bindings. 

Image 1
After the UpdateSource function call next is to check the error by using the HasError property which will return true in case there is error after calling the UpdateSource function and then set the blnIsValid to false as the validation is fail. Some code is used for the first name, last name, email address and the contact number. By this way the view can tell the view model that there are some error in the view as user didn't entered any input in the control and is want to save the form.
Hope you get some idea about how to perform the validation on the when you are using the Validation rules.The output can be seen in the Image 1 which is displayed above when user open the form and want to save the form without entering any input.You can download the source code from here.  

All and any comments / bugs / suggestions are welcomed!


Sunday, October 24, 2010

Auto generation of Properties (Shortcut keys)

In this post I give you some useful tips for auto generation of the properties.The code snippet which is quite useful are
  1. prop
  2. propa
  3. propdp
  4. propfull
  5. propg

1- prop :
when you type prop in the visual studio editor and hit tab it will create property of int type with the name MyProperty, which you can see in the Image 1 as shown below. You can see in the image that the data type and the name of the property are of yellow background , mean you can change the data type and the name of the property.

Image 1

2- propa :
The real benefit of using the code snippet is when you write propa and press tab key, you can see the code generated  in the Image 2, here you can see that data type is int and the name of the property is GetMyProperty. In the Image 2 you can see the default focus is on the data type of the property and all the reference of the data type in the generated code are highlighted with dotted rectangle as you can see in the Image 2. When you change the data type and press tab key all the highlighted data types are changed to the data type which you entered in this case I have changed it to the string data type.
Image 2
Now it time to change the name of the property. As you can see in the Image 2 that property is the GetMyProperty. When focus is on the GetMyProperty then all the occurrence of the MyProperty are highlighted with dotted rectangle now change the MyPrperty in GetMyProperty to whatever name you want to give, I have changed it to FirstName and hit tab key all the occurrence of  MyProperty is changed to FirstName. Which you can see in the Image 3 as below.
Image 3
The last thing you have to do is provide the name of the class who is owning this property and you can provide it in the ownerclass which is underline red in the Image 2 and Image 3.

3- propdp :
When you write propd and press the tab key then code for the dependency property is generated which can be seen in the Image 4.  Here you can see the default data type is int and the default name of the property is MyProperty.

Image 4
Now you can change the data type and the dependency property name which is described in propa for the attached property.

4- propfull :
When you type propfull and press the tab key then it will generate the code which is shown in the image 5, here you can see that it has private variable and public property, by default the data type of the variable is int and the name of the variable is myVar and the property name is MyPropery.
Image 5
As you can see in the Image the data type, the variable name and the property name are background of yellow mean you can change them by changing the data type first and press tab key then the variable name and press key and at the end property name and press key, you don't need to use the mouse for this, all this can be done by using the tab key.

5- propg :
When type propg and hit the tab key the code generated is shown in the Image 6, here you can see that property is generated with private setter.
Image 6



As we use more properties in our applications it is quite easy to remember these code snippet and generate code for the properties , attached properties and dependency properties.

All and any comments / bugs / suggestions are welcomed!


Saturday, October 23, 2010

Range Validation Rule

In this post I will show you one of the rule which is quite often used in applications is the Range validation, To check the range of the input user control so that user can't enter less or more then the minimum and maximum value respectively. In my previous post I have show you how to use the validation rules you can read it if you don't have any idea about the validation rules.This post is the continuity of the previous post.
Let us start with the range validation rule example. The example code for this example is the same as I have used for the previous post I have added new validation rule with the name of the RangeValidation in the ValidationRules folder, where all the validation rules are placed.In the List 1 you can see the complete class for the RangeValidation rule. Here you can see that I have three properties one for the MaximumLength  and MinimumLength for checking the maximum values entered in the user input control and to check the minimum value entered by the user in the input control respectively.

public class RangeValidation : ValidationRule { public int MaximumLength { get; set; } public int MinimumLength { get; set; } public string FieldName { get; set; } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string strValue= value as string; int intLength = (strValue == null) ? 0 : strValue.Length; if ((intLength > MaximumLength) && (MaximumLength > 0)) return new ValidationResult(false, string.Format("{1} should be no longer than {0} characters.", MaximumLength, FieldName)); if (intLength < MinimumLength) return new ValidationResult(false, string.Format("{1} should be no shorter than {0} characters.", MinimumLength, FieldName)); else return new ValidationResult(true, null); } }
List 1

In the Validate override function you can see that I have first taken the value of the which is passed in the value parameter and then check the length of the string entered by the user by using the conditional operator. Then check for the maximum value if the MaximumLength is greater then 0 as the default value for the int property is 0 if you didn't set the value of the MaximumLength. In the next if condition I will check for the minimum value and if the value is valid then it will return the validation result with true and null parameter mean user input is valid.
In List 2 I have the xaml which is the view end of the example, Here you can see that I have used the range validation only for the first name of the user input control. Here you can see that I have set the maximum length and the minimum length for the user input control and also the name of the field "First name" which is used in the error message.

< TextBox Grid.Row="5" Grid.Column="1" Margin="2,1,20,1" Height="23"> < TextBox.Text> < Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True"> < Binding.ValidationRules> < validationRules:RequiredFieldValidation/> < validationRules:RangeValidation MaximumLength="50" MinimumLength="4" FieldName="First Name"/> < /Binding.ValidationRules> < /Binding> < /TextBox.Text> < /TextBox>
List 2
You can see the out of both the minimum and the maximum check in the Image 1 and Image 2 you can also see that field name is also used in the messages. Which is the First name in this case.
Image 1

Image 2

By using the properties in the validation rule you can pass additional parameter to the validation rules. As the Validate function only two parameter one is the value which is of type object and second one is the culture information but if you used the converter they (converter) can take parameter which is of type object as well. But the Validate function only take two parameter so in order to pass information to the Validate function you can use properties of the class to pass the information to the validate function.Hope you get some idea of how to pass extra information to the validate function.You can download the source code from here.  

All and any comments / bugs / suggestions are welcomed!


Tuesday, October 19, 2010

Math.DivRem Function

In this short post I will show a simple and helpful function for calculating the Quotient and the Reminder when doing math calculation.The System.Math static class contain the function with the name DivRem which is used to get the quotient and the remainder when dividing one value to the second value.Math.DivRem calculate the quotient of two 32-bit signed integers and also returns the remainder in an output parameter.

int intQuotient = 0; int intRemainder = 0; intQuotient= Math.DivRem(19, 5, out intRemainder); Console.WriteLine("Reminder: {0} and Quotient : {1}", intRemainder, intQuotient); Console.ReadKey();

The output of the above code will be, Here you can see that remainder is 4 and quotient is 3 when dividing 19 with 5.

Reminder: 4 and Quotient :3

The parameter which are passed to the Math.DivRem are.
1- The first parameter will be dividend.
2- The second parameter will be Divisor.
3- The third parameter will be the remainder as output.

The Math.DivRem method performs an essential function for certain mathematical programs. If you need to calculate the remainder and store it after a division operation, use the Math.DivRem method instead of the division (/) or modulo (%) operators.


All and any comments / bugs / suggestions are welcomed!

Sunday, October 17, 2010

Validating User Input Using ValidationRule

In my post Input Validation using MVVM Pattern I have show you how to validate user input using the IDataErrorInfo interface in the MVVM pattern.Now in this post I will show you how to validate user input using the ValidationRule class.The ValidationRule has one abstract method which is used to write the logic for the validation of the input.I have used same example as I have used in the Input Validation using MVVM Pattern but instead of using the IDataErrorInfo interface I have used the ValidationRule class and its abstract method.
Let us start with our example code of how to validate the user input using the ValidationRule class using MVVM.I have create separate folder for the modal, view modal and the view and also for the resource dictionary I have create the theme folder and for the ValidationRule I have create ValidationRules folder all my classes which are inherit from ValidationRule class are placed here. So that all the validation rules can be found by placing on reference at the top of the view.

Model:
         In model I have one class with name PersonModel which has the UserID, Fist Name, Last Name, Full Name,EmailID, Contact Number and Date of birth properties. The PersonModel class is inherit from the INotifyPropertyChangedProperty interface So that in case of the change in the data in the modal is , it will send back the new changes to the view, As in case of the First Name and Last Name which are changed and send back to the view to display the Full name which is raising the Property Changed event of the INotifyPropertyChanged.

ViewModel:
In view model folder I have one class with the name PersonViewModel which has the commands and the properties of binding the control in the view. These properties are the IsDialogClose ( You can find more detail about the IsDialogClose over here. I have discuss in detail about how to close the view from the view model) and the is the Person property of the PersonModel and the save and the cancel command are there.
ValidationRules:
Before discussing the View of the MVV, I will discuss the ValidationRules folder first as I have define the ValidationRules which are placed in the ValidationRules folder.In the List 1 you can see that I have one class with the name  RequiredFieldValidation which is inherit from the ValidationRule and implement the abstract method. You can see that the return type of the Validate method is the ValidationResult in case of invalid date the Validation return is pass the value false along with the error message and in case of valid data the ValidationResult is passed the value true.

public class RequiredFieldValidation : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string strValue = value as string; if ((strValue.Length == 0) || ((strValue.Length > 0) && (strValue.Trim().Length == 0))) return new ValidationResult(false, "Field is required."); return new ValidationResult(true, null); } }
List 1

In the List 1 you can see that I have simple logic for the required field. I will check for the length of the value to be passed and also if the value is empty string then it will also report it as invalid as in some case we will not allow user to enter only the space in the required field.Now our required field is ready. I also have the email validation validator there in the ValidationRules folder which is used to validate the email address.
View:
Now I have validation rules for the user input now it time to bind the rules with the input controls. In List 2 you can see the xaml of the email input control here you see that I have used the the binding tag and set the Path (which is the name of the property define in the model or in view model as I have define in the model so I have set the DataContaxt of the grid which hold the input control like the first name, last name , email address etc, The Person property is define in the ViewModel which is of type PersonModel). The UpdateSourceTrigger is set tot he PropertyChanged which is LostFocus by default. when the value in the text box is change then the validation take place. Mode is set to TwoWay and also the ValidationOnDataErrors and ValidationOnExceptions are set to true.

< TextBox Grid.Row="5" Grid.Column="1" Margin="2,1,20,1" Height="23"> < TextBox.Text> < Binding Path="ContactNumber" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" ValidatesOnDataErrors="True" ValidatesOnExceptions="True"> < Binding.ValidationRules> < validationRules:RequiredFieldValidation/> < validationRules:PositiveInteger/> < /Binding.ValidationRules> < /Binding> < /TextBox.Text> < /TextBox>
List 2
Next is the binding of the ValidationRules, The Bidning has the property ValidationRules which is used to set the validation rules. Here you can see that for the email validation I have set the Required field validation and also the valid email ValidationRules. Which I have placed in the ValidationRules folder.
The output of the both the validation of the email is shown in the Image 1 and Image 2.

Image 1


Image 2

Hope you get starting point of how to use the ValidationRule for the input validation using MVVM. In application whether it is web or desktop required field validation is common and it is easy to change to change the message or required field validation on common location and later you can change it as well for whole application.You can download the source code from here.  


All and any comments / bugs / suggestions are welcomed!