Search content within the blog

Monday, December 5, 2011

Updating Source in WPF Data Binding

In WPF data binding, when source property is updated from target property is called as updating source property and is defined using UpdateSourceTrigger property of Binding object. This property is used to define how you want to update source. There are two binding modes are available TwoWay and OneWayToSource which causes update to source property on change of target property.

You can specify mainly three different values to UpdateSourceTrigger property of Binding. If you don’t specify any value to UpdateSourceTrigger it uses default.


PropertyChanged – It updates source property as soon as target property changed.

<TextBox Name="CustomerName" Height="30" Margin="5"
Text="{Binding Source={StaticResource MyCustomerData},
Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="0" Grid.Column="1" />

LostFocus – When target object loses focus as soon as source property is updated.

<TextBox Name="CustomerName" Height="30" Margin="5"
Text="{Binding Source={StaticResource MyCustomerData},
Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"/>

Explicit – Source property is updated when you call explicitly UpdateSource method from code.

<TextBox Name="CustomerName" Height="30" Margin="5"
Text="{Binding Source={StaticResource MyCustomerData},
Path=CustomerName, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>

Code:


BindingExpression bindingExpression =
CustomerName.GetBindingExpression(TextBox.TextProperty);
bindingExpression.UpdateSource();

Value Converters in WPF

Start Posting Your Contents Here


Value converters are used in Data binding. When source object type and target object type are different at that time value converts are used to manipulate data between source and target. Converter class must implement IValueConverter interface. The IValueConverter interface consists of two methods Convert and ConvertBack. Convert Method gets called when source updates target object and ConvertBack method gets called when target updates source object.


<StackPanel>
<CheckBox x:Name="ShowBackgroundCheckbox"
Content="Show Background" Margin="5" />
<TextBox Text="Value Converter" Margin="5"
Background="{Binding
ElementName=ShowBackgroundCheckbox, Path=IsChecked}"/>
</StackPanel>

In above example Textbox’s Background property is bound with Checkbox’s IsChecked property. This binding won't work because IsChecked property is Boolean and background is Brush type. So for successful data binding the source and target type must match which is not true in above XAML code. So we need to create one value converter which manipulates checkbox’s IsChecked property and textbox’s Background property.

<Window.Resources>
<local:BooleanToBackgroundConverter x:Key="booleanToBackground" />
</Window.Resources>

<StackPanel>
<CheckBox x:Name="ShowBackgroundCheckbox"
Content="Show Background" Margin="5" />
<TextBox Text="Value Converter" Margin="5"
Background="{Binding
ElementName=ShowBackgroundCheckbox, Path=IsChecked,
Converter={StaticResource booleanToBackground}}"/>
</StackPanel>

public class BooleanToBackgroundConverter:IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
bool result = (bool)value;
if (result)
{
return Brushes.LightBlue;
}
return null;
}

public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}









When Show Background checkbox is checked the textbox get filled with LightBlue background. To achieve that I created one class named BooleanToBackgroundConverter which implements IValueConverter interface. In our example Checkbox is source for textbox. So whenever user changes checkbox’s value the Convert method will get called. The ConvertBack method converts target value to source value. This method will get called when twoway binding established between source and target.

Converter Parameters
Additional information can be passed to value converter using converter parameter.

<TextBox Text="Value Converter" Margin="5"
Background="{Binding
ElementName=ShowBackgroundCheckbox, Path=IsChecked,
Converter={StaticResource booleanToBackground}, ConverterParameter=1}"/>

public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
bool result = (bool)value;
int param = Int32.Parse(parameter.ToString());
if (result)
{
if (param == 1)
return Brushes.Red;
return Brushes.LightBlue;
}
return null;
}








EventSetters in Style

Event can also be attached inside style. Style provides EventSetter inside you can add EventName and attach appropriate handler for that event.

<Window.Resources>
<Style x:Key="MyButtonEvent" TargetType="Button">
<EventSetter Event="MouseEnter" Handler="Button_MouseEnter" />
<EventSetter Event="MouseLeave" Handler="Button_MouseLeave" />
</Style>
</Window.Resources>
<StackPanel>
<Button Name="Cut" Content="Cut"
Height="40" Width="150"
Style="{StaticResource MyButtonEvent}" />
</StackPanel>

private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
btn.Background = Brushes.Red;
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
btn.Background = Brushes.Green;
}




In above example you can see that Button_MouseEnter and Button_MouseLeave handler is attached inside EventSetter of Style. Whenever mouse enter and leave it will change button background color.

Validate Data using IDataErrorInfo in WPF

WPF Data binding supports for business layer data validation using IDataErrorInfo interface. IDataErrorInfo interface was exists earlier in Windows forms application. Microsoft added support for binding to report error using IDataErrorInfo interface in WPF 3.5 version. IDataErrorInfo interface has two properties one is string Error and another is string indexer. String indexer accepts property name and returns corresponding error. To enable data validation using IDataErroInfo interface you must set ValidatesOnDataError property to True of binding object.

I have reused and modified example I demonstrated in my previous post Validation Rules in WPF. In that example I have added IDataErrorInfo interface and removed validation rules from XAML code. Let’s have a look on below modified example.

<Window.Resources>
<local:Employee x:Key="EmployeeInformation" />
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource=
{x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.20*"/>
<RowDefinition Height="0.20*" />
<RowDefinition Height="0" />
</Grid.RowDefinitions>

<TextBlock Text="Enter Name: " Grid.Column="0"
Grid.Row="0" Margin="3"/>
<TextBox Name="Name" Grid.Column="1"
Grid.Row="0" Height="30" Margin="3">
<TextBox.Text>
<Binding Source="{StaticResource EmployeeInformation}"
Path="Name" ValidatesOnDataErrors="True" />
</TextBox.Text>
</TextBox>
<TextBlock Text="Enter Age: " Grid.Column="0"
Grid.Row="1" Margin="3"/>
<TextBox Name="Age" Grid.Column="1"
Grid.Row="1" Height="30" Margin="3">
<TextBox.Text>
<Binding Source="{StaticResource EmployeeInformation}"
Path="Age" ValidatesOnDataErrors="True" />
</TextBox.Text>
</TextBox>
</Grid>

public class Employee : INotifyPropertyChanged, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
private int age;
public int Age
{
get { return age; }
set { age = value; OnPropertyChanged("Age"); }
}
//Implements INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
//Implements IDataErrorInfo
public string Error //WPF doesn't use this property
{
get { return null; }
}

//Data Validation here.
public string this[string columnName]
{
get
{
switch (columnName)
{
case "Name":
{
return ValidateName(columnName);
}
case "Age":
{
return ValidateAge(columnName);
}
}
return null;
}
}

private string ValidateName(string columnName)
{
if (Name == null) return null;
if (Name.All(c => char.IsLetter(c) || c == ' '))
return null;
return "Please enter only alphabets";
}

private string ValidateAge(string columnName)
{
if (age == 0) return null;
if (age >= 18 && age <= 35)
{
return null;
}
return "Please enter Age between 18 to 35";
}
}


Validation Rules in WPF

WPF data binding model provides ability to validate user input. You can associate Validation Rule with your Binding as well with MultiBinding. Binding engine automatically checks whether any ValidationRule associated or not if yes then every time value passes to the source it will applies validation. Validation applies only when target value updates source value (i.e. with TwoWay or OneWayToSource binding modes).

To create validation rule you need to inherit ValidationRule class. This class is abstract class and has abstract method named Validate which returns ValidationResult type.

Below example explains how to associate validation rule to data binding.


<Window x:Class="WpfApplication1.ValidationRuleDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Validation Rule" Height="130" Width="280">
<Window.Resources>

<local:Employee x:Key="EmployeeInformation" />
<local:AgeRangeValidationRule x:Key="ageRangeValidation" />
<local:OnlyDigitsValidationRule x:Key="onlyDigitsValidation" />
<local:NameValidationRule x:Key="nameValidation" />

<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource=
{x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>

<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.20*"/>
<RowDefinition Height="0.20*" />
<RowDefinition Height="0" />
</Grid.RowDefinitions>

<TextBlock Text="Enter Name: " Grid.Column="0"
Grid.Row="0" Margin="3"/>
<TextBox Name="Name" Grid.Column="1"
Grid.Row="0" Height="30" Margin="3">
<TextBox.Text>
<Binding Source="{StaticResource EmployeeInformation}"
Path="Name">
<Binding.ValidationRules>
<local:NameValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBlock Text="Enter Age: " Grid.Column="0"
Grid.Row="1" Margin="3"/>
<TextBox Name="Age" Grid.Column="1"
Grid.Row="1" Height="30" Margin="3">
<TextBox.Text>
<Binding Source="{StaticResource EmployeeInformation}"
Path="Age">
<Binding.ValidationRules>
<local:OnlyDigitsValidationRule />
<local:AgeRangeValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</Window>

Code Behind

public class Employee : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
private int age;
public int Age
{
get { return age; }
set { age = value; OnPropertyChanged("Age"); }
}

public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}

Validation Rule classes

public class NameValidationRule :ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
string name = value.ToString();
if (name.All(c=> char.IsLetter(c) || c== ' '))
return new ValidationResult(true, null);
return new ValidationResult(false, "Please enter only alphabets");
}
}

public class AgeRangeValidationRule: ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
int age = int.Parse(value.ToString());

if (age >= 18 && age <= 35)
{
return new ValidationResult(true, null);
}

return new ValidationResult(false,
"Please enter Age between 18 to 35");
}
}

public class OnlyDigitsValidationRule : ValidationRule
{
public override ValidationResult Validate(object value,
System.Globalization.CultureInfo cultureInfo)
{
if (!value.ToString().All(c => char.IsDigit(c)))
return new ValidationResult(false,
"Please enter only digits");

return new ValidationResult(true, null);
}
}



DataTriggers in WPF

This post shows how you can implement data triggers in WPF.

The code is self explanatory. The window consists of textboxes which turn red in foreground color if a value of a memeber of a itemsource to which the data is bounded is set to false.

The data is bound using XML data provider.

Put the follo0wing ina XML file.

<members>
<member>
<isactive>true</isactive>
<groupcolor>#FFCC3333</groupcolor>
<name>Tom Jackson</name>
</member>
<member>
<isactive>false</isactive>
<groupcolor>#FFA4AB28</groupcolor>
<name>Stacey Footheart</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FFA6D877</groupcolor>
<name>Jack Herdin</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FF138C48</groupcolor>
<name>Kim Getruds</name>
</member>
<member>
<isactive>false</isactive>
<groupcolor>#FF5FADB9</groupcolor>
<name>Larry Nusom</name>
</member>
<member>
<isactive>true</isactive>
<groupcolor>#FF3B1076</groupcolor>
<name>Gary Heart</name>
</member>
</members>

Place the folowing in a XAML file.

<Window x:Class="datatriggers_cs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="datatriggers_cs" Height="300" Width="300"
>
<Window.Resources>
<XmlDataProvider Source="members.xml" x:Key="memberslist" />

<Style x:Key="itemstyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="Green" />
<Style.Triggers>
<DataTrigger Binding="{Binding XPath=isactive}" Value="false">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>

</Window.Resources>

<Grid>
<ItemsControl ItemsSource="{Binding Source={StaticResource memberslist}, XPath=/members/member}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderBrush="SlateBlue" BorderThickness="2" Background="White" CornerRadius="3">
<TextBlock Style="{StaticResource itemstyle}" Text="{Binding XPath=name}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>


OUTPUT
----------


Friday, December 2, 2011

Epander control in WPF - Exmaple

Just copy paste the code. it is self explanatory.

XAML

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Expender WPF Sample" Height="300" Width="400"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Expander HorizontalAlignment="Left" Header="Standard Expander"
VerticalAlignment="Top" ExpandDirection="Down" Width="150">
<TextBlock TextWrapping="Wrap" Background="AntiqueWhite">
This is the standard expander
behavior. The expander opens
and the controls below it
move down.
</TextBlock>
</Expander>
<StackPanel Grid.Row="1" Margin="10,5,0,0">
<RadioButton Content="Choice One"/>
<RadioButton Content="Choice Two"/>
<RadioButton Content="Choice Three"/>
</StackPanel>
</Grid>

<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="33" />
<RowDefinition />
</Grid.RowDefinitions>
<Canvas Panel.ZIndex="99">
<Expander HorizontalAlignment="Left" Header="PopUp Window Expander"
VerticalAlignment="Top" ExpandDirection="Down" Width="175">
<Grid Background="Cornsilk">
<Grid.BitmapEffect>
<DropShadowBitmapEffect />
</Grid.BitmapEffect>

<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>

<TextBlock Text="How Cool Is This!" FontWeight="Bold"
Margin="5"/>
<TextBlock Grid.Row="1" TextWrapping="Wrap" Margin="5">
This is the popup expander
behavior. The expander opens
and overlays the controls
below it.
</TextBlock>
</Grid>
</Expander>
</Canvas>
<StackPanel Grid.Row="1" Margin="10,5,0,0">
<RadioButton Content="Choice One"/>
<RadioButton Content="Choice Two"/>
<RadioButton Content="Choice Three"/>
</StackPanel>
</Grid>
</Grid>
</Window>



OUTPUT


Expander control in WPF

An Expander control provides a way to provide content in an expandable area that resembles a window and includes a header.

The Content and Header of an Expander can also contain complex content, such as RadioButton and Image objects.


Setting the Direction of the Expanding Content Area

You can set the content area of an Expander control to expand in one of four directions (Down, Up, Left, or Right) by using the ExpandDirection property. When the content area is collapsed, only the Expander Header and its toggle button appear. A Button control that displays a directional arrow is used as a toggle button to expand or collapse the content area. When expanded, the Expander tries to display all of its content in a window-like area.

Creating Scrollable Content

When you place an Expander control in a ScrollViewer, set the ScrollViewer dimension property that corresponds to the direction in which the Expander content opens to the size of the Expander content area. For example, if you set the ExpandDirection property on the Expander to Down (the content area opens down), set the Height property on the ScrollViewer control to the required height for the content area. If you instead set the height dimension on the content itself, ScrollViewer does not recognize this setting and therefore, does not provide scrollable content.

The following example shows how to create an Expander control that has complex content and that contains a ScrollViewer control.

XAML

<Window x:Class="Practises.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Expander Width="200" HorizontalContentAlignment="Stretch">
<Expander.Header>
<TextBlock Margin="20,0,0,0">My Expander</TextBlock>
</Expander.Header>
<Expander.Content>
<ScrollViewer Height="180">
<TextBlock TextWrapping="Wrap">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
</TextBlock>
</ScrollViewer>
</Expander.Content>
</Expander>
</Grid>
</Window>



DockPanel in WPF

Introduction


The dock panel is a layout panel, that provides an easy docking of elements to the left, right, top, bottom or center of the panel. The dock side of an element is defined by the attached property DockPanel.Dock. To dock an element to the center of the panel, it must be the last child of the panel and the LastChildFill property must be set to true.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" WindowTitle="DockPanel Sample">
<DockPanel LastChildFill="True">
<Border Height="25" Background="SkyBlue" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Top">
<TextBlock Foreground="Black">Dock = "Top"</TextBlock>
</Border>
<Border Height="25" Background="SkyBlue" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Top">
<TextBlock Foreground="Black">Dock = "Top"</TextBlock>
</Border>
<Border Height="25" Background="LemonChiffon" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Bottom">
<TextBlock Foreground="Black">Dock = "Bottom"</TextBlock>
</Border>
<Border Width="200" Background="PaleGreen" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Left">
<TextBlock Foreground="Black">Dock = "Left"</TextBlock>
</Border>
<Border Background="White" BorderBrush="Black" BorderThickness="1">
<TextBlock Foreground="Black">This content will "Fill" the remaining space</TextBlock>
</Border>
</DockPanel>
</Page>


OUTPUT

Tuesday, November 29, 2011

Static vs Dynamic resources in WPF

A resource can be referenced as either static or dynamic resource.

The major difference between static and dynamic resources is “static resource will evaluate the resource only once while dynamic resource will be evaluated every time the resource needed”.

Dynamic resource has more performance overhead than static resources because it look up for resources every time it requested or needed.

Static resource is faster but it takes little more time to load page or window than dynamic resource because dynamic resources are loaded when you actually used those.

Below example gives you clear picture about Static and Dynamic resource markup extension.

XAML

<Window.Resources>
<SolidColorBrush Color="LightBlue" x:Key="buttonBackground" />
</Window.Resources>

<StackPanel Name="stkPanel">

<Button Name="Button1" Content="Button1"
Width="150" Height="40" Margin="5"
Background="{StaticResource buttonBackground}"/>

<Button Name="Button2" Content="Button2"
Width="150" Height="40" Margin="5"
Background="{DynamicResource buttonBackground}"/>

<Button Name="Button3" Content="Button3"
Width="150" Height="40" Margin="5"
Background="{StaticResource buttonBackground}"/>

</StackPanel>

Code behind

void StaticAndDynamicResources_Loaded(object sender, RoutedEventArgs e)
{
stkPanel.Resources["buttonBackground"] = Brushes.Yellow;
}

Output



As shown in above example, three buttons are using buttonBackground resource defined in windows.resources element. Button1 and Button3 are using static resource markup extension while button2 is using dynamic resource markup extension. After loading of my window, I have changed color of buttonBackground resource from Lightblue to Yellow in code behind. So when I run my application, Button2 will have yellow background and rest of the buttons will have LightBlue background. The reason behind for not changing background of Button1 and Button3 because both button uses static resource and static resource is loaded only once with application while button2 uses dynamic resource and it changes every time when it accessed.


Hope you liked this article. Please feel free to write feedback/comments in comment section below.

Friday, July 29, 2011

Sql Server : Top 10 cached queries.

In this article, we will see how to view the most cached statements on the server.

The view sys.dm_exec_cached_plans and function dm_exec_sql_text can be used for this purpose.

Let us execute the following query

sql-server-dmv-cache
select top 10
db_name(sql_text.dbid) as db_name,
cache_plan.objtype,
sql_text.text ,
cache_plan.usecounts
from
sys.dm_exec_cached_plans as cache_plan
cross apply sys.dm_exec_sql_text(plan_handle) as sql_text
order by
usecounts desc

Here are some important points to note about this query:

The result is based on the descending order of the column ‘usecounts’ which is used to indicate the number of times the cached objects are used.
The column ‘object type’ indicates whether the statement is of the type procedure,view, adhoc etc.
The column text shows the exact statement which was cached.
The column db_name is null for the cached types adhoc, prepared, etc





OUTPUT

Thursday, July 28, 2011

Managing cookies in WPF

A cookie is an arbitrary piece of data that can be stored by an application on the client machine during application sessions (session cookies) or across application sessions (persistent cookies). You can create both types of cookies by calling SetCookie.

Cookie data typically takes the form of a name/value pair in the following format:

Name=Value

You pass a string of this format to SetCookie, along with the Uri of the location for which the cookie should be set (typically, the application domain).

Whether a cookie is a session cookie or a persistent cookie depends on whether the cookie string that you pass to SetCookie includes an expiry date. The string for a session cookie does not include an expiry date. The string for a persistent cookie does, and must be in the following format:

NAME=VALUE; expires=DAY, DD-MMM-YYYY HH:MM:SS GMT

Persistent cookies are stored in the current Windows installation's Temporary Internet Files folder until they expire, in which case they are deleted. You can delete a persistent cookie from your application by setting its expiry date to a date/time value that is in the past.


Code snippet in Listing 1 creates two cookies using SetCookie method. One is a session cookie and other is a persistent cookie.

string simpleCookie = "CSCUser1=Mahesh";
string cookieWithExpiration = "CSCUser2=Mahesh;expires=Sat, 10-Oct-2012 00:00:00 GMT";


Listing 1
Uri cookieUri1 = new Uri(@"C:\Junk\SimpleMC");
Uri cookieUri2 = new Uri(@"C:\Junk\PersMC");

Application.SetCookie(cookieUri1, simpleCookie);
Application.SetCookie(cookieUri2, cookieWithExpiration);


Application.GetCookie method retrieves cookie data from the given Uri.
The code listed in Listing 2 uses the GetCookie method to get the cookie data and displays it in a MessageBox.

Listing 2
Uri cookiePath = new Uri(@"C:\Junk\SimpleMC");
string cookie = Application.GetCookie(cookiePath);
MessageBox.Show(cookie);

Drawing Shapes in WPF

Drawing Shapes in WPF
This article is an introduction to graphics programming in XAML and WPF. In this article, I discuss various graphics objects including lines, rectangles, ellipses, and paths and how to draw them using XAML and WPF.

Drawing a Line


The Line tag of XAML draws a line. The X1,Y1 and X2,Y2 attributes represent the starting and ending point of the line and Stroke represents the color of the line. The StrokeThickness attribute represents the thickness of the line.

The following code draws a line from point (100,100) t (300,100) with blue color and thickness is 2.

<Line Stroke="#000fff" StrokeThickness="2" X1="100" Y1="100"

X2="300" Y2="100"/>

The output looks like Figure 1.

Figure 1. Drawing a line




Drawing and Filling a Rectangle


The Rectangle tag of XAML draws a rectangle. The Height and Width attributes represent the height and width of the rectangle. The Stroke and StrokeThickness represents the color and thickness of the rectangle boundary.

The following code draws a rectangle with height 100 and width 300.

<Rectangle Width="300" Height="100" Stroke="Blue" StrokeThickness="5">

</Rectangle>

The output looks like Figure 2.

Figure 2. Drawing a rectangle



The Fill attributes fill a rectangle with a color. The following code fills a rectangle with yellow color.

Rectangle Fill="Yellow" Width="300" Height="100" Stroke="Blue"

StrokeThickness="5">

</Rectangle>

The output looks like Figure 3.

Figure 3. Filling a rectangle





By setting RadiusX and RadiusY attributes, you can also draw a rectangle with rounded corners.

<Rectangle Width="120" Height="100" RadiusX="10" RadiusY="10"

Stroke="Green" StrokeThickness="5" Fill="Black">

</Rectangle>

The output looks like Figure 4.

Figure 4. Drawing a rounded rectangle




Drawing and Filling an Ellipse


The Ellipse tag of XAML draws an ellipse and circle (ellipse with equal height and width). The Height and Width attributes represent the height and width of the ellipse. The Stroke and StrokeThickness represents the color and thickness of the ellipse boundary. The Fill attribute fills the ellipse with a color.

The following code draws an ellipse with height 100 and width 300.

<Ellipse Height="100" Width="300" StrokeThickness="5" Stroke="Black" Fill="Gold"/>

The output looks like Figure 5.

Figure 5. Drawing and Filling an Ellipse





Drawing and Filling a Path


The Path tag of XAML draws a path. The Data attribute of the Path represents various points in the path. Here M represents MoveTo command and C represents the absolute path. Capital H represents the LineTo command.

The following code draws a path.

<Path Data="M 200,40 C 50,90 200,250 200,75 H 300" Stroke="Black" StrokeThickness="4"/>

The output looks like Figure 6.

Figure 6. Drawing a path






Similar to the rectangle and ellipse, the Fill attribute fills a path with a color.

<Path Data="M 200,40 C 50,90 200,250 200,75 H 480" Stroke="Black"

StrokeThickness="4" Fill="Yellow"/>

The output looks like Figure 7.

Figure 7. Filling a path



Drawing and Filling a Polygon

The <Polygon /> tag of XAML draws a ploygon. The Points attribute represents various points of the polygon.

The following code draws and fills a polygon.

<Polygon Points="100,50 50,100 150,100 100,50 100,30" Stroke="Green" StrokeThickness="3" Fill="Yellow"/>

The output looks like Figure 8.

Figure 8. Drawing and filling a polygon




Here is another example of a polygon.

<Polygon Points="100,0 75,75 100,100 125,75"

Stroke="Black" StrokeThickness="2" Fill="Yellow"/>

<Polygon Points="100,100 125,125 100,200 75,125"

Stroke="Yellow" StrokeThickness="2" Fill="Black"/>

<Polygon Points="100,100 125,75 200,100 125,125"

Stroke="Red" StrokeThickness="2" Fill="Blue"/>

<Polygon Points="100,100 75,125 0,100 75,75"

Stroke="Blue" StrokeThickness="2" Fill="Red"/>


The output looks like Figure 9.

Figure 9. Nice looking polygon



Drawing a Polyline

The <Polyline /> tag of XAML draws a ployline, which is a series of connected lines. Unlike a polygon, which is a closed curver, a polyline is usually an open curve. If you want to draw a series of connected lines but closed curve, you might want to use polygon.

Similar to the polygon, a polyline has Points attribute that defines the points of lines draw from and to. The following code draws a ployline.

<Polyline Points="50,100 150,100 100,50 250,50" Stroke="Blue" StrokeThickness="2"/>

The output looks like Figure 10.

Figure 10. Drawing a polyline

Transferring data between ListBoxes in WPF.

This article shows us how data can be transferred from one listbox to another in WPF.
For the demo purpose the listbox is binded to a arraylist, in reality it may obtain data from the database, a collection of objects ot from XML file.

The code is self explanatory,

XAML
<Window x:Class="WPFControlsSample.TwoListBoxes"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TwoListBoxes" Height="300" Width="606" Loaded="Window_Loaded">
<Grid>
<ListBox Margin="11,13,355,11" Name="LeftListBox" />
<ListBox Margin="0,13,21,11" Name="RightListBox" HorizontalAlignment="Right" Width="216" />
<Button Name="AddButton" Height="23" Margin="248,78,261,0" VerticalAlignment="Top"
Click="AddButton_Click">Add >></Button>
<Button Name="RemoveButton" Margin="248,121,261,117"
Click="RemoveButton_Click"><< Remove</Button>
</Grid>
</Window>


XAML.CS


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;

namespace WPFControlsSample
{
/// <summary>
/// Interaction logic for TwoListBoxes.xaml
/// </summary>
public partial class TwoListBoxes : Window
{
private ArrayList myDataList = null;
string currentItemText ;
int currentItemIndex ;

public TwoListBoxes()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Get data from somewhere and fill in my local ArrayList
myDataList = LoadListBoxData();
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}

/// <summary>
/// Generate data. This method can bring data from a database or XML file
/// or from a Web service or generate data dynamically
/// </summary>
/// <returns></returns>
private ArrayList LoadListBoxData()
{
ArrayList itemsList = new ArrayList();
itemsList.Add("Coffie");
itemsList.Add("Tea");
itemsList.Add("Orange Juice");
itemsList.Add("Milk");
itemsList.Add("Mango Shake");
itemsList.Add("Iced Tea");
itemsList.Add("Soda");
itemsList.Add("Water");
return itemsList;
}

private void AddButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = LeftListBox.SelectedValue.ToString();
currentItemIndex = LeftListBox.SelectedIndex;

RightListBox.Items.Add(currentItemText);
if (myDataList != null)
{
myDataList.RemoveAt(currentItemIndex);
}

// Refresh data binding
ApplyDataBinding();
}

private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
// Find the right item and it's value and index
currentItemText = RightListBox.SelectedValue.ToString();
currentItemIndex = RightListBox.SelectedIndex;
// Add RightListBox item to the ArrayList
myDataList.Add(currentItemText);

// LeftListBox.Items.Add(RightListBox.SelectedItem);
RightListBox.Items.RemoveAt(RightListBox.Items.IndexOf(RightListBox.SelectedItem));

// Refresh data binding
ApplyDataBinding();
}

/// <summary>
/// Refreshes data binding
/// </summary>
private void ApplyDataBinding()
{
LeftListBox.ItemsSource = null;
// Bind ArrayList with the ListBox
LeftListBox.ItemsSource = myDataList;
}
}
}

Creating Fancy Tooltips in WPF

Each control in WPF has a Tooltip property that can be accessed through XAML or code behind. The Tooltip property can host any kind of controls such as a rectangle, text block, or a panel. In other words, we can display another window with any number of controls as a tooltip of a control.

The following code creates a simple tooltip for a button control.

<Button Width="100" Height="30">Click Me

<Button.ToolTip>

<ToolTip>This is a tooltip test for a button control. You

can click me if you want but I will do nothing for you.

</ToolTip>

</Button.ToolTip>

</Button>

The output looks like the one in the figure below,



As I said earlier, a Tooltip can host any number of controls. For example, in the below code, a button tooltip hosts a StackPanel with two children StackPanels. First StackPanel hosts an image and a text block and second StackPanel hosts a larger textblock. The output looks like Figure 2, which is a fancy tooltip.

<Button Width="100" Height="30">Click Me

<Button.ToolTip>

<StackPanel Background="Honeydew" Height="200" Width="200">

<StackPanel Background="BurlyWood" Height="30" Width="200" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top" >

<Image VerticalAlignment="Top" Width="30" Height="30" Source="C:\Projects\XAML\FancyTooltip\FancyTooltip\samp.png" Name="image1" />

<TextBlock FontFamily="Aharoni" FontSize="24" FontWeight="Bold" Foreground="Black" TextWrapping="Wrap" VerticalAlignment="Top" Height="30" HorizontalAlignment="Right" Width="143">

<Run FontFamily="Andalus" FontSize="18" FontWeight="Normal" Text="Hello! Fancy Tip"/>

</TextBlock>

</StackPanel>



<StackPanel Width="200" Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top" >

<TextBlock TextWrapping="Wrap" Foreground="#FFF9F4F4" TextAlignment="Center" Background="{x:Null}" HorizontalAlignment="Right" VerticalAlignment="Top" Width="181" Height="98">

<Run FontFamily="Verdana" FontSize="11" FontWeight="Normal" Foreground="#FF151514"

Text="Format your tip the way you want and put any image, text or other controls on it.

Also, you can add more controls in this tip the way you want to format it."/>

</TextBlock>

</StackPanel>

</StackPanel>

</Button.ToolTip>

</Button>


Figure 2




Using this approach, you may design your tooltips the way you want.

Note: In the above code, you may want to change the source of the image file by changing the following code: Source="C:\Projects\XAML\FancyTooltip\FancyTooltip\samp.png"

Tuesday, July 26, 2011

Two way Binding in WPF

In this article we shall understand two way binding in WPF applications.

Abstract :

In this article I will show you about two way binding in WPF application. Its very easy to do in WPF in comparison of windows Application programming.

Two way binding is used when we want to update some controls property when some other related controls property change and when source property change the actual control also updates its property. I think this sentence is hard to understand :)

Let me explain you with an example.

Suppose we have one one Slider control and one textbox. Now if I move slider its value should be displayed in text box and when I input some value in textbox it should be reflected in Slider too.. that's called two way binding .. :)

Implementation :

We will create sample application that will demonstrate the same as I mentioned in abstract part of the article.

Start with File >> New >>Projects >>Visual C# >> WPF Application ...

DragDrop One Slider control on the WPF form ..and a Textbox ..Setup the GUI like shown in below image






Now we want to bind TextBox Text Property to the Slider's value property ..
In XAML code of TextBox we will write Text Property as below

Text="{Binding Mode=OneWayToSource, ElementName=Slider1,Path=Value, UpdateSourceTrigger=PropertyChanged}

Lets understand what it says
Mode : Specify how we want to Bind Control
here we will have default, OneTime, OneWay ,OneWayToSource, TwoWay.

OneTime: changes Slider Property one time only when we write value in Text box
OneWay: Only Text box Property will be updated when we move Slider ..but if we write some value in TextBox it will not be reflected in Slider
OneWayToSource: by this option we can update the Value of Slider from Text box but can not Update value of textBox from Slider.
TwoWay: if we update the value of textbox it will be reflated to Slider and If we update the value of slider it will be reflected in TextBox .

Now when we bind something we need to specify which control we are binding so
ElemenetName : Specify which control to bind ..

Path Specifies which specific property we are trying to bind here we are using Value property becuase we want to Bind Value property of the Slider to TextBox

UpdateSourceTrigger: it specifies when trigger should be fired .. we specified when some PropertyChanged in Source .

Here is My Full XAML Code of Grid take a look ..

<Window x:Class="TwowayBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>

<Slider Name="Slider1" Value="0" Margin="84,85,173,199" SmallChange="1" Maximum="100" ></Slider>

<TextBox Name="txtValue" Margin="84,118,173,174" Text="{Binding Mode=TwoWay, ElementName=Slider1,Path=Value, UpdateSourceTrigger=PropertyChanged}"></TextBox>

<Label Content="Value " Height="28" HorizontalAlignment="Left" Margin="39,114,0,0" Name="label1" VerticalAlignment="Top" />

<Label Content="Two way binding Demo :" Height="61" HorizontalAlignment="Left" Margin="17,12,0,0" Name="label2" VerticalAlignment="Top" FontSize="32" />

</Grid>
</Window>


Just write the code like it and Run the project ..
You have successfully learned how to bind Two Controls Two way . :)
Thank you for reading article :)

Styles in WPF

The following sample shows how styles can be applied at page level in WPF. The style details are encapsulated under <Window.Resources> tags. Each style that you create must have a unique name associated with it. This is done by the key property.
Setting the Key property to unique names created unique style elements. The creation of style is very similar to the way it is done in web applications.

Once the style elements are created we need to associate the control with the style name.

Note: We specify the style as "Control.Property" example "TextBlock.Background" the reason being some of the controls do not understand when you just specify the property that you want to modify or style. Example a "TextBlock" does not understand when you just say "Background". You need to explicitly specify "Control.Property" for it to work properly.



XAML Code.

<Window x:Class="applystyles_cs.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="applystyles_cs" Height="300" Width="300"
>
<Window.Resources>

<Style x:Key="myTextstyle">
<Setter Property="TextBlock.Background" Value="Black" />
<Setter Property="TextBlock.Margin" Value="10,10,10,5" />
<Setter Property="TextBlock.Foreground" Value="White" />
<Setter Property="TextBlock.FontSize" Value="20" />
<Setter Property="TextBlock.HorizontalAlignment" Value="Center" />
</Style>

<Style x:Key="btnstyle">
<Setter Property="Button.Margin" Value="10,5,10,10" />
<Setter Property="Button.Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="Blue" />
<GradientStop Offset="1" Color="Red" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Button.HorizontalAlignment" Value="Center" />
</Style>

</Window.Resources>

<StackPanel>
<TextBlock Style="{StaticResource myTextstyle}">
Hello
</TextBlock>
<Button Style="{StaticResource btnstyle}">
Click Me</Button>
</StackPanel>
</Window>

WPF Message box

The sample demonstrates the use of message box in WPF. it also shows the various options available for the WPF message box parameters like "caption", "image to be shown", "MessageBoxText".


The code/example is self explanatory .Just copy paste the code in the XAML and it's code behind file.


XAML Code
<Window x:Class="MessageBoxSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MessageBoxSample" Height="300" Width="500"
>
<Grid>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>

<Label Grid.Column="0" Grid.Row="0">Associate with Owner Window?</Label>
<CheckBox Grid.Column="1" Grid.Row="0" Name="ownerCheckBox"></CheckBox>

<Label Grid.Column="0" Grid.Row="1">messageBoxText:</Label>
<TextBox Grid.Column="1" Grid.Row="1" Name ="messageBoxText">MessageBoxText</TextBox>

<Label Grid.Column="0" Grid.Row="2">caption:</Label>
<TextBox Grid.Column="1" Grid.Row="2" Name="caption">Caption</TextBox>

<Label Grid.Column="0" Grid.Row="3">button:</Label>
<ComboBox Grid.Column="1" Grid.Row="3" Name="buttonComboBox">
<ComboBoxItem IsSelected="True">OK</ComboBoxItem>
<ComboBoxItem>OKCancel</ComboBoxItem>
<ComboBoxItem>YesNo</ComboBoxItem>
<ComboBoxItem>YesNoCancel</ComboBoxItem>
</ComboBox>

<Label Grid.Column="0" Grid.Row="4">icon:</Label>
<ComboBox Grid.Column="1" Grid.Row="4" Name="imageComboBox">
<ComboBoxItem>Asterisk</ComboBoxItem>
<ComboBoxItem>Error</ComboBoxItem>
<ComboBoxItem>Exclamation</ComboBoxItem>
<ComboBoxItem>Hand</ComboBoxItem>
<ComboBoxItem>Information</ComboBoxItem>
<ComboBoxItem IsSelected="True">None</ComboBoxItem>
<ComboBoxItem>Question</ComboBoxItem>
<ComboBoxItem>Stop</ComboBoxItem>
<ComboBoxItem>Warning</ComboBoxItem>
</ComboBox>

<Label Grid.Column="0" Grid.Row="5">defaultResult:</Label>
<ComboBox Grid.Column="1" Grid.Row="5" Name="defaultResultComboBox">
<ComboBoxItem>Cancel</ComboBoxItem>
<ComboBoxItem>No</ComboBoxItem>
<ComboBoxItem IsSelected="True">None</ComboBoxItem>
<ComboBoxItem>OK</ComboBoxItem>
<ComboBoxItem>Yes</ComboBoxItem>
</ComboBox>

<Label Grid.Column="0" Grid.Row="6">options</Label>
<ComboBox Grid.Column="1" Grid.Row="6" Name="optionsComboBox">
<ComboBoxItem>DefaultDesktopOnly</ComboBoxItem>
<ComboBoxItem IsSelected="True">None</ComboBoxItem>
<ComboBoxItem>RightAlign</ComboBoxItem>
<ComboBoxItem>RtlReading</ComboBoxItem>
<ComboBoxItem>ServiceNotification</ComboBoxItem>
</ComboBox>

<Button Grid.Column="1" Grid.Row="7" Name="showMessageBoxButton" Click="showMessageBoxButton_Click">Show MessageBox</Button>

<StatusBar Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="8" >
<StatusBarItem>
<TextBlock Name="resultTextBlock">Ready</TextBlock>
</StatusBarItem>
</StatusBar>

</Grid>

</Window>






XAML.CS code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MessageBoxSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

void showMessageBoxButton_Click(object sender, RoutedEventArgs e)
{
// Configure the message box
Window owner = ((bool)ownerCheckBox.IsChecked ? this : null);
string messageBoxText = this.messageBoxText.Text;
string caption = this.caption.Text;
MessageBoxButton button = (MessageBoxButton)Enum.Parse(typeof(MessageBoxButton), this.buttonComboBox.Text);
MessageBoxImage icon = (MessageBoxImage)Enum.Parse(typeof(MessageBoxImage), this.imageComboBox.Text);
MessageBoxResult defaultResult = (MessageBoxResult)Enum.Parse(typeof(MessageBoxResult), this.defaultResultComboBox.Text);
MessageBoxOptions options = (MessageBoxOptions)Enum.Parse(typeof(MessageBoxOptions), this.optionsComboBox.Text);

// Show message box, passing the window owner if specified
MessageBoxResult result;
if (owner == null)
{
result = MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options);
}
else
{
result = MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options);
}

// Show the result
resultTextBlock.Text = "Result = " + result.ToString();
}
}
}

Monday, July 25, 2011

WPF - Sort a GridView Column When a Header Is Clicked

In this post we shall learn how to Sort a GridView Column When a Header Is Clicked

The Listview contains its view as a Gridview. The Giridview is bound to a Arraylist which is a collection of dates.

The Gridview data is sorted when a header column of Giridview is clicked.

Note: The declaration that says that "Sort the Gridview data when a header column is clicked is defined in Listview".


XAML content.


<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ListViewSort.Window1"
xmlns:s="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:p="clr-namespace:System;assembly=mscorlib">
<Window.Resources>
<DataTemplate x:Key="HeaderTemplateArrowUp">
<DockPanel>
<TextBlock HorizontalAlignment="Center" Text="{Binding}"/>
<Path x:Name="arrow"
StrokeThickness = "1"
Fill = "gray"
Data = "M 5,10 L 15,10 L 10,5 L 5,10"/>
</DockPanel>
</DataTemplate>
<DataTemplate x:Key="HeaderTemplateArrowDown">
<DockPanel>
<TextBlock HorizontalAlignment="Center" Text="{Binding }"/>
<Path x:Name="arrow"
StrokeThickness = "1"
Fill = "gray"
Data = "M 5,5 L 10,10 L 15,5 L 5,5"/>
</DockPanel>
</DataTemplate>
</Window.Resources>

<StackPanel>
<TextBlock HorizontalAlignment="Center" FontSize="16"
Foreground ="Blue" Margin="0,20,0,30">
ListView Sample with Sort Capability
</TextBlock>
<ListView x:Name='lv' Height="150" HorizontalAlignment="Center"
VerticalAlignment="Center"
GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler"
>
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Year}"
Header="Year"
Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Month}"
Header="Month"
Width="100"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Day}"
Header="Day"
Width="100"/>
</GridView>
</ListView.View>
<ListView.ItemsSource>
<s:ArrayList>
<p:DateTime>1993/1/1 12:22:02</p:DateTime>
<p:DateTime>1993/1/2 13:2:01</p:DateTime>
<p:DateTime>1997/1/3 2:1:6</p:DateTime>
<p:DateTime>1997/1/4 13:6:55</p:DateTime>
<p:DateTime>1999/2/1 12:22:02</p:DateTime>
<p:DateTime>1998/2/2 13:2:01</p:DateTime>
<p:DateTime>2000/2/3 2:1:6</p:DateTime>
<p:DateTime>2002/2/4 13:6:55</p:DateTime>
<p:DateTime>2001/3/1 12:22:02</p:DateTime>
<p:DateTime>2006/3/2 13:2:01</p:DateTime>
<p:DateTime>2004/3/3 2:1:6</p:DateTime>
<p:DateTime>2004/3/4 13:6:55</p:DateTime>
</s:ArrayList>
</ListView.ItemsSource>
</ListView>

</StackPanel>
</Window>



XAML.CS - Code behind



using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Windows.Data;

namespace ListViewSort
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;

void GridViewColumnHeaderClickedHandler(object sender,
RoutedEventArgs e)
{
GridViewColumnHeader headerClicked =
e.OriginalSource as GridViewColumnHeader;
ListSortDirection direction;

if (headerClicked != null)
{
if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
{
if (headerClicked != _lastHeaderClicked)
{
direction = ListSortDirection.Ascending;
}
else
{
if (_lastDirection == ListSortDirection.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
}
}

string header = headerClicked.Column.Header as string;
Sort(header, direction);

if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTemplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}

// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.HeaderTemplate = null;
}


_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
}
}
private void Sort(string sortBy, ListSortDirection direction)
{
ICollectionView dataView =
CollectionViewSource.GetDefaultView(lv.ItemsSource);

dataView.SortDescriptions.Clear();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add(sd);
dataView.Refresh();
}
}
}

Friday, June 3, 2011

SQL Concepts with examples

VIEWS
--------
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No


INDEX
------
CREATE INDEX IDX_CUSTOMER_LOCATION
on CUSTOMER (City, Country)


CURSORS
---------
Declare @name varchar(32)
declare cursorname cursor read_only for
select name from Ashwin

open cursorname
fetch NEXT from cursorname into @name
while(@@Fetch_status=0)
begin
print @name
fetch next from cursorname into @name
end
close cursorname
deallocate cursorname

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source

Triggers
---------
Create TRIGGER InsteadTrigger on InsteadView
INSTEAD OF INSERT
AS
BEGIN
--Build an INSERT statement ignoring inserrted.PrimaryKey and
--inserted.ComputedCol.
INSERT INTO BaseTable
SELECT Color+'altered', Material+'altered'
FROM inserted
END

CREATE TRIGGER [trglogin]
ON [dbo].[tbl_Login]
FOR UPDATE
AS
BEGIN
if((UPDATE(col1))
begin
print 'col1 is updated..'
end
if((UPDATE(col2))
begin
print 'col2 is updated..'
end
end




User defined functions
--------------------------
Create Function dbo.Factorial (@number int)
Returns int
As
BEGIN
Declare @finalResult int
If @number < 2
Select @finalResult = @number
Else
Select @finalResult = @number * dbo.factorial(@number - 1)

Return @finalResult
END
GO
Select dbo.Factorial (8)


Create Function dbo.TitleTable (@title_id Varchar(6))
Returns @ReturnTable Table (title_id Varchar(6),
title Varchar(80),
type Char(12))
As
BEGIN
Insert @ReturnTable
Select title_id, title, type From titles where title_id=@title_id
order by 1
Return
End
GO
Select * from dbo.TitleTable('BU1032')

C# 3.0 Features: Object Initializers

C# 3.0 is just around the corner so I thought I'd start writing about a few of the features that it exposes and provide quick and concise examples of how they can be used. Many of the new features rely on the compiler to generate code that you would have had to write in the past. This can result in significantly less code compared to C# 2.0 syntax in many cases. Here's a list of some of the key features available in C# 3.0:

* Object Initializers
* Anonymous Types
* Automatic Properties
* Extension Methods
* Lambda Expressions
* LINQ
* Collection Initializers

In this post I'll discuss the fundamentals of object initializers in C# 3.0. To get started, let's look at the standard way of initializing an object with data in C# 2.0 using constructors. The following example creates a Person object and passes three values to its constructor.

Person p = new Person("John", "Doe", "602-123-1234");

As mentioned, C# 3.0 now supports the concept of "object initializers" which means you can easily assign data to specific properties in a type with having to create an explicit constructor (you can of course still create constructors as well). The standard C# { and } brackets are used to create object initializers. Here's an example of using an object initializer to assign property data to a Person type. It's nice because doing the same thing without using a constructor in C# 2.0 would have resulted in around 5 lines of code which is too many for something simple like property value assignments.

Person p = new Person() {FirstName="John",LastName="Doe",Phone="602-123-1234",City="Phoenix"};

If the Person type defines a sub object as a property you can even use object initializers to create the sub object. Here's an example of defining an Address object:

Person p = new Person()
{
FirstName = "John",
LastName = "Doe",
Address = new Address()
{
Street = "1234 St.",
City = "Phoenix"
}
};


If you've used JavaScript Object Notation (normally referred to as JSON) in AJAX or other client-side applications, you'll recognize this style of syntax. It's simple, compact, and easy to use. Although I formatted the example above onto multiple lines to maximize readability, it could certainly be compacted quite a bit if desired.

Wednesday, May 25, 2011

Extension Methods in C#

.NET 3.5 is out which means all of the great features available in C# 3.0 are available to use now. Here's a quick list of the main language enhancements available in C# 3.0:
# Object Initializers
# Automatic Properties
# Extension Methods
# Anonymous Types
# Lambda Expressions
# LINQ
# Collection Initializers

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:

*Extension methods cannot be used to override existing methods
*An extension method with the same name and signature as an instance method will not be called
*The concept of extension methods cannot be applied to fields, properties or events
*Use extension methods sparingly....overuse can be a bad thing!

Here's an example of creating an extension method in C# that adds a RemoveNonNumeric() method to the String class. Notice that the class is defined as static as well as the extension method itself. The "this" keyword in the parameter signature tells the compiler to add the extension method to the String class since "string" follows the keyword.

namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string RemoveNonNumeric(this string s)
{
MatchCollection col = Regex.Matches(s, "[0-9]");
StringBuilder sb = new StringBuilder();
foreach (Match m in col)
sb.Append(m.Value);
return sb.ToString();
}
}


Here's an example of how the extension method can be used. You'll see that the namespace for the extension method class is imported. From there, the compiler treats the RemoveNonNumeric() method as if it was originally part of the standard System.String class.

using StringExtensions;
.
.
.
.
.
....
string phone = "123-123-1234";
string newPhone = phone.RemoveNonNumeric();

Saturday, May 14, 2011

Advantages of wcf service over web services.

As several people asking me the WCF benefits over web services, I outlined the points here

1.WCF supports more of WS-* standards than web services

2.As I mentioned in the article WCF supports multiple bindings HTTP,TCP,MSMQ,WS-HTTP etc where as web service supports only HTTP.

3.WCF can maintain transactions like COM+

4.It has JSON integration

5.It can be hosted on IIS,WAS, Self hosting and windows services

6.Web services have no instance management ie you can not have a singleton web service or session full webservice

Transact-SQL :- ROW_NUMBER()

Transact-SQL :- ROW_NUMBER()

While creating query we may need a column which will hold the sequential number like 1, 2, 3… Also we may need to show that sequential number according to a particular partition. In that situation we can use the ‘ROW_NUMBER’ keyword.

Below syntax can be followed :-


1. To get sequential number irrespective of any partition.

ROW_NUMBER ( ) OVER (<order_by_clause>)

SELECT ROW_NUMBER() OVER (ORDER BY [Col2] ASC) AS RowNo,
[Col1],[Col2],[col3] FROM [dbo].[demo_table];

Result will be:

RowNo Col1 Col2 col3
-------------------- -------------------- --------------------------------------------------
1 4 Andew 2009-03-01 00:00:00.000
2 8 Andew NULL
3 6 James 2009-07-01 00:00:00.000
4 3 John 2009-02-01 00:00:00.000
5 1 John 2009-06-24 00:00:00.000
6 2 Lee 2009-06-24 00:00:00.000
7 5 Steven 2009-06-24 00:00:00.000

2. To get sequential number within a partition.
ROW_NUMBER ( ) OVER (<partition_by_clause><order_by_clause>)

SELECT ROW_NUMBER() OVER (PARTITION BY [Col2] ORDER BY [Col2] ASC) AS RowNo,[Col1],[Col2],[col3] FROM [demo_table];

Result will be:

RowNo Col1 Col2 Col3
------------------- -------------------- ---------------------------------------------------
1 4 Andew 2009-03-01 00:00:00.000
2 8 Andew NULL
1 6 James 2009-07-01 00:00:00.000
1 3 John 2009-02-01 00:00:00.000
2 1 John 2009-06-24 00:00:00.000
1 2 Lee 2009-06-24 00:00:00.000
1 5 Steven 2009-06-24 00:00:00.000

Thursday, May 12, 2011

Assemblies in ASP.net

What is an assembly?

* An Assembly is a logical unit of code
* Assembly physically exist as DLLs or EXEs
* One assembly can contain one or more files
* The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
* When you compile your source code by default the exe/dll generated is actually an assembly
* Unless your code is bundled as assembly it can not be used in any other application
* When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
* Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest?

* Assembly manifest is a data structure which stores information about an assembly
* This information is stored within the assembly file(DLL/EXE) itself
* The information includes version information, list of constituent files etc.

What is private and shared assembly?

The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.
What is Global Assembly Cache?

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under <drive>:\WinNT\Assembly folder.
How assemblies avoid DLL Hell?

As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example :

* You created assembly Assembly1
* You also created a client application which uses Assembly1 say Client1
* You installed the client in C:\MyApp1 and also placed Assembly1 in this folder
* After some days you changed Assembly1
* You now created another application Client2 which uses this changed Assembly1
* You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder
* Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly

Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form:

major.minor.build.revision

If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match.

When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied.
How do I create shared assemblies?

Following steps are involved in creating shared assemblies :

* Create your DLL/EXE source code
* Generate unique assembly name using SN utility
* Sign your DLL/EXE with the private key by modifying AssemblyInfo file
* Compile your DLL/EXE
* Place the resultant DLL/EXE in global assembly cache using AL utility

How do I create unique assembly name?

Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :

sn -k mykeyfile.key

Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.
How do I sign my DLL/EXE?

Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines :

[assembly:AssemblyKeyFile("file_path")]

Now recompile the project and the assembly will be signed for you.

Note : You can also supply the key file information during command line compilation via /a.keyfile switch.
How do I place the assembly in shared cache?

Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache.

AL /i:my_dll.dll

Now your dll will be placed at proper location by the utility.
Hands On...

Now, that we have understood the basics of assemblies let us apply our knowledge by developing a simple shared assembly.

In this example we will create a VB.NET component called SampleGAC ( GAC stands for Global Assembly Cache). We will also create a key file named sample.key. We will sign our component with this key file and place it in Global Assembly Cache.

* Step 1 : Creating our sample component

Here is the code for the component. It just includes one method which returns a string.

imports system

namespace BAJComponents
public class Sample
public function GetData() as string
return "hello world"
end function
end class
end namespace

* Step 2 : Generate a key file

To generate the key file issue following command at command prompt.

sn -k sample.key

This will generate the key file in the same folder

* Step 3 : Sign your component with the key

Now, wee will sign the assembly with the key file we just created.

vbc sampleGAC.vb /t:library /a.keyfile:sample.key

* Step 4 : Host the signed assembly in Global Assembly Cache

We will use AL utility to place the assembly in Global Assembly Cache.

AL /i:sampleGAC.dll

After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there. Note how the assembly folder is treated differently that normal folders.



*
Step 5 : Test that our assembly works

Now, we will create a sample client application which uses our shared assembly. Just create a sample code as listed below :

imports system
imports BAJComponents
public class SampleTest
shared sub main()
dim x as new sample
dim s as string="x".getdata()
console.writeline(s)
end sub
end class

Compile above code using :

vbc sampletest.vb /t:exe /r:<assembly_dll_path_here>

Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly.

Difference between Response.Redirect and Server.transfer

You can transfer current users page request to another page with two methods:

* Server.Transfer (HttpServerUtility.Transfer Method)
* Response.Redirect (HttpResponse.Redirect Method)

Its not always clear how these two approaches differ so let us try to clarify things a little:

Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page.
HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'.
After browser receives this code it tries to open the new location of the resource that was suggested by the server.
This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response.
All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected URL.

Also its important to say that the new URL can reside on the same server but also it can be on some other server and the redirected URL does not need to be .aspx page it can be regular HTML page also).

So we can us the Redirect method to redirect users request to another page on our server like this:

Response.Redirect("newPage.html");

or to redirect our it to some other server like this:

Response.Redirect("http://www.someotherserver.com/newPage.aspx");


In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server.
(This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc).

All posted Form variables and query strings can optionally remain available to the second Page where we transfered request (if we use second overload Server.Transfer(string path, bool preserveForm) and supply true for the second parameter).
Otherwise the Form Variables and Query String are cleared just like when we use Redirect.
WARNING: If you use this method to preserve Query String and Form variables and receive error: "View State Is Invalid" its because your EnableViewStateMac attribute of the <pages> element is set to true. More on this error on this page: PRB: "View State Is Invalid" Error Message When You Use Server.Transfer

Its also important to note that because of the way Server.Transfer works, after the transfer, the URL shown in the users Web Browser remains the original one that was requested, because browser has no knowledge that its request was transfered (transfer occurs on the server side).

TIP: One thing to be careful about when using the Server.Transfer is to clear the the HttpResponse object with Response.Clear method on the transfered page to avoid any output from the first page to be shown on the second page.

So now that we know what are the similarities and differences between these two approaches we can try to use them wisely.

Here is the summary:

Response.Redirect should be used when:

* we want to redirect the request to some plain HTML pages on our server or to some other web server
* we don't care about causing additional roundtrips to the server on each request
* we do not need to preserve Query String and Form Variables from the original request
* we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)

Server.Transfer should be used when:

* we want to transfer current page request to another .aspx page on the same server
* we want to preserve server resources and avoid the unnecessary roundtrips to the server
* we want to preserve Query String and Form Variables (optionally)
* we don't need to show the real URL where we redirected the request in the users Web Browser