Wednesday, December 18, 2013

Navigation in silverlight using Frame

Purpose:

                If application contain multiple pages or user control, which requires navigating between pages. It requires silverlight navigation frame work.

 Navigation types:

                1. Application Navigation
1.       Frame based navigation
2.       Page based navigation
                2. Web Browser-Integrated Navigation
                3. External Navigation
                4. Extending the Navigation System

Navigation using frame or page:

          In frame based navigation, frame acts as a container for page controls, and facilitates navigation to pages. At any one time, the frame displays the content of a single page. You change the page that is displayed within the frame by navigating, either programmatically or through user action, to a new page.

Example:

<UserControl x:Class="NavigationApplication.MasterPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">
      <sdk:Frame x:Name="ChildFrame" Source="/Views/Home.xaml">

      </sdk:Frame>
  </Grid>
</UserControl>

Navigating between pages in XAML:

        HyperlinkButton control in Silverlight is used to navigate between pages; it has NavigateUri property, which is used to set target URI of the page. Make sure that HyperlinkButton control should resides outside the frame.
 

Example: 

<UserControl x:Class="NavigationApplication.MasterPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">
        <HyperlinkButton NavigateUri="/Home.xaml" Content="Home" />

                <HyperlinkButton NavigateUri=" /Pages/contacts.xaml" Content="Contact Us" />

      <sdk:Frame x:Name="ChildFrame" Source="/Views/Home.xaml">

      </sdk:Frame>
  </Grid>
</UserControl>


Navigating between pages using code behind:

        The above navigation will navigate to target URI without making any validation. If you don’t want to make some validation or pass some values from one page to another page means, can use navigation in code behind.

XAML:

     Create click event in xaml
<HyperlinkButton Name="aboutUs" Content="About Us"                                                                                        Click="aboutUs_Click"
 Width="100" Height="20"/>

XAML.cs:

      Map frame to target URI, here About.Xaml page

ChildFrame.Navigate(new Uri("/Pages/About.xaml", UriKind.Relative));


Error Handling in Navigation:

            Frame had inbuilt support to handle navigation errors. This is called NavigationFailed event, in this event we can show some error details during navigation.

XAML:

<sdk:Frame x:Name="ChildFrame" Source="/Views/Home.xaml" NavigationFailed=" ChildFrame_NavigationFailed">

      </sdk:Frame>

XAML.cs:

       Handle navigation errors in code behind, by using the way

private void ChildFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
  {
   e.Handled = true;
   masterCtrl.Navigate(new Uri("/Pages/ErrorDetails.xaml",UriKind.Relative));
  }



Tuesday, December 3, 2013

Data Template in Silverlight / WPF

OverView:

       This article is about how to use Data Template in silverlight or WPF.

Data Template:

         Template gives you option to change appearance of data item in controls like Grid, ListBox, ComboBox etc, for example simple ComboBox contain multiple value in drop down format but with the help of Template we can change the appearance of it like drop down with image enclosed it and even something more.

When using data template in control it replace the existing appearance with new appearance,
Create Data Template:
It can be create in different ways
1.  in XAML
2. in Code behind
3. Using XamlReader

In Xaml:

In this method it’s directly defined in XAML page under <UserControl.Resources> section,
Example:
<UserControl.Resources>
        <DataTemplate>
            <ComboBox x:Name="ddChar" SelectionChanged="ddChar_SelectionChanged">
                <ComboBoxItem>A</ComboBoxItem>
                <ComboBoxItem>B</ComboBoxItem>
                <ComboBoxItem>C</ComboBoxItem>
                <ComboBoxItem>D</ComboBoxItem>
                <ComboBoxItem>F</ComboBoxItem>
                <ComboBoxItem>G</ComboBoxItem>
            </ComboBox>
        </DataTemplate>
    </UserControl.Resources>

It can be applied to any control in code behind by using Resources Dictionary, its nothing but key value pair dictionary which hold some set of resources, template etc
lstNames = Resources["oddNumberTemplate"] as DataTemplate;

lstNames is an ListBox, in which we are binding our ComboBox, this method can be used in both Silverlight and WPF

In Code Behind:

 This method can only be used in WPF, Silverlight doesn’t support direct creation of DataTemplate, it can be created by
Example:


ListView lstView; //  ListView
// create and add the data template to the parent control
DataTemplate dTemp = new DataTemplate(typeof(ComboBox ));
lstView.ItemTemplate = dTemp;

// create and add the Combo box to the data template
FrameworkElementFactory cmbElement =
    new FrameworkElementFactory(typeof(ComboBox ));
dTemp.VisualTree = cmbElement;

// Create binding
Binding bind = new Binding();
bind.Path = new PropertyPath("ComboBoxItem");
bind.Mode = BindingMode.TwoWay;

// set the binding in the Combo Box
cmbElement.SetBinding(ComboBox.ComboBoxItem, bind);
cmbElement.SetValue(ComboBox.ComboBoxItem, "hello");


Steps:

1.  Create DataTemplate by specifying type ex: ComboBox
2. Attach Created Template to parent Element ItemTemplate
3. Create FrameworkElementFactory by specifying type of DataTemplate
4. Attach DataTemplate to Visual Tree.
5. Create Binding by specifying mode and path


Using XAML Reader:

It can be used in both Silverlight and WPF, but widely used in Silverlight, it can be created with the help of string builder or string
Example:
StringBuilder xamlData = new StringBuilder();
     xamlData.Append("<DataTemplate xmlns='http://schemas.microsoft.com/client/2007'  xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>");

     xamlData.Append("<ComboBox ");
     xamlData.Append("SelectionChanged=\"ComboBox_SelectionChanged\" ");
     xamlData.Append(">");
     foreach (var number in Enumerable.Range(1,100))
        {
          xamlData.Append(String.Format("<ComboBoxItem Content='{0}'  />", number ));
        }
     xamlData.Append("</ComboBox> ");
     xamlData.Append("</DataTemplate>");

Add DataTemplate(ComboBox) in silverlight page programmatically

Here we have DataGridTemplateColumn,add this template column into datagrid as Follow.

        DataGridTemplateColumn template = new DataGridTemplateColumn();
               templateColumn.Header = 
"";
               templateColumn.CellTemplate = (
DataTemplate
)
               
XamlReader.Load(@xamlData);
        this
.dataGrid1.Columns.Add(template);




Tuesday, November 26, 2013

Validation in MVVM

Validation in MVVM - Silverlight part I

Purpose:

            Values a user may enter in this form can be restricted by the system (Silverlight application) and have to fit exactly to a list of requirements or you just want to prevent problems when saving the data to the database. Showing a message to the user when a value is entered is pretty straight forward as I'll show you in the following example.

Using Validation Exception:

                Validation exception occurs if an input value does not match the expected data type, range or pattern of the data field. Values a user may enter in this form can be restricted by the customer and have to fit exactly to a list of requirements or you just want to prevent problems when saving the data to the database.  For example, if a user enters an integer value in a data field that expects a DateTime value, a validation exception occurs.

Validation in MVVM:

Step 1:
To implement MVVM pattern create ViewModelBase, which implement INotifyPropertyChanged, to notify any change in view model to XAML.

Example:
public abstract class ViewModelBase:INotifyPropertyChanged
    {
        #region INotifyPropertyChangeImplemetation

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion INotifyPropertyChangeImplemetation

        protected void NotifyPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


Step 2:
Create Silverlight application and a class for ViewModel (class should implement ViewModelBase)
Example:
public class MainPageViewModel : ViewModelBase


Step 3:
Create required XAML as mentioned below, in XAML two properties should be set to TRUE to notify any validation errors

ValidatesOnExceptions= True, it will throw error if validation fails.

NotifyOnValidationError=True, it highlight the control which contain error.

Mode=TwoWay, Binding should be TwoWay for validation in MVVM

<TextBox Text="{Binding Age,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" Margin="5"></TextBox>

Set DataContext for XAML, to establish link between XAML and ViewModel
xmlns:VM="clr-namespace:ValidationInSilverlight"

and

<UserControl.DataContext>
        <VM:MainPageViewModel />
</UserControl.DataContext>


Step 5:
In the ViewModel,
Import using System.ComponentModel.DataAnnotations name space to use ValidationException, this will be thrown if during error.

Create property to hold value and validate before setting value to variable, like below

private int age;

public int Age
        {
            get { return age; }
            set
            {
                if (value <= 0 || age > 200)
                {
                    throw new ValidationException("Age Should be between 0 - 200");
                }
                age = value;
                NotifyPropertyChange("Age");
            }
        }


Note:

         Validation takes place, once the focus goes out of control or values removed.

Sample Description:
         Sample contain some more example like mandatory field, email

Project Sample:

Thursday, November 21, 2013

Using IValue Converter


Description:

             Value converter needs to implement the IValueConverter interface. IValueConverter had 2 public method (Convert and ConvertBack) with object return type (can return any data type), each method had four parameter

Convert:

Modifies source data from view model before display in XAML
value:
Data going to be processed before display
targetType:
Type of data expected by the target
Parameter:
Optional parameter for conversion logic ex: not operator, convert true to false and vice versa.
culture:
current culture used

ConvertBack:

Modifies destination data from XAML before processing in view model
value:
Destination data being processed by method
targetType:
Data expected by source object
parameter:
Optional parameter for conversion logic
culture:
Current culture used in processing

When to use value converter

                 Value converters are mostly used in situation like conversion from one format to another format without modifying source data, widely used example like covert from  Celsius to Fahrenheit and vice versa.

Other example:

1. Conversion like from pounds to kilogram or gram etc.
2. Conversion from Boolean true to visibility and vice versa

Implementation:

              Let us implement simple temperature converter, which convert from Celsius to Fahrenheit and vice versa

Step 1: import System.Windows.Data and System.Globalization namespace.
Step 2: Add class file which inherit IValueConverter.
Step 3: Formula to convert from 
             Celsius to Fahrenheit is 37°C x  9/5 + 32 = 98.6°F and convert from 
             Fahrenheit to Celsius is (98.6°F  -  32)  x  5/9 = 37°C, 

Implement these two methods as below

public class TemperatureConverter:IValueConverter
    {
        /// <summary>
        /// Celsius to Fahrenheit
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue * 9) / 5) + 32;
            }
            return null;
        }

        /// <summary>
        /// Fahrenheit to Celsius
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Int64)
            {
                Int64 currValue = (Int64)value;
                return ((currValue - 32) * 5) /9;
            }
            return null;           
        }
    }



Using Value Converter in XAML:

Step 1: Import the namespace of class to XAML
xmlns:codes="clr-namespace:IValueConverterImplementation.Codes"

Step 2: Import the Value convertor to UserControl Resources, so that it can be used in XAML
<codes:TemperatureConverter x:Name="TemperatureConverter" />

Step 3: Define Controls and used it in Converter, StaticResource property

Example:

Without converter:
<TextBlock Text="{Binding Temperature}" ></TextBlock>

With Converter:
<TextBlock Text="{Binding Temperature,Converter={StaticResource TemperatureConverter}}" ></TextBlock>

In Text="{Binding Temperature}", Temperature is Int64 value from ViewModel.




Project Sample:

In demo project, you can find more examples like
1. DateTimeConverter – to convert DateTime to Date or short date
2. TextConverter – to convert incoming string to Upper or Lower Case
3. BooleanToVisibleConverter – convert false to Collapsed and true to Visible


Tuesday, November 19, 2013

Data Import from CSV file to DataTable

             In this article, we will how to import CSV data to dot net DataTable with Stream and StreamReader in c#.

Using OpenFileDialog,

We can enable users to select files in a Silverlight-based application by using the OpenFileDialog class. After the user has selected one or more files, we can process the selected files.

Steps to include OpenFileDialog,

1. Create an instance of the OpenFileDialog class.
2. Optionally, specify the file filter string and the filter index by setting the Filter and FilterIndex properties.
3. Call the ShowDialog method to display the open file dialog box.
4. When the method returns, test whether the dialog box was closed with the OK button or the Cancel button. If it was closed with the OK button, process the user's selection.

Using StopWatch,

To keep track the elapsed time to import data from CSV to windows grid
1.  Import namespace System.Diagnostics
2. Create object for StopWatch Class and call start method.
3. Once the process complete Stop the Watch, find the time in ElapsedMilliseconds or in TimeSpan format.


Using Stream and StreamReader,

By using the stream and StreamReader we read data from the CSV file,
For more info about File Reading and StreamReader refer




Steps to create CSV file


1. Open Excel and type details in format like header followed by details required
2. In save dialog change Save as type to CSV (Comma delimited) and gave some file name.


Its saved as csv file, separted by comma(,) for each value in excel cell

Project Sample: