Friday, June 10, 2011

yield statement


Yield statement can be used in Iterator block and return value to Enumerator Object. This statement was first introduced in dotnet framework 2.0. You can use Yield return or yield break in your Iterator block. Yield break statement you can use to stop execution of iterator block with no return value. This can be used with LINQ query (see below example).

Here are some restrictions for using yield statement.

  • Yield statement can be added only inside Iterator Block.
  • You cannot use Yield statement inside Anonymous Method or Lambda Expression.
  • You can’t use “return” statement in iterator block instead you must use “yield break” statement.
  • You can’t use Yield statement in Try block with catch but you can use it in Try block with finally.
  • You can’t write Yield statement in finally block of your try…catch statement.
  • You can’t pass parameters as ref or out to Iterator method.


public partial class YieldStatement : Window
{
    public YieldStatement()
    {
        InitializeComponent();

        foreach (int k in Square(10))
        {
            Console.Write(k.ToString() + " ");
        }
    }
    public IEnumerable<int> Square(int limit)
    {
        for (int i = 1; i <= limit; i++)
        {
            yield return i * i;
        }
    }
}

Output

1 4 9 16 25 36 49 64 81 100

public partial class YieldStatement : Window
{
    public YieldStatement()
    {
        InitializeComponent();

        var result = from string s in GetValues(true)
                     where s.Length > 3
                     select s;
        foreach (string s in result)
        {
            Console.WriteLine(s);
        }
    }
    public IEnumerable<string> GetValues(bool stop)
    {
        yield return "One";
        yield return "Two";
        yield return "Three";
        if (stop)
            yield break;
        yield return "Four";
        yield return "Five";
    }
}

Output
Three

In first example, user invokes Square method; it multiplies number and return using yield return keyword. So user will get multiplied number start from 1 to entered limit.

In second example, user will receive string values having more than three characters. I passed true as parameter so I got only “Three” as output. This is because of “yield break” statement. If I pass false as parameter then I will get “Three”, “Four” and “Five” as output.

Wednesday, June 8, 2011

What’s new in WPF 4.0 - Summary



I have written so many posts related new features introduced in WPF 4.0. In this post I consolidated all the posts together at one place so who wants to learn new features of WPF 4.0 can easily go through my each post sequentially.



Monday, June 6, 2011

WPF 4.0 - DataGrid, Calendar and DatePicker Control

In WPF 4.0, three new controls have been added DataGrid, Calendar and DatePicker. You can use these controls in your application for different purposes. Silverlight application also supports these controls. 

In this post i will explain how to use these controls in WPF and XAML with simple example.


Data Grid Control 

Data Grid control is use to represent data. You can fully customize Data Grid as per your requirement.  I have summarized few useful properties of Data Grid below and also used most of them in my example below.

Property Name
Description
AlternatingRowBackground
Apply background on Alternate rows
AlternationCount
Specify number of alternating items.
AutoGenerateColumns
Creates columns automatically. (Default value is true)
CanUserResizeColumns
You can specify whether columns in grid resizable or not. (Default value is true)
CanUserReorderColumns
Specify value whether user can change order of columns or not. (Default value is true)
CanUserResizeRows
You can specify whether rows in grid resizable or not. (Default value is true)
CanUserSortColumns
Specify whether user can sort columns or not. (Default value is true)
FrozenColumnCount
You can specify number of columns you want to freeze
HeadersVisibility
Specify header visibility for Column, Row, None or All. (Default value is All)
SelectionMode
You can specify how rows and columns are selected in the DataGrid.
You can select SelectionMode either as Extended or Single.(Default value is Extended).
SelectionUnit
You can specify row, cell or both can be selected in the DataGrid. You can select either Cell or CellorRowHeader or FullRow. (Default value is FullRow).
IsReadonly
You can specify whether user can edit values in DataGrid or not. (Default value is false)
GridLinesVisibility
You can display Horizontal, Vertical, All or None gridlines in your Data Grid using this property.  (Default value is All)
ColumnWidth
Specify common width for all columns in DataGrid.
RowHeight
Specify common height for all rows in DataGrid.


 
Type of Columns
in Data Grid
Description
DataGridHyperLinkColumn
You can use this column type to display Hyperlink.
DataGridComboBoxColumn
You can use this column to display enumeration data.
DataGridTextColumn
You can use this column type to display text.
DataGridCheckBoxColumn
You can use this column type to display Boolean value.
DataGridTemplateColumn
You can use this template column to create your own custom column.

<DataGrid x:Name="grid1"
            AutoGenerateColumns="False"
            AlternatingRowBackground="LightBlue"
            AlternationCount="1"
            HeadersVisibility="Column"
            FrozenColumnCount="1"
            GridLinesVisibility="All"
            CanUserReorderColumns="True"
            CanUserResizeColumns="True"
            CanUserResizeRows="True"
            CanUserSortColumns="True"
            SelectionMode="Extended"
            SelectionUnit="FullRow"
            IsReadOnly="True"
            ColumnWidth="85"
            RowHeight="50">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}"
                            Header="Name" />
        <DataGridTextColumn Binding="{Binding Length}"
                            Header="Length" />
        <DataGridCheckBoxColumn Binding="{Binding Exist}"
                                Header="Exist" />
        <DataGridTemplateColumn Header="Image" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding FullName}"
                            Height="50" Width="50"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Code behind

void DataGridControl_Loaded(object sender, RoutedEventArgs e)

{
    grid1.ItemsSource = new DirectoryInfo(@"c:\users\public\pictures\sample pictures\").GetFiles("*.jpg");
}




























Calendar Control

Using Calendar control user can select date. This control provides rich functionality over date selection. i mentioned below few useful properties of this control.


Property Name
Description
DisplayDateStart
Date from Calendar Starts
DisplayDateEnd
Date where Calendar Ends
DisplayMode
Specify calendar display mode to Month, Decade and Year
DisplayDate
Date to display in calendar
FirstDayOfWeek
Specify beginning day of the week (e.g. Monday)
IsTodayHighlited
Specify current date is highlighted
SelectionMode
Specify selection modes to None, SingleDate, SingleRange and MultipleRange

<Calendar Name="MyCalendar"
            Margin="5"
            DisplayDateStart="1/1/2000"
            DisplayDateEnd="12/31/2025"
            DisplayMode="Month"
            DisplayDate="5/27/2011"
            FirstDayOfWeek="Sunday"
            IsTodayHighlighted="True"  
            SelectionMode="MultipleRange">
    <Calendar.SelectedDates>
        <sys:DateTime>5/10/2011</sys:DateTime>
        <sys:DateTime>5/11/2011</sys:DateTime>
        <sys:DateTime>5/12/2011</sys:DateTime>
        <sys:DateTime>5/13/2011</sys:DateTime>
        <sys:DateTime>5/14/2011</sys:DateTime>
    </Calendar.SelectedDates>
    <Calendar.BlackoutDates>
        <CalendarDateRange Start="5/16/2011" End="5/18/2011" />
        <CalendarDateRange Start="5/2/2011" End="5/3/2011" />
    </Calendar.BlackoutDates>
</Calendar>















Date Picker


You can select date using Date Picker control. This control is very powerful and simple to use. It validates entered date and it also accepts the date in various formats like MM/DD/YYYY, YYYY/MM/DD, Month Day, Year etc. Date Picker internally uses Calendar control so you can specify few similar properties to Calendar control.

<DatePicker Width="200" Height="25"
            VerticalAlignment="Top"
            Margin="10"
            DisplayDateStart="1/1/2000"
            DisplayDateEnd="12/31/2025"
            DisplayDate="5/27/2011"
            FirstDayOfWeek="Sunday"
            IsTodayHighlighted="True" />


















Hope you like this post. Please post your queries/feedback/comments here in comments section.