Friday, May 29, 2009

Page.IsValid and Validate And JavaScript

In this post I will try to explain you how you can use the Page.IsValid and Validate function in web application.Here I have a situation where I have to used the IsValid property and the Validate function in one of the web page. The problem is When you have some validation on client side and depending on the validation you return either true or false from the client validation function, If the client validation return true then asp.net validator are not fired. The asp.net validator like require field validator, range validator, regular expression validator and custom validator etc. So in order to the client and asp.net validator work in parallel we have to use the validate and the IsValid property of the Page.
Let us start with our example code. For this example code I have two text box one is for the user name and the second one is for the user password, I have only one required field validator for the user name, So that you can understand what the problem is. Next I have three button control for three different scenarios,

1- Sign In (IsValid):
The First button which is the sign in (IsValid) consist of the some JavaScript validation and in the click event handler it will check the Page.IsValid property as well.
2- Sign In: It only has the server side validator and will be fire when you press this sign in button.
3- Sign In (JavaScript): This Sign in (JavaScript) button consist of the javascript validation and it will not check the Page.IsValid property.

Let me discuss this example in three steps

Step 1 (Server Side Validators):
In the first step which is very simple one and will fire only the server side validator and you can see this by pressing the simple Sign in button. If you don't have any of the client side validation then only the server side validator are fires and you will see the validators message on the form. Here is the output when you will click the Sign In button.



Step 2 (Server Side Validator And Client Side Validation):
In the next step which is performed on the Sign In (JavaScript) button, this button has some client side, which is added as the attribute of the button and the attribute is the click event of the button. For this problem I have one javascript function. which only return true, so that you can understand what the problem is. In this case as the client side validation return true so the server side validation is not catch and the server side event handler for the button is executed, and in this case as I have put the Server.Transfer to redirect to the next page. The server side validation is not catch and user will not see the validator message although user didn't enter the login name in this case.

Step 3 (Page.Validate And Page.IsValid):
Now from the step 2 we have notice that although we have server side validator but when the client side validation return true value then the server side validator are not catched and the page is redirected to the next page. To solve the problem in the step 2 , mean to check the validity of the validator we will use the Page.IsValid and Page.Validate. Here is the code which is used to validate the server side validators.
Page.Validate();
if (Page.IsValid)
Server.Transfer("frmSecondPage.aspx");
In the code above I have called the Page.Validate() function.This method is invoked when a user clicks any ASP.NET server control that has the CausesValidation property set to true, which is the default. These include the Button, ImageButton, and LinkButton Web server controls, the HtmlInputButton, HtmlInputImage, and HtmlButton HTML server controls, and controls that can automatically post back to the server such as the TextBox, CheckBox, ListControl, and BulletedList controls. To disable validation for any button control on the page, set the button control's CausesValidation property to false.
When this method is invoked, it iterates through the validation controls contained in the ValidatorCollection object associated with the Page.Validators property and invokes the validation logic for each validation control in the current validation group. The validation group is determined by the control that posted the page to the server. If no validation group is specified, then no validation group is used.
Then to before redirection I have check the Page.IsValid property which return either true or false depending on the result of the validators on the page. For this property to return true, all validation server controls in the current validation group must validate successfully. You should check this property only after you have called the Page.Validate method, or set the CausesValidation property to true in the OnServerClick event handler for an ASP.NET server control that initiates form processing.If you force validation of a validation group using the Validate method, then all validation controls in the specified validation group must validate successfully as well.
So by using the Page.Validate and Page.IsValid property we solved our problem of catching the validity of the server side validators.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Thursday, May 28, 2009

Changing Theme In WPF

In my last post about the WPF ListBox Control, one of the reader has send link in the comments about the theme of the WPF and silver light controls. I have downloaded the sample template from the Xaml Template and checked the controls, they look very fantastic, then I have search about the control template on the net and found some usefull link about the control template. Here I will show you how you can use that templates in your application and how you can change the resource dictionary at run time.
After search on internet I have found some useful resource dictionaries from CodePlex, and these resource dictionaries are free of cost and you can download the source code as well, and if you want to make some changes then you can change the colors as well. Here is the output images of the my example code, I have put some of the control in the main so that you can see the result of the resource dictionary. First is the Expression Black theme.


Here is the Shiny Blue theme



And last image shows the Bureau Black themes.


Here is the small piece of code which is used to load the resource dictionary at run time you can see that I have used the Application.Current.Resources.Source, to load the new resource dictionary
switch(cboTheme.SelectedIndex)
{
case 0:
Application.Current.Resources.Source = new Uri("../../Themes/BureauBlack.xaml", UriKind.Relative);
break;
case 1:
Application.Current.Resources.Source = new Uri("../../Themes/BureauBlue.xaml", UriKind.Relative);
break;
case 2:
Application.Current.Resources.Source = new Uri("../../Themes/ExpressionDark.xaml",UriKind.Relative);
break;
case 3:
Application.Current.Resources.Source = new Uri("../../Themes/ExpressionLight.xaml", UriKind.Relative);
break;
case 4:
Application.Current.Resources.Source = new Uri("../../Themes/ShinyBlue.xaml", UriKind.Relative);
break;
case 5:
Application.Current.Resources.Source = new Uri("../../Themes/ShinyRed.xaml",UriKind.Relative);
break;
case 6:
Application.Current.Resources.Source = new Uri("../../Themes/WhistlerBlue.xaml", UriKind.Relative);
break;
}
Hope you will get some knowledge about how to change the theme of the WPF application at run time.You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


Monday, May 25, 2009

Date And Time Format C#

During the development of project you should come across the date manipulation and displaying specific format of the date or time to the user depending on the situation. I have also come across this situation where I have to display the time format in 12 hours and need to show it in Am/Pm format. Here in this short post I will try to summarize the maximum number of date format which I have used in my project, hope some of them may be helpful to you as well. First here are the predefined string functions which are used to get the date and time.
Date/Time Format
Output
DateTime.Now.ToLongDateString()
Monday, May 25, 2009
DateTime.Now.ToShortDateString()5/25/2009
DateTime.Now.ToLongTimeString()8:47:57 PM
DateTime.Now.ToShortTimeString()
8:47 PM
DateTime.Now.ToString()
5/25/2009 8:47:57 PM


Now I will list down some the custom string format to get the date. In the below date format I have use the (/) backslash as separator, you can use separator like -(minus) sign as well. In the format below I have started with month/day/year, You can change it to day/month/year, or year/month/day etc.In the blow format as you can see that when I have placed 2 characters like dd the output is in the format of digit for the month and day case not in case of year. And in case of three characters the output will be in character case like Mon for the day and May for the month, and last is the case of the four character where the day is displayed in full name like in this Monday and In case of month which is three character May, it will display full name of month.
Date Format
Output
DateTime.Now.ToString("MM/dd/yyyy")
05/25/2009
DateTime.Now.ToString("MM/ddd/yyyy")
05/Mon/2009
DateTime.Now.ToString("MM/dddd/yyyy")05/Monday/2009
DateTime.Now.ToString("MMM/ddd/yyyy")
May/Mon/2009
DateTime.Now.ToString("MMMM/ddd/yyyy")
May/Mon/2009
DateTime.Now.ToString("MMMM/ddd/yy")
May/Mon/09

Here are the sum of the time format which may helpful to you. Here HH combination or single H is used for the Hours and MM or M is used for minutes and ss or s is used for the seconds portion and the last one which I really forget whenever I have to show time in 12 hours is the tt combination which is used to show time in Am/Pm format.
TimeFormat
Output
DateTime.Now.ToString("HH:MM")
22:01
DateTime.Now.ToString("HH:MM:ss")
22:05:49
DateTime.Now.ToString("hh:mm:ss")10:01:49
DateTime.Now.ToString("hh:mm:ss tt")
10:01:49 PM
DateTime.Now.ToString("hh:mm tt")
10:01 PM
DateTime.Now.ToString("H:m")
22:2

Hope you will get some of the date and time format and get some sort of understanding of how you can use them to get the required output regarding the date and time. If you have any suggestion please share it withe me.

All and any comments / bugs / suggestions are welcomed!


Sunday, May 24, 2009

WPF ListBox Control

I have nearly 4 years of professional experience of the software engineering, In that 4 years I have used nearly all the controls like combo Box, grid view, list view etc controls to is display information to the user but I hardly remember that I have used the List Box control in my any of the project. But now when I am learning the WPF I have used the list box control for the first time and I have found it really cool control regarding the WPF environment. In this post I will discuss the List box control and also the Data Template and the triggers of the control template. Hope you will get some starting point from this post.
For this post I have the customer table in the XML format file and I get data from that file which is place in the DB folder, in the bin directory of the project. The reason for placing the customer table in the XML file is , if any of the user didn't have the sql server then this solution still work form him/her. The goal of this post is to define the layout of the each of the item in the list box item and to display more information regarding one record to display on the list box control. And also to learn about the triggers.

Data Template:
First of all I have define the Data Template for the list box item.DataTemplate are used to specify the visualization of your data objects. DataTemplate objects are particularly useful when you are binding an ItemsControl such as a ListBox to an entire collection. Without specific instructions, a ListBox displays the string representation of the objects in a collection. In that case, you can use a DataTemplate to define the appearance of your data objects. The content of your DataTemplate becomes the visual structure of your data objects. Here is how the output of the list box how its looks like after I have define the data template for the list box item .


Here is the xaml for the Data template of the item template, and I have place the data template for the list box item within the item template area. I have used the grid control and set the columns and the rows of the grid. Next I have added three text block control to display the company name, city and the country of the customer. The text block are displayed in the second column of the grid and I have used the 1, 2 and 3 rows of for the company name, city and the country respectively. The below xaml give the above image output.

<ListBox.ItemTemplate >
<DataTemplate >
<Grid Margin="2,1,2,1" VerticalAlignment="Top" Height="82" >
<Grid.RowDefinitions>
<RowDefinition Height="2"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="2"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.05*"/>
<ColumnDefinition Width="0.45*"/>
<ColumnDefinition Width="0.45*"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Text="{Binding CompanyName}" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" />
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="{Binding City}" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" />
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Top" Text="{Binding Country}" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>

Style And Control Template :
Next I have to set the look of the item of the list box control. For this I have used the style and the control template to set the appearance of the list box item.Windows Presentation Foundation (WPF) styling and templating refer to a suite of features (styles, templates, triggers, and storyboards) that allow designers of an application, document, or user interface (UI) to create visually compelling effects and to standardize on a consistent appearance for their product. Although an author or designer can customize appearance extensively on an application-by-application basis, a strong styling and templating model is necessary to allow maintenance and sharing of the appearance within and among applications. Windows Presentation Foundation (WPF) provides that model.(source). Styles are used to apply common property to more then one element. Below is the code for the style I have used for the list box item, As I want to set common properties for the list box item so I have set the TargetTtype to the ListBoxItem. The common properties such as width, VerticalContentAlignment , Margin, Padding and Foreground color the list box Item. After setting the common properties of the list box items next I have to set the control template for the list box item, to change the appearance and structure of the list box item. For this to change the structure and the appearance of the ListBox item I have set the template property of the style and set the value of the template property.

<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Width" Value="Auto" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Margin" Value="1" />
<Setter Property="Padding" Value="3" />
<Setter Property="Foreground" Value="#FFFFFFFF"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Grid ShowGridLines="True">
<Grid VerticalAlignment="Top" Height="82" >
<Grid.RowDefinitions>
<RowDefinition Height="2"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="0.33*"/>
<RowDefinition Height="2"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.05*"/>
<ColumnDefinition Width="0.45*"/>
<ColumnDefinition Width="0.45*"/>
</Grid.ColumnDefinitions>
<Border Name="brdLeftBorder" Margin="2,2,0,2" Grid.RowSpan="5" CornerRadius="3,0,0,3" Panel.ZIndex="1" Background="{DynamicResource NormalItem}"/>
<Border Margin="0,0,0,0" Grid.Column="1" Grid.ColumnSpan="2" Grid.RowSpan="5" Background="#FF666666" CornerRadius="0,5,5,0" />
<Border Margin="0,0,0,0" Grid.ColumnSpan="3" Grid.RowSpan="5" Background="{x:Null}" BorderThickness="2,2,2,2" BorderBrush="#FF202020" CornerRadius="5,5,5,5" Panel.ZIndex="0"/>
</Grid>
<Grid>
<ContentPresenter />
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="brdLeftBorder" Property="Background" Value="{DynamicResource SelectedItem}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="brdLeftBorder" Property="Background" Value="{DynamicResource MouseOver}" />
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

As you can see in the above example, the ControlTemplate class has a TargetType property that is similar to the TargetType property of the Style class. However, note that unlike Style and DataTemplate, ControlTemplate objects do not have the notion of an implicit key. In other words, if you have a standalone ControlTemplate with the TargetType property set to a type, the ControlTemplate does not get applied to that type automatically. Also note that the TargetType property is required on a ControlTemplate if the template definition contains a ContentPresenter.


After adding the value of the template property of the style above is the look of the listBox item. Now its time to define some user interaction related functionality by using triggers.

Triggers:
In the above code I have used the trigger tag in the control template before closing tag of the control template. I have used two trigger one is the IsSelected and the other one is the IsMouseOver trigger. Trigger are used to applies property values or performs actions conditionally. I have define the Linear gradient brush with the key NormalItem which is of green gradient, MouseOver which is of orange gradient and the SelectedItem which is of blue gradient. And here is the output of the all the three gradients.




In the triggers what I have did is to change the background of the left side border. In the IsSelected trigger I have change the background color of the left side border to the SelectedItem gradient. In the second trigger of the control template which is to change the left border to change to the MouseOver gradient , same property the background property of the target brdLeftBorder is used. One important thing about the trigger is when the condition is no more true of the trigger, say in case of IsMouseOver , when the mouse is out of the item then previous setting are applied. Hope you get some starting point about the control template, data template and the trigger, Send me your suggestion regarding this article, your suggestions are most welcome.

You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Sunday, May 17, 2009

WPF Card View

In this post I will show you how you can display user information using WPF Card View, here I have some of the Card to display the user information. I know there is some inexperience when you watched the WPF cards as there are my first time designing using the expression blend.






I have attached the source code of the above cards and you can download it from here. So that if you think that any of the above card is used in your project you can used it easily, as the Source code is give.

All and any comments / bugs / suggestions are welcomed!

Friday, May 15, 2009

Jquery Selectors

In my one of the projects One of the client required some sort of report about his system, for that reports I have generated the html table in code behind file , from server side.Here is the format of the report.


You can see from the above report that each alternative color is give to each of the row in the table. While designing the above table I have to give the different css class to the each cell depending upon the location of the cell in the row, I have different css class for the first cell of each of the row as the style properties such as the top, bottom, left and right of the first cell of each row is different from the cell next to it. So I have 3 css class for the cell one for the very first cell of the table and one for the first cell of the every row and the one for the remaining cells in the table. Let us start with the example of how to achieve this functionality with the use of jquery selectors.
:even and :odd Selectors:
The even and the odd selectors are very handy selectors of the jquery. As there name is self describing even selector is used to select the even elements and the odd selector select the odd elements when used. The :odd and :even selectors use JavaScript's native zero-based numbering. Therefore, the first row counts as 0 (even) and the second row counts as 1 (odd), and so on.

$('#tblMainTable tr:odd').addClass('alternativeRowColor');

In the above statement I have provided the name of the table which is tblMainTable so that the alternative row color is applied only to the table of the given name, this is handy when you have multiple table in you aspx form and you want to apply the alternative row color to a given table. If you omit the name of the table then it will apply the alternative row color to the all the table in the web form or aspx page. If we omit the table name and the web form has multiple table then the alternative row color is applied in the following order. If the last row of the first table has a white background, then first row in the next table would have the "alternate" background. Same is the use of the even select which will select the even rows or elements, starting from the 0(zero) index and then 2 and so on.

:first and :last Selectors:
By using the odd and the even select I have assign the alternative color to the table rows now I have to assign the css classes to the table cell based on the location of the cell in the table and row. Here is the statement or jquery code which is used to assign the css classes to the first row of the table , you can say that header row of the table, I have not used thead part of the html table. For the very first cell of the table I have set the top, bottom, left and right border and set the style and the color of the border as it is the fist cell so it include all four side border. By using the statement below I have give the name of the table and then select the first row of the table and then the first cell of that row.The first selector will matches the first selected element and the last selector will matchs the last selected element.

$('#tblMainTable tr:first td:first').addClass('tdBorderTopLeftMostCell')
$('#tblMainTable tr:first td:first').nextAll().addClass('tdBorderTopMostCell');

As the first cell of the table is set the border on all side so the next cell will have no border on lef side but that will contain the border on remaining three sides. So I have to set different css class for the remaining header cell of the table. For this purpose I have apply same css class for the remaining cells and need to select the remaining cells of the table. For this purpose I have repeat the previous statement and after that function call I have call the nextAll function which will return all sibling cells after the first cell. The nextAll find all sibling elements after the current element. Like the nextAll jquery has the prevAll which will select the previous elements.The last selector will select the last element.
For the rest of the rows as they are same in nature, like the first cell of each row has the left, bottom and the right side border and the remaining cell in same row has only the bottom and right side borders, so you can say that they have same in nature. Here is the small piece of the jquery code which will set the border to the first and the remaining cell of the rows.

$('#tblMainTable tr').each(function(){
$('td:first', this).addClass('tdBorderLeftMostCell');
$('td:first', this).nextAll().addClass('tdMiddleCells');
});

In the above code I have used the each function of the jquery to iterate through the every row of the table and then using that row by using this key word apply the css class to the first and the remaining cell of the current row. As in this post I am discussing the some of the selector of the jquery so I will not discuss the each function of the jquery, will discuss it in other post.

You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!

Sunday, May 10, 2009

params C#

Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a single-dimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value parameter.
Here is the code example of how to use the params keyword when passing the parameter to the function
static void Main(string[] args)
{
IntegerParams(1, 2, 3);
ObjectParams(1, 'a', "test");
int[] myarray = new int[3] { 10, 11, 12 };
IntegerParams(myarray);
}

public static void IntegerParams(params int[] pintList)
{
for (int intIndex = 0; intIndex < pintList.Length; intIndex++)
Console.WriteLine(pintList[intIndex]);
Console.WriteLine();
}

public static void ObjectParams(params object[] pobjObjectList)
{
for(int intIndex= 0; intIndex < pobjObjectList.Length; intIndex++)
Console.WriteLine(pobjObjectList[intIndex]);
Console.WriteLine();
}
In the above code sample, I have two function one which take the int and the other one which take the object, I have set the same name for the both of the function, mean one is the IntParams and the second one is the ObjectParames function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:

params datatype[] argument name

Note that the argument passed using params argument should be an single dimension array also it should be the last argument in the argument list for the function.The params parameter can then be accessed as an normal array. You can call the function without passing single parameter to it, and there will be no error.

All and any comments / bugs / suggestions are welcomed!


Detecting Useragent Using Jquery

Browser detection might seem, at first, like a logical way to deal with browser differences. After all, it’s easy to say: “I know what the set of capabilities of browser X are, so testing for the browser makes perfect sense, right?” But browser detection is full of pitfalls and problems.Browsers identify themselves by setting a request header known as the user agent string. Parsing this string isn’t for the faint-hearted. In addition, many browsers now allow their users to spoof this string, so we can’t even believe what it tells us after we do parse it! A JavaScript object named navigator gives us a partial glimpse into the user agent information, but even it has browser differences. We almost need to do browser detection in order to do browser detection!
jQuery provides a set of flags that we can use for branching that are set up when the library is loaded, making them available even before any ready handlers have executed. They are defined as properties of an object instance with a reference of $.browser. The formal syntax for this flag set is as follows:

$.browser
Defines a set of flags that can be used to discover to which broad set of browser families the
current user agent belongs. These flags are as follows:
  • msie—Set to true if the user agent header identifies the browser as Microsoft Internet Explorer.
  • mozilla—Set to true if the user agent header identifies the browser as any Mozillabased browser. This includes browsers such as Firefox, Camino, and Netscape.
  • safari—Set to true if the user agent header identifies the browser as Safari or any Safari-based browser.
  • opera—Set to true if the user agent header identifies the browser as Opera.
  • version—Set to the version number of the rendering engine for the browser.
Note that these flags don’t attempt to identify the specific browser that’s being used; jQuery classifies a user agent based upon which family of browsers it belongs to. Browsers within each family will sport the same sets of characteristics; specific browser identification should not be necessary. The vast majority of commonly used, modern browsers will fall into one of these four browser families.
The version property deserves special notice because it’s not as handy as we might think. The value set into this property isn’t the version of the browser (as we might initially believe) but the version of the browser’s rendering engine. For example, when executed within Firefox 2.0.0.2, the reported version is 1.8.1.6— the version of the Gecko rendering engine. This value is handy for distinguishing between IE6 and IE7, containing 6.0 and 7.0 respectively.
We mentioned earlier that there are times when we can’t fall back on object detection and must resort to browser detection. One example of such a situation is when the difference between browsers isn’t that they present different object classes or different methods but that the parameters passed to a method are interpreted differently across the browser implementations. In such a case, there’s no object to perform detection on.

All and any comments / bugs / suggestions are welcomed!


Tuesday, May 5, 2009

Fold Animation Using WPF

During my search on net I came across jQuery UI - Demos and documentation site, where I have see many effects like blind, clip explode, bounce etc by using jquery. But the most interesting effect on that list to me was the Fold effect. So I try to do that fold animation using WPF, as these days I am working in WPF so that is why I want to do in WPF. The fold animation I have created for the example is same as it was given in the jQuery UI - Demos and documentation, but one additional thing I have done is , when animation finished mean when fold is completed then I have open the window in same manner, you can say fold close animation and fold open animation at the same time. So let us start with example code.
For this example I have the following screen. In the screen you can see that I have same GUI as you can see on the jQuery UI - Demos and documentation web page. I have a button control and One filled area which looks similar to the area shown in jQuery UI - Demos and documentation Page.

Here is the code which is used for the fold animation. In the code you can see that I have two double Animation object one for the height and the second one is for the width of the control. For the height animation I have set the To property to 30 and from property to 200 mean I want to change the height of the control from the 200 to 30 by using the double animation object. Then I set the duration of the double animation object how much time it will take to complete the height of the control. In the next statement I have Set the target name which in this case is my Grid object named "grdFoldAnimationGrid", using the name property of the grdFoldAnimationGrid. And In the next statement I have set the Target Property of the control which is animated by the height double animation object. As I am using the Grid Control for the animation so here I have used the Grid.HeightProperty.
DoubleAnimation dblaHeightAnimation = new DoubleAnimation();
dblaHeightAnimation.To = 30;
dblaHeightAnimation.From = 200;
dblaHeightAnimation.Duration = new Duration(TimeSpan.FromSeconds(.3));
Storyboard.SetTargetName(dblaHeightAnimation, grdFoldAnimationGrid.Name);
Storyboard.SetTargetProperty(dblaHeightAnimation, new PropertyPath(Grid.HeightProperty ));

DoubleAnimation dblaWidthAnimation = new DoubleAnimation();
dblaWidthAnimation.To = 0;
dblaWidthAnimation.From = 220;
dblaWidthAnimation.Duration = new Duration(TimeSpan.FromSeconds(.3));
dblaWidthAnimation.BeginTime = new TimeSpan(0, 0, 0,0,300);
Storyboard.SetTargetName(dblaWidthAnimation,grdFoldAnimationGrid.Name);
Storyboard.SetTargetProperty(dblaWidthAnimation, new PropertyPath(Grid.WidthProperty));

Storyboard strbStoryBoard = new Storyboard();
strbStoryBoard.Completed += new EventHandler(strbStoryBoard_Completed);
strbStoryBoard.Children.Add(dblaWidthAnimation);
strbStoryBoard.Children.Add(dblaHeightAnimation);

strbStoryBoard.Begin(this);
For the second animation object which is to animate the width of the control. I have first set the To and from properties of the width double animation object and then set the Duration property. Which are same for the height double animation object. The key to the width double animation object is the begin time property, which set the time when the width double animation object will start working.I have set the begin time of the width double animation to the time taken by the height double animation to complete. If you look at the code again you can see that the Duration of the height double animation object is set to .3 second and the begin time of the width double animation is set to 300 milliseconds. So when the height animation is completed then the width animation will start.
The code above is used to close or you can say hide the control, now below is the code which is used to open/ show in the same manner, the fold open manner. The code below is same as above but there are as some minor and important changes related to show the control in fold animation. First if you look at the code you can see that to open/show the control for fold animation in this case the width of the control is animated first and for this purpose I have animated the width of the control first but little addition for this is that I have set the begin time property of the width to the 600 second which mean that when the fold animation close is completed then it will wait for 600 milliseconds and then start the open fold animation.
DoubleAnimation dblaWidthAnimation = new DoubleAnimation();
dblaWidthAnimation.To = 0;
dblaWidthAnimation.From = 220;
dblaWidthAnimation.Duration = new Duration(TimeSpan.FromSeconds(.3));
dblaWidthAnimation.BeginTime = new TimeSpan(0, 0, 0,0,600);
Storyboard.SetTargetName(dblaWidthAnimation,grdFoldAnimationGrid.Name);
Storyboard.SetTargetProperty(dblaWidthAnimation, new PropertyPath(Grid.WidthProperty));

DoubleAnimation dblaHeightAnimation = new DoubleAnimation();
dblaHeightAnimation.To = 30;
dblaHeightAnimation.From = 200;
dblaHeightAnimation.Duration = new Duration(TimeSpan.FromSeconds(.3));
dblaHeightAnimation.BeginTime = new TimeSpan(0, 0, 0,0,900);
Storyboard.SetTargetName(dblaHeightAnimation, grdFoldAnimationGrid.Name);
Storyboard.SetTargetProperty(dblaHeightAnimation, new PropertyPath(Grid.HeightProperty ));

Storyboard strbStoryBoard = new Storyboard();
strbStoryBoard.Children.Add(dblaWidthAnimation);
strbStoryBoard.Children.Add(dblaHeightAnimation);

strbStoryBoard.Begin(this);

After the width animation the height animation will be start for which I have set the begin time to the 900 milliseconds, as the begin time of the width animation is 600 plus the duration time of the width animation is 300. One important thing which I have to mention here is that the To and From properties of the both the height and the width animation are just opposite to the what we have set the first code, the To and From properties of width animation object has the value 220 and 0(zero) and the for height animation object is To and From values 200 and 30 respectively.So that the control will be shown.You can download the source code from here.


All and any comments / bugs / suggestions are welcomed!


Sunday, May 3, 2009

WPF Double Animation Lab

In my Post on Jquery Sliding Animation using WPF I have explain the sliding animation which is used in the jquery. In that post I have explain in dept what is the double animation and what are important property when need to be set when double animation is used for the control. Now for this post I have try to develop the Test Lab which is used to produce different animation in one example instead of write the one post per animation.
For the example code below is the image of the main form of the application. Here you can see in the main form that I have two combo box control one is used to set the horizontal alignment of the control and the second one is used to set the vertical alignment of the control (control which is used to animate and will be discuss later). After the combo box controls I have added three radio button control, the name of the radio buttons are Height , width and the both (height and width). If you select the height radio button then the control will be animated only height wise and if you select the width then the control will be animated width wise but if you select the both radio button then the control will be animated both height and width wise.


Now come to the control which will be animated. I have used the border control for the animation and I have set the background color and the border color of the border control to purple color. As you can see in the above image. One more control which is left but is most important control which is the button control which is used to start animation. In the Button click event handler the first statement I have write is to disable button control before animation and when animation completed then I have enable the button control. The reason of disabling the button control at the start of animation and then enabling the button control when animation completed , so that you get familiarity of the animation completed event handler which is fired when the animation is completed.You can download the source code from here.Download the source code Test the animations. By using this test lab you can produce the sliding , blind etc animation just by changing the vertical and horizontal alignment of the control


All and any comments / bugs / suggestions are welcomed!

Friday, May 1, 2009

GridView Paging And Sorting

In this post I will try to explain how you can apply paging and sorting on the grid view control. Most of the developer use the paging and sorting when they have used the grid view control in there web application.For this example I have a grid view control only in my web page. I have used the XML to store the data which is displayed in the grid view control. Detail related to the paging and sorting functionality will be provided as they are used in the example.

Grid View Paging:
In order to perform page functionality in the grid view control what you have to do is to set the AllowPaging property to true for the grid view control.By default, the GridView control displays 10 records on a page at a time. You can change the number of records displayed on a page by setting the PageSize property.When paging is enabled, an additional row called the pager row is automatically displayed in the GridView control. The pager row contains controls that allow the user to navigate to the other pages. You can control the settings of the pager row (such as the pager display mode, the number of page links to display at a time, and the pager control's text labels) by using the PagerSettings property. The pager row can be displayed at the top, bottom, or both the top and bottom of the control by setting the Position property. You can also select from one of four built-in pager display modes by setting the Mode property. The following table describes the built-in display modes. (Source)
Member NameDescription
PagerButton.NextPreviousA set of pagination controls consisting of previous and next buttons.
PagerButton.NextPreviousFirstLastA set of pagination controls consisting of previous, next, first, and last buttons.
PagerButton.NumericA set of pagination controls consisting of numbered link buttons to access pages directly.
PagerButton.NumericFirstLastA set of pagination controls consisting of numbered and first and last link buttons.
In the above list of pager Button mod the Numeric is the default mod applied when you set the allowpaging property of the grid view control to true.The grid view control automatically hide the pager row if there is one page record int the data source of the grid view. Here is the list of event which are provided by the grid view control when paging action is occur in the grid view control.
  1. PageIndexChanged: Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control.
  2. PageIndexChanging: Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation.
In the above list you can see that PageIndexChanged event is occurred after the grid view control handles the paging operation. So to handle the paging we need the PageIndexChanging event in order to perform the functionality which is necessary for handling the paging manually. So in my code example I have used the PageIndexChanging event of the grid view control. So when the any of the paging button is click I got the control to perform the manual paging on grid view control. In the PageIndexChanging event handler what I did is to call the SortDataTable function, which will sort the records. Then in the next statement the PageIndex property of the grid view control is assign the new value by using the argument of the function which is e.NewPageIndex which hold the new value of the page index( the page value , which user has clicked on the grid pager row).
protected void grdvResultGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdvResultGrid.DataSource = SortDataTable(GetGridDataTable(), true);
grdvResultGrid.PageIndex = e.NewPageIndex;
grdvResultGrid.DataBind();
}

protected DataView SortDataTable(DataTable ptblDataTable, Boolean pblnIsPageIndexChanging)
{
if (ptblDataTable != null)
{
DataView dataView = new DataView(ptblDataTable);
if (GridViewSortExpression != string.Empty)
if (pblnIsPageIndexChanging)
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GridViewSortDirection);
else
dataView.Sort = string.Format("{0} {1}", GridViewSortExpression, GetSortDirection());
return dataView;
}
else
return new DataView();
}
In the PageIndexChanging event handler I have called the SortDataTable function which take the data table and Boolean value, the Boolean parameter which is self describing is used for paging and sorting purpose, if the value of the parameter is true then sort the data on previous sorting value which can be either "ASC" (ascending) or "DESC" (descending). For sorting purpose I have used the DataView and then call the sort property of the DataView which will take the sort expression of column name following by sort order. In the above code We can sort the record by only one column, if you want to sort the records by multiple column names then you can combine the column names by separating them with comma (,) sign.

Grid View Sorting:
In order to achieve the sorting in the grid view control what you have to do is to set the AllowSorting property of the grid view control to true. When sorting is enabled, the heading text for each column field with its SortExpression property set is displayed as a link button. The SortExpression property for an automatically generated columns field is automatically populated. If you define your own columns through the Columns collection, you must set the SortExpression property for each column; otherwise, the column will not display the link button in the header. Clicking the link button for a column causes the items in the grid view control to be sorted based on the sort expression. Typically, the sort expression is simply the name of the field displayed in the column, which causes the grid view control to sort with respect to that column. Like the grid view paging I have used the sorting event handler for the sorting purpose.
protected void grdvResultGrid_Sorting(object sender, GridViewSortEventArgs e)
{
GridViewSortExpression = e.SortExpression;
int pageIndex = grdvResultGrid.PageIndex;
grdvResultGrid.DataSource = SortDataTable(GetGridDataTable(), false);
grdvResultGrid.DataBind();
grdvResultGrid.PageIndex = pageIndex;
}
Above is the code for the grid view sorting. I have used two view state to store the sort expression and the sort direction so that when page is post back the value are not reinitialized and these view state values are used to sort the grid view records when user change the page number of the grid view control, so that user can see the sorted order record in the grid view control. In the sorting event handler of the grid view control I have called the SortDataTable function but in this time the second parameter which is of Boolean type is passed the value false, mean the sort direction value will be changed this time and the function GetSortDirection() will be called to get the alternative value for the sort direction, So if the sort direction is Asc then it will change to the desc by looking at the value of the sort direction view state.You can download the source code from here


All and any comments / bugs / suggestions are welcomed!

GridView Gridline color

During web development I came across the problem of how to set the GridLine color in the gridveiew. Here is the simple line of code you can use to set the grid line color.

grdvOrders.Attributes.Add("bordercolor", "#acc0e9");

Here is the sample output of my grid view control when i have not used the above line of code in my Page_Load event handler. As I have set the GridLine property of the grid view control to Both so the grid line are shown here, but the color of the grid line are white.

And here is the output of the my grid view control when i have used the code of adding the border color to the attributes of the grid view control.



In the image above you can see the that grid line color is set now, which I have provided in the attribute of the grid view control. This is the short tip regarding the grid view control of how to set color of the grid line.

All and any comments / bugs / suggestions are welcomed!