ASPHostDirectory.COM Cheap Silverlight Hosting

Blog about Silverlight Hosting and all its latest technology

ASPHostDirectory Silverlight 4 Hosting :: Export data to Excel from Silverlight/WPF DataGrid

clock December 23, 2010 09:41 by author Darwin

Data export from DataGrid to Excel is very common task, and it can be solved with different ways, and chosen way depend on kind of app which you are design. If you are developing app for enterprise, and it will be installed on several computes, then you can to advance a claim (system requirements) with which your app will be work for client. Or customer will advance system requirements on which your app should work. In this case you can use COM for export (use infrastructure of Excel or OpenOffice). This approach will give you much more flexibility and give you possibility to use all features of Excel app. About this approach I’ll speak below. Other way – your app is for personal use, it can be installed on any home computer, in this case it is not good to ask user to install MS Office or OpenOffice just for using your app. In this way you can use foreign tools for export, or export to xml/html format which MS Office can read (this approach used by JIRA). But in this case will be more difficult to satisfy user tasks, like create document with landscape rotation and with defined fields for printing.

Integration with Excel from Silverlight 4 and .NET 4

In Silverlight 4 and .NET 4 we have dynamic objects, which give us possibility to use MS Office COM objects without referenced to MS Office dlls. So for creating excel document in .NET 4 you can write this code::

dynamic excel = Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", string.Empty);

And in Silverlight 4 this:

dynamic excel = AutomationFactory.CreateObject("Excel.Application");

If you want to use AutomationFactory in Silverlight 4 app you need to set “Required elevated trust when running outside the browser” in project settings. You can check at code that your app have this privileges with property AutomationFactory.IsAvailable.

First, lets design new method, which will export to Excel two-dimension array:

public static void ExportToExcel(object[,] data) { /* ... */ }

Above I wrote how to get instance of Excel app. Now we will write some additional requirements for export:

excel.ScreenUpdating = false;
dynamic workbook = excel.workbooks;
workbook.Add(); 

dynamic worksheet = excel.ActiveSheet;

const int left = 1;
const int top = 1;
int height = data.GetLength(0);
int width = data.GetLength(1);
int bottom = top + height - 1;
int right = left + width - 1;

if (height == 0 || width == 0)
  return;

In this code we set that Excel will not show changes until we allow. This approach will give us little win in performance. Next we create new workbook and get active sheet of this book. And then get dimension of range where we will place our data.

Next step – export to Excel. When you export to excel with set data by cell this is slowly approach than export data to range of cells (you can try to compare speed of exporting with 1000 rows). So we will use setting data for range of cells:

dynamic rg = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[bottom, right]];
rg.Value = data;

Ok, our data in excel document. This approach work in .NET, but doesn’t work in Silverlight 4. When I tried to export data like I wrote above I got exception 

{System.Exception: can't convert an array of rank [2]
   at MS.Internal.ComAutomation.ManagedObjectMarshaler.MarshalArray(Array array, ComAutomationParamWrapService paramWrapService, ComAutomationInteropValue& value)
   at MS.Internal.ComAutomation.ManagedObjectMarshaler.MarshalObject(Object obj, ComAutomationParamWrapService paramWrapService, ComAutomationInteropValue& value, Boolean makeCopy)
   at MS.Internal.ComAutomation.ComAutomationObject.InvokeImpl(Boolean tryInvoke, String name, ComAutomationInvokeType invokeType, Object& returnValue, Object[] args)
   at MS.Internal.ComAutomation.ComAutomationObject.Invoke(String name, ComAutomationInvokeType invokeType, Object[] args)
   at System.Runtime.InteropServices.Automation.AutomationMetaObjectProvider.TrySetMember(SetMemberBinder binder, Object value)
   at System.Runtime.InteropServices.Automation.AutomationMetaObjectProviderBase.<.cctor>b__3(Object obj, SetMemberBinder binder, Object value)
   at CallSite.Target(Closure , CallSite , Object , Object[,] )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at ExportToExcelTools.ExportManager.ExportToExcel(Object[,] data)
   at ExportToExcelTools.DataGridExcelTools.StartExport(Object data)
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)}


For export in Silverlight I use this code (export by rows):

for (int i = 1; i <= height; i++)
{
  object[] row = new object[width];
  for (int j = 1; j <= width; j++)
  {
    row[j - 1] = data[i - 1, j - 1];
  }
  dynamic r = worksheet.Range[worksheet.Cells[i, left], worksheet.Cells[i, right]];
  r.Value = row;
  r = null;
}

If you are developing app just for Silverlight you can use some other data structure instead of array. I try to write code which will work at .NET and Silverlight so I will use arrays.

After data export we should to set to Excel object that it can apply changes, and then we will show it:

excel.ScreenUpdating = true;
excel.Visible = true;

Before this we can set more beautiful view of our document:

// Set borders
for (int i = 1; i <= 4; i++)
  rg.Borders[i].LineStyle = 1;

// Set auto columns width
rg.EntireColumn.AutoFit();

// Set header view
dynamic rgHeader = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[top, right]];
rgHeader.Font.Bold = true;
rgHeader.Interior.Color = 189 * (int)Math.Pow(16, 4) + 129 * (int)Math.Pow(16, 2) + 78; // #4E81BD

With this code we set borders, set auto size for cells and mark out first row (with background color and special style for text – it will be bold): it will be header, which will show DataGrid column’s headers. If you want to set more you can use Excel macros to get how to change document view: you need to start record macro, then change interface by hand, end record macro and look at macro code.

At the end of export you need to clean resources. In .NET for solve this you can use method Marshal.ReleaseComObject(…), but Silverlight doesn’t have this method, but we can set null to variables and then invoke garbage collector collect method:

#if SILVERLIGHT
#else
Marshal.ReleaseComObject(rg);
Marshal.ReleaseComObject(rgHeader);
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
#endif
rg = null;
rgHeader = null;
worksheet = null;
workbook = null;
excel = null;
GC.Collect();

So know we have this code:

using System;
#if SILVERLIGHT
using System.Runtime.InteropServices.Automation;
#else
using System.Runtime.InteropServices;
#endif 

namespace ExportToExcelTools
{
  public static class ExportManager
  {
    public static void ExportToExcel(object[,] data)
    {
#if SILVERLIGHT
      dynamic excel = AutomationFactory.CreateObject("Excel.Application");
#else
      dynamic excel = Microsoft.VisualBasic.Interaction.CreateObject("Excel.Application", string.Empty);
#endif 

      excel.ScreenUpdating = false;
      dynamic workbook = excel.workbooks;
      workbook.Add(); 

      dynamic worksheet = excel.ActiveSheet; 

      const int left = 1;
      const int top = 1;
      int height = data.GetLength(0);
      int width = data.GetLength(1);
      int bottom = top + height - 1;
      int right = left + width - 1; 

      if (height == 0 || width == 0)
        return; 

      dynamic rg = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[bottom, right]];
#if SILVERLIGHT
      //With setting range value for recnagle export will be fast, but this aproach doesn't work in Silverlight
      for (int i = 1; i <= height; i++)
      {
        object[] row = new object[width];
        for (int j = 1; j <= width; j++)
        {
          row[j - 1] = data[i - 1, j - 1];
        }
        dynamic r = worksheet.Range[worksheet.Cells[i, left], worksheet.Cells[i, right]];
        r.Value = row;
        r = null;
      }
#else
      rg.Value = data;
#endif 

      // Set borders
      for (int i = 1; i <= 4; i++)
        rg.Borders[i].LineStyle = 1; 

      // Set auto columns width
      rg.EntireColumn.AutoFit(); 

      // Set header view
      dynamic rgHeader = worksheet.Range[worksheet.Cells[top, left], worksheet.Cells[top, right]];
      rgHeader.Font.Bold = true;
      rgHeader.Interior.Color = 189 * (int)Math.Pow(16, 4) + 129 * (int)Math.Pow(16, 2) + 78; // #4E81BD     

      // Show excel app
      excel.ScreenUpdating = true;
      excel.Visible = true;

#if SILVERLIGHT
#else
      Marshal.ReleaseComObject(rg);
      Marshal.ReleaseComObject(rgHeader);
      Marshal.ReleaseComObject(worksheet);
      Marshal.ReleaseComObject(workbook);
      Marshal.ReleaseComObject(excel);
#endif
      rg = null;
      rgHeader = null;
      worksheet = null;
      workbook = null;
      excel = null;
      GC.Collect();
    }
  }
}

Export data from DataGrid to two-dimension array

So we have method which export array to Excel, now we need to write method which will export DataGrid data to array. In WPF we can get all items with Items property, but in Silverlight this property is internal. But we can use ItemsSource property and cast it to List:

List<object> list = grid.ItemsSource.Cast<object>().ToList();

Before we realize export I want to think about features we need:

1. In some cases we want to export not all columns from data grid, so we need an approach to disable export some of columns.
2. In some cases columns don’t have header (text header), but in excel we want to see text header or header with other text than data grid have, so we need an approach to set header text for export.
3. It is easy to get which properties of object need to show in excel cell for columns with types inherited from DataGridBoundColumn because it has Binding with Path, with which we can get path for export value. But in case when we use DataGridTemplateColumn it is more hardly to find out which values of which property need to export. This is why we need an approach to set custom path for export (more we can use SortMemberPath).
4. We need to set formatting for export to Excel.


I solved all of this problems with attached properties:

/// <summary>
/// Include current column in export report to excel
/// </summary>
public static readonly DependencyProperty IsExportedProperty = DependencyProperty.RegisterAttached("IsExported",                                                                         typeof(bool), typeof(DataGrid), new PropertyMetadata(true));

/// <summary>
/// Use custom header for report
/// </summary>
public static readonly DependencyProperty HeaderForExportProperty = DependencyProperty.RegisterAttached("HeaderForExport",                                                                                typeof(string), typeof(DataGrid), new PropertyMetadata(null));

/// <summary>
/// Use custom path to get value for report
/// </summary>
public static readonly DependencyProperty PathForExportProperty = DependencyProperty.RegisterAttached("PathForExport",                                                                                typeof(string), typeof(DataGrid), new PropertyMetadata(null));

/// <summary>
/// Use custom path to get value for report
/// </summary>
public static readonly DependencyProperty FormatForExportProperty = DependencyProperty.RegisterAttached("FormatForExport",                                                                               typeof(string), typeof(DataGrid), new PropertyMetadata(null));

#region Attached properties helpers methods 
public static void SetIsExported(DataGridColumn element, Boolean value)
{
  element.SetValue(IsExportedProperty, value);


public static Boolean GetIsExported(DataGridColumn element)
{
  return (Boolean)element.GetValue(IsExportedProperty);


public static void SetPathForExport(DataGridColumn element, string value)
{
  element.SetValue(PathForExportProperty, value);


public static string GetPathForExport(DataGridColumn element)
{
  return (string)element.GetValue(PathForExportProperty);


public static void SetHeaderForExport(DataGridColumn element, string value)
{
  element.SetValue(HeaderForExportProperty, value);


public static string GetHeaderForExport(DataGridColumn element)
{
  return (string)element.GetValue(HeaderForExportProperty);


public static void SetFormatForExport(DataGridColumn element, string value)
{
  element.SetValue(FormatForExportProperty, value);


public static string GetFormatForExport(DataGridColumn element)
{
  return (string)element.GetValue(FormatForExportProperty);


#endregion

Then I use this code for getting all columns for export:

List<DataGridColumn> columns = grid.Columns.Where(x => (GetIsExported(x) && ((x is DataGridBoundColumn)
          || (!string.IsNullOrEmpty(GetPathForExport(x))) || (!string.IsNullOrEmpty(x.SortMemberPath))))).ToList();

With this code we get all columns with true values of IsExported attached property (I set true as default value for this attached property above) and for which I can get export path (binding or custom setting path, or SortMemberPath is not null).

Next we will create new two-dimension array, first dimension is number of elements plus one – for header. And then set text headers into first row of array:


// Create data array (using array for data export optimization)
object[,] data = new object[list.Count + 1, columns.Count]; 

// First row will be headers
for (int columnIndex = 0; columnIndex < columns.Count; columnIndex++)
  data[0, columnIndex] = GetHeader(columns[columnIndex]);

Method GetHeader try to get values from HeaderForExport attached property for current column and if it has null value method get header from column:

private static string GetHeader(DataGridColumn column)
{
  string headerForExport = GetHeaderForExport(column);
  if (headerForExport == null && column.Header != null)
    return column.Header.ToString();
  return headerForExport;
}

Then we fill array with values from DataGrid:

for (int columnIndex = 0; columnIndex < columns.Count; columnIndex++)
{
  DataGridColumn gridColumn = columns[columnIndex]; 

  string[] path = GetPath(gridColumn); 

  string formatForExport = GetFormatForExport(gridColumn); 

  if (path != null)
  {
    // Fill data with values
    for (int rowIndex = 1; rowIndex <= list.Count; rowIndex++)
    {
      object source = list[rowIndex - 1];
      data[rowIndex, columnIndex] = GetValue(path, source, formatForExport);
    }
  }
}

Method GetPath is easy, it try to get path from set by attached property value or binding or SortMemberPath. I only support easy paths: with only properties as chain of path, I don’t support arrays or static elements in paths, and of course I mean that binding set for current row item:

private static string[] GetPath(DataGridColumn gridColumn)
{
  string path = GetPathForExport(gridColumn); 

  if (string.IsNullOrEmpty(path))
  {
    if (gridColumn is DataGridBoundColumn)
    {
      Binding binding = ((DataGridBoundColumn)gridColumn).Binding as Binding;
      if (binding != null)
      {
        path = binding.Path.Path;
      }
    }
    else
    {
      path = gridColumn.SortMemberPath;
    }
 

  return string.IsNullOrEmpty(path) ? null : path.Split('.');
}

After getting path value with method GetValue we will try to get value by this path for current item:

private static object GetValue(string[] path, object obj, string formatForExport)
{
  foreach (string pathStep in path)
  {
    if (obj == null)
      return null; 

    Type type = obj.GetType();
    PropertyInfo property = type.GetProperty(pathStep); 

    if (property == null)
    {
      Debug.WriteLine(string.Format("Couldn't find property '{0}' in type '{1}'", pathStep, type.Name));
      return null;
   

    obj = property.GetValue(obj, null);
 

  if (!string.IsNullOrEmpty(formatForExport))
    return string.Format("{0:" + formatForExport + "}", obj); 

  return obj;
}

Sample

For sample I wrote some model classes and fill test data:

public class Person
{
  public string Name { get; set; }
  public string Surname { get; set; }
  public DateTime DateOfBirth { get; set; }


public class ExportToExcelViewModel
{
  public ObservableCollection<Person> Persons
  {
    get
    {
      ObservableCollection<Person> collection = new ObservableCollection<Person>();
      for (int i = 0; i < 100; i++)
        collection.Add(new Person()
        {
          Name = "Person Name " + i,
          Surname = "Person Surname " + i,
          DateOfBirth = DateTime.Now.AddDays(i)
        });
      return collection;
    }
  }
}

In WPF window I use this xaml declaration:

<Window x:Class="ExportToExcelSample.MainWindow"
        xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ExportToExcelSample="clr-namespace:ExportToExcelSample"
        xmlns:ExportToExcelTools="clr-namespace:ExportToExcelTools;assembly=ExportToExcelTools" >
    <Window.DataContext>
        <ExportToExcelSample:ExportToExcelViewModel />
    </Window.DataContext>
    <ScrollViewer>
        <StackPanel>
            <Button Click="Button_Click">Export To Excel</Button>
            <DataGrid x:Name="grid" ItemsSource="{Binding Persons}" AutoGenerateColumns="False" >
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" />
                    <DataGridTextColumn Binding="{Binding Path=Surname}" Header="Surname"                                        ExportToExcelTools:DataGridExcelTools.HeaderForExport="SecondName" />
                    <DataGridTemplateColumn ExportToExcelTools:DataGridExcelTools.FormatForExport="dd.MM.yyyy"                                            ExportToExcelTools:DataGridExcelTools.PathForExport="DateOfBirth"                                           ExportToExcelTools:DataGridExcelTools.HeaderForExport="Date Of Birth">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel>
                                    <TextBlock Text="{Binding
Path=DateOfBirth, StringFormat=dd.MM.yyyy}" />
                                    <TextBlock Text="{Binding
Path=DateOfBirth, StringFormat=HH:mm}" />
                                </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>
    </ScrollViewer>
</Window>

And method Button_Click with this code:

private void Button_Click(object sender, RoutedEventArgs e)
{
  grid.ExportToExcel();
}

Where ExportToExcel is extension method for DataGridm which invoke export to Excel method with separate thread. That's all. In Silverlight 4 code will be exactly the same. Below I’ll put anchor with samples for Silverlight 4 and WPF 4 (solution for Visual Studio 2010).

What is so SPECIAL on ASPHostDirectory.com Silverlight 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in
Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight 4 Hosting :: Silverlight 4 and MVVM pattern with ICommand

clock November 9, 2010 05:34 by author Darwin

MVVM (Model- View – View Model) is the WPF / Silverlight UI design Pattern code model. A certain guideline a developer should follows in order to achieve a more testable, debug gable, manageable, readable Application.

A zero code behind, yes no button click event hander in the code behind file, no form / windows load logic, no UI binding logic, No UI validation or type casting code in the code behind file. Yes i menn no code or logic in the UI mainpage.xaml.cs file.

Following features are used in order to achieve the MVVM pattern with no logic on the UI code behind file , and to make sure that the presentation layer and logic loosely couple.

1) Two way binding capability of WPF/Silverlight UI (XAML)
2) IValueConvert for binding (eg: string class converting to colour class)
3) INotification or Dependency Property
4) Data context
5) Static resources
6) Icommand for avoiding the code behind event handler.
7) Use of validation=true in xaml(presentation layer)


Before MVVM, the MVP pattern was famous for winform and wpf
applications ( Though it never took the full advantage of the Two way binding feature of WPF). MVC pattern is still famous with Asp.net Application.
Draw back of the old fashion winform or wpf / Silverlight application (with no mvvm pattern)


1) The Presentation and the code behind logic were tightly coupled
2) If we change the UI control we have change the logic in the code behind
3) Cannot imagine of more than one view sharing the same logic.
4) Not possible to write a unit test for a code behind, as the
presentation layer is tightly couple to the control.
5) In normal WPF application the view (xaml) is just treated as a data
storage.


Advantages of MVVM pattern:

1) Proper layering of the view and the data. The data is not stored in
view, View is just for presenting the data.
2) Clean testable and manageable code.
3) NO code behind so the Presentation layer and the logic are loosely
coupled.
4) With Silverlight 4.0 we have a new Icommand Support


In this example we have a textbox displaying Personname and another textbox displaying PersonAge,and on a click of a button the age will increment by a year till 26... the code is done in MVVM pattern.

Step 1: Create a Silverlight Application in Viual studio 2010 and name it as “simplePersonandageMVVM”

Step 2: Once created add a class file and call it as “PersonModel.cs” and paste this code . (this would be the model thats is data object)

using System.ComponentModel;

namespace simplePersonandageMVVM
{  

    public class PersonModel : InotifyPropertyChanged
    {
        string name;
        public string Name
        {
            get { return this.name; }
            set
            {
                this.name = value;
                fire("Name");

            }
        }
        int age;
        public int Age
        {
            get { return this.age; }
            set
            {
                this.age = value;
                fire("Age");
            }
        }
        public PersonModel() { }
        public PersonModel(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

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

}

Step 3: Create another class call it as “PersonViewModel.cs” This would be the viewModel and will take the role of an adapter between view(presentation layer) and the Model(entity class).

namespace simplePersonandageMVVM
{
    public class PersonViewModel
    {
        public PersonModel p { get; set; }
        public PersonViewModel()
        {
            p = new PersonModel("prabjot", 20);                    
        }

        public ICommand GetPerson
        {
            get { return new GetPersonCommand(this); }
        }       

        public void Increaseage(PersonModel d)
        {
            d.Age++;         
            string x = d.Age.ToString();          
            MessageBox.Show(x);               

        }
    }
}

Step 4: Create a Command object class implementing the ICOMMAND interface and call it as “GetPersonCommand.cs”. This class overrides both the Icommand methods. Here the method CanExecute() checks for the condition if its met then only the button click is enable. Where as the other method Execute() takes care of execution on button click.

namespace simplePersonandageMVVM
{
    public class GetPersonCommand : Icommand
    {
        PersonViewModel pincommand;
        public GetPersonCommand( PersonViewModel Pcame)
        {
          pincommand= Pcame;          

          
        }

        public bool CanExecute(object parameter)
        {
           if(pincommand.p.Age > 25)
           {
               return false ;
           }
        else
           {
               return true;
           }           

        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
           pincommand.Increaseage(pincommand.p);
        }
    }
}

Step 5: Finally your xaml file looks like this

<UserControl x:Class="simplePersonandageMVVM.MainPage"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:d=http://schemas.microsoft.com/expression/blend/2008
    xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
             xmlns:local="clr-namespace:simplePersonandageMVVM"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:PersonViewModel  x:Key="pkey" />
    </UserControl.Resources>   

    <Grid x:Name="LayoutRoot" Background="White"
          DataContext="{Binding Source={StaticResource pkey}}" >
        <Grid Name="hi" DataContext="{Binding Path=p, Mode=TwoWay}">
            <TextBox Height="23" HorizontalAlignment="Left" Margin="53,30,0,0"
                 Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Name, Mode=TwoWay}" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="53,68,0,0" Name="textBox2"
                 Text="{Binding Path=Age, Mode=TwoWay}"  VerticalAlignment="Top" Width="120" />
            <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="53,112,0,0" Name="button1"
                VerticalAlignment="Top" Width="75"  Command="{Binding Path=DataContext.GetPerson, ElementName= LayoutRoot }"
                    CommandParameter="{Binding Path=Age, ElementName=hi}"  />
      </Grid>
    </Grid>     

</UserControl>

What is so SPECIAL on ASPHostDirectory.com Silverlight 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service
- We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration
- With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight 4 Hosting :: Working with DataForm in Microsoft Silverlight 4

clock October 29, 2010 10:48 by author Darwin

Follow this steps:

1. Start a new Silverlight solution, name it DataFormExample, and add a reference to System.Windows.Controls.Data.DataForm.Toolkit (from the Silverlight Toolkit). Alternatively, you can drag the DataForm from the Toolbox to the design surface.

2. Open MainPage.xaml and add a namespace import statement at the top of this fi le (in the tag) as shown in the following code. This will allow us to use the DataForm, which resides in the assembly that we've just referenced.

xmlns:df="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data.DataForm.Toolkit"

3. Add a DataForm to MainPage.xaml and name it as myDataForm. In the DataForm, set AutoEdit to False and CommandButtonsVisibility to All as shown in the following code:

<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="40" ></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="Working with the DataForm"
Margin="10"
FontSize="14" >
</TextBlock>
<df:DataForm x:Name="myDataForm"
AutoEdit="False"
CommandButtonsVisibility="All"
Grid.Row="1"
Width="400"
Height="300"
Margin="10"
HorizontalAlignment="Left"
VerticalAlignment="Top" >
</df:DataForm>
</Grid>

4. Add a new class named Person to the Silverlight project having ID, FirstName, LastName, and DateOfBirth as its properties. This class is shown in the following code. We will visualize an instance of the Person class using the DataForm.

public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}

5. Open MainPage.xaml.cs and add a person property of the Person type to it. Also, create a method named InitializePerson in which we'll initialize this property as shown in the following code:

public Person person { get; set; }
private void InitializePerson()
{
person = new Person()
{
ID = 1,
FirstName = "Darwin",
LastName = "Marx",
DateOfBirth = new DateTime(1980, 10, 5)
};
}

6. Add a call to InitializePerson in the constructor of MainPage.xaml.cs and set the CurrentItem property of the DataForm to a person as shown in the following code:

InitializePerson();
myDataForm.CurrentItem = person;

7. You can now build and run your solution. When you do this, you'll see a DataForm that has automatically generated the necessary fields in order to display a person.

How it works

To start off, we needed something to display in our DataForm: a Person entity. This is why we've created the Person class: it will be bound to the DataForm by setting the CurrentItem property to an object of type Person.

Doing this will make sure that the DataForm automatically generates the necessary fi elds. It looks at all the public properties of our Person object and generates the correct control depending on the type. A string will be displayed as a TextBox, a Boolean value will be displayed as a CheckBox, and so on.

As we have set the CommandButtonsVisibility property on the DataForm to All, we get an Edit icon in the command bar at the top of the DataForm. (Setting AutoEdit to False makes sure that we start in the display mode, rather than the edit mode). When you click on the Edit icon, the DataForm shows the person in the editable mode (using the EditItemTemplate) and an OK button appears. Clicking on the OK button will revert the form to the regular displaying mode. Do keep in mind that the changes you make to the person are persisted immediately in memory (in the case of a TextBox, when it loses focus).

If necessary, you can write extra code to persist the Person object from the memory to an underlying datastore by handling the ItemEditEnded event on the DataForm.

There's more...

At this moment, we've got a DataForm displaying a single item that you can either view or edit. But what if you want to cancel your edit? As of now, the Cancel button appears to be disabled. As the changes you make in the DataForm are immediately persisted to the underlying object in the memory, cancelling the edit would require some extra business logic. Luckily, it's not hard to do.

First of all, you'll want to implement the IEditableObject interface on the Person class, which will make sure that cancelling is possible. As a result, the Cancel button will no longer be disabled. The following code is used to implement this:

public class Person : IEditableObject
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public void BeginEdit()
{}
public void CancelEdit()
{}
public void EndEdit()
{}
}

This interface exposes three methods: BeginEdit, CancelEdit, and EndEdit. If needed, you can write extra business logic in these methods, which is exactly what we need to do. For most applications, you might want to implement only CancelEdit, which would then refetch the person from the underlying data store. In our example, we're going to solve this problem by using a different approach. (You can use this approach if you haven't got an underlying database from which your data can be refetched, or if you don't want to access the database again.) In the BeginEdit method, we save the current property values of the person. When the edit has been cancelled, we put them back to the way they were before. This is shown in the following code:

public void BeginEdit()
{
// save current values
tmpPerson = new Person()
{
ID = this.ID,
FirstName = this.FirstName,
LastName = this.LastName,
DateOfBirth = this.DateOfBirth
};
}
public void CancelEdit()
{
// reset values
ID = tmpPerson.ID;
FirstName = tmpPerson.FirstName;
LastName = tmpPerson.LastName;
DateOfBirth = tmpPerson.DateOfBirth;
}

Now, cancelling an edit is possible and it actually reverts to the previous property values.

More on DataForm behavior

The DataForm exposes various events such as BeginningEdit (when you begin to edit an item), EditEnding (occurs just before an item is saved), and EditEnded (occurs after an item has been saved). It also exposes properties that you can use to defi ne how the DataForm behaves.

Validating a DataForm or a DataGrid

As you might have noticed, the DataForm includes validation on your fields automatically. For example, try inputting a string value into the ID field. You'll see that an error message appears. This is beyond the scope of this recipe, but more on this will be discussed in the Validating the DataForm recipe.

Managing the editing of an object on different levels

There are different levels of managing the editing of an object. You can manage this on the control level itself by handling events such as BeginningEdit or ItemEditEnded in the DataForm. Besides that, you can also handle editing on a business level by implementing the IEditableObject interface and providing custom code for the BeginEdit, CancelEdit, or EndEdit methods in the class itself. Depending on the requirements of your application, you can use either of the levels or even both together.

What is so SPECIAL on ASPHostDirectory.com Silverlight 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in
Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight 4 Hosting :: Using Silverlight's Web Client Class

clock October 22, 2010 05:57 by author Darwin

Silverlight provides several different networking classes that can be used to retrieve data from distributed resources such as Web services, REST APIs and even sockets. By learning to use these classes, you can access data from nearly any source without having to write a lot of custom code to do it. In this article, we'll focus on the one of the key classes in the System.Net namespace named WebClient and show how it can be used to make asynchronous calls. By using it, you can call a variety of services exposed by Web sites such as Flickr.com, Digg.com and many more.

In cases where you don't have any control over the server that's being called by Silverlight, you can create a middleman service on your server to handle calling the remote service. Silverlight can then call your middleman service, which in turn calls the remote server to access the data.

If this sounds like too much work, you'll be happy to know that another option does exist to help mitigate cross-domain call issues. If the owner of distributed service wants Silverlight clients to be able to call the service, they can place a Flash crossdomain.xml file or a Silverlight clientaccesspolicy.xml file at the root of their server. These specialized XML files define whether remote callers such a Flash and Silverlight are allowed to call services on the server. Although I won't provide details about these files here, Microsoft provides a nice summary here if you're interested in additional details. Silverlight supports a subset of Flash's crossdomain.xml specification.

Now that we've touched on some of the cross-domain issues you may encounter, let's talk more about using the WebClient class.

Using the WebClient Class

If you've worked with any of the classes in the System.Net namespace, you've more than likely used or seen the WebClient class. It's been in the .NET Framework since it was first released.

Silverlight also provides a WebClient class that can be used to make asynchronous calls to a distributed service. Unlike the .NET Framework's WebClient class, the Silverlight version is asynchronous by default since remote service calls can lock up the browser -- leading to an unpleasant end user experience.

Fortunately, you don't have to be an expert in asynchronous communications and threading to work with the WebClient class. It provides several different properties, methods and events that simplify the process.

To use the WebClient, class you'll need to follow three simple steps:

1. Create an instance of System.Net.WebClient in your Silverlight application code.
2. Wire up the DownloadStringCompleted event to an event handler.
3. Call the DownloadStringAsync method.
4. Add code into the DownloadStringCompleted event handler to process the data returned from the remote service call.

Once the System.Net namespace has been imported, an instance of the WebClient class can be created. From there, the DownloadStringCompleted event can be wired to an event handler. The DownloadStringCompleted event is raised after data is returned from a remote service.

You can see this example below. This code wires the WebClient object's DownloadStringCompleted event to an event handler named linqClient_DownloadStringCompleted that's responsible for processing the data returned from the service. It accepts two parameters, including the sender and a DownloadStringCompletedEventArgs object that provides access to the service data.

WebClient linqClient = new WebClient();
linqClient.DownloadStringCompleted += new
  DownloadStringCompletedEventHandler(linqClient_DownloadStringCompleted);

To call the target service and retrieve data from it, invoke the WebClient's DownloadStringAsync() method and pass the remote service's address as a parameter:

linqClient.DownloadStringAsync(remoteURL);

This begins the call to the service and automatically routes any data returned to the appropriate event handler. Data is returned as a string, so you'll need to write code to process the data depending upon the format (XML, JSON, etc.).

private void linqClient_DownloadStringCompleted(object sender,
  DownloadStringCompletedEventArgs e)
{
    //Dispatcher.BeginInvoke(() => ProcessWithLinqToXml(e.Result));|
    ProcessWithLinqToXml(e.Result);

}

private void ProcessWithLinqToXml(string xmlData)
{
    XDocument doc = XDocument.Parse(xmlData);
    List photos = (from photo in doc.Descendants("photo")
        select new Model.Photo
        {
           Farm = photo.Attribute("farm").Value,
           ID = photo.Attribute("id").Value,
           IsFamily = ConvertBoolean(photo.Attribute("isfamily").Value),
           IsFriend = ConvertBoolean(photo.Attribute("isfriend").Value),
           IsPublic = ConvertBoolean(photo.Attribute("ispublic").Value),
           Owner = photo.Attribute("owner").Value,
           Secret = photo.Attribute("secret").Value,
           Server = photo.Attribute("server").Value,
           Title = photo.Attribute("title").Value,
        }).ToList();

     //Process Photo Objects
}

The code above demonstrates how data returned from a service can be accessed through a DownloadStringCompletedEventArgs object and processed using LINQ to XML functionality available in Silverlight.

You can see that the WebClient class provides a straightforward way to access distributed service data without having to worry about a lot of asynchronous complexities.

What is so SPECIAL on ASPHostDirectory.com Silverlight 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee -
ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support -
We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support
- if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee
- ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service
- We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration
- With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight Hosting :: Configure an AuthenticationDomainService Using RIA Services Class Library

clock October 7, 2010 07:14 by author Darwin

Today, we will explain brief tutorial about configure an AuthenticationDomainService using RIA services. We hope that we can give the best explanation that we can do. Please enjoy this tutorial.

Using a Ria Services Class library to collect DomainServices and DomainContexts in a solution is a good practice because everyone know the value of having classes separated in projects instead of having them in the web project.

To workaround to this problem you may simply write by hand this class and put it in the client side part of the Ria Services library project. The code can be copied by an AuthenticationDomainContext generated in the web project but it is very simple and we show you the code here:

public sealed partial class RiaContext : System.Windows.Ria.RiaContextBase
{
    #region Extensibility Method Definitions

    partial void OnCreated();

    #endregion

    public RiaContext()
    {
        this.OnCreated();
    }

    public new static RiaContext Current
    {
        get
        {
            return ((RiaContext)(System.Windows.Ria.RiaContextBase.Current));
        }
    }

    public new User User
    {
        get
        {
            return ((User)(base.User));
        }
    }
}

With this class you can configure the Authentication Domain Context as you did with the generated class. So you have to add it to the App.config, in the ApplicationLifetimeObjects tag and then add a kind of authentication like the WindowsAuthentication and FormsAuthentication.

The second drawback is that if you run the project this way and then you call the Login() method (or any other method) of the RiaContext you will get an error:

The DomainContextType is null or invalid and there are no contexts generated from AuthenticationBase<T>

This probably come from the fact that the RiaContext is not correctly initializated so when the class search for a valid domaincontext to handle the Login call it fails because it does not find it. The tip to correct this behavior is to specify the DomainContext property in the Authentication you have choosed. Here is how to change the App.xaml file:

<Application.ApplicationLifetimeObjects>
    <slpgria:RiaContext>
        <slpgria:RiaContext.Authentication>
            <appsvc:FormsAuthentication>
                <appsvc:FormsAuthentication.DomainContext>
                    <slpgdc:MyAuthenticationDomainContext />
                </appsvc:FormsAuthentication.DomainContext>
            </appsvc:FormsAuthentication>
        </slpgria:RiaContext.Authentication>
    </slpgria:RiaContext>
</Application.ApplicationLifetimeObjects>

As you can see you have simply to give an instance of the generated Authentication Domain context class to the FormsAuthentication (or Windows Authentication as well). The RiaContext need to have this instance to make the calls to the BL methods in the Domain Service.

Hope this post can help you. Need Silverlight 4 hosting? You can visit http://www.asphostdirectory.com.

What is so SPECIAL on ASPHostDirectory.com Silverlight 4 Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting - Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight Hosting :: Command Binding in Silverlight 4

clock August 18, 2010 08:44 by author Darwin

To implement the Command binding you have to create a DelegateCommand which implements the ICommand interface. The ICommand interface is available in System.Windows.Input namespace in the System.Windows.dll assembly. It defines the contract for commanding.

- It has an EventHandler “CanExecuteChanged” which occurs when changes occur that affect whether the command should execute.
- It has a method named “CanExecute” and returns boolean value true or false based on whether the command can be executed in its current state.
- Another method named “Execute” which calls when the command is invoked.

Here is the implementation of the ICommand interface:

namespace System.Windows.Input

   public interface ICommand 
   { 
       event EventHandler CanExecuteChanged; 
       bool CanExecute(object parameter); 
       void Execute(object parameter); 
    }
}

Now we have to implement the methods defined in the ICommand interface to our DelegateCommand class. Here is the simple implementation of the same:

using System;
using System.Windows.Input;

namespace Silverlight4.CommandBinding.Demo.CommandBase

    public class DelegateCommand : ICommand
   
        /// <summary> 
        /// Occurs when changes occur that affect whether the command should execute. 
        /// </summary> 
        public event EventHandler CanExecuteChanged;

        Func<object, bool> canExecute; 
        Action<object> executeAction; 
        bool canExecuteCache;

        /// <summary> 
        /// Initializes a new instance of the <see cref="DelegateCommand"/> class. 
        /// </summary> 
        /// <param name="executeAction">The execute action.</param> 
        /// <param name="canExecute">The can execute.</param> 
        public DelegateCommand(Action<object> executeAction, 
                               Func<object, bool> canExecute) 
       
            this.executeAction = executeAction; 
            this.canExecute = canExecute; 
        }

        #region ICommand Members
        /// <summary> 
        /// Defines the method that determines whether the command 
        /// can execute in its current state. 
        /// </summary> 
        /// <param name="parameter"> 
        /// Data used by the command. 
        /// If the command does not require data to be passed, 
        /// this object can be set to null. 
        /// </param> 
        /// <returns> 
        /// true if this command can be executed; otherwise, false. 
        /// </returns> 
        public bool CanExecute(object parameter) 
       
            bool tempCanExecute = canExecute(parameter);

            if (canExecuteCache != tempCanExecute) 
           
                canExecuteCache = tempCanExecute; 
                if (CanExecuteChanged != null) 
               
                    CanExecuteChanged(this, new EventArgs()); 
                
            }

            return canExecuteCache; 
        }

        /// <summary> 
        /// Defines the method to be called when the command is invoked. 
        /// </summary> 
        /// <param name="parameter"> 
        /// Data used by the command. 
        /// If the command does not require data to be passed, 
        /// this object can be set to null. 
        /// </param> 
        public void Execute(object parameter) 
       
            executeAction(parameter); 
       
        #endregion 
    }
}

Implementation of ViewModelBase

Let us now implement the ViewModelBase for our application. Though for this sample application you can directly use the ViewModel, but it is recommended to create a base class implementation by inheriting the INotifyPropertyChanged interface so that, if you are creating multiple ViewModel it will be easier to inherit the base class. Here is the code for that:

using System.ComponentModel;

namespace Silverlight4.CommandBinding.Demo.CommandBase

    public abstract class ViewModelBase : INotifyPropertyChanged 
   
        public event PropertyChangedEventHandler PropertyChanged; 
        /// <summary> 
        /// Called when [property changed]. 
        /// </summary> 
        /// <param name="propertyName">Name of the property.</param> 
        protected void OnPropertyChanged(string propertyName) 
       
            if (PropertyChanged != null) 
           
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
           
        
    }
}

Implementation of ViewModel

Now our all the base classes are ready to use. Hence, we can go further to create our first ViewModel. In this example we are going to load Customer informations, so we will name it as CustomerViewModel.

First of all we will create a new instance of DelegateCommand “LoadCustomersCommand” which is a ICommand type variable. It takes two parameters. First one is the Action which fires when the command executes and the second one is a Function pointer which returns whether the command can be executed. If it returns true, the command binded to the element will be enabled to do the operation and if it returns false, the command binded to the element will be disabled by default. Once it becomes true by any other operation, the UI thread automatically make the element enabled.

Here in the demo application when the command executes, we will fetch the customer information from the provider and store the data in the ObservableCollection called “CustomerCollection”. We used ObservableCollection because it inherits the INotifyPropertyChanged interface and causes the UI thread to update the UI automatically when the collection changed event occurs binded to the specific UI.

/// <summary>
/// Initializes a new instance of the <see cref="CustomerViewModel"/> class.
/// </summary>
public CustomerViewModel()

    LoadCustomersCommand = new DelegateCommand(LoadCustomers, CanLoadCustomers);
}

/// <summary>
/// Loads the customers.
/// </summary>
/// <param name="parameter">The parameter.</param>
private void LoadCustomers(object parameter)

    CustomerCollection = CustomerProvider.LoadCustomers();
}

/// <summary>
/// Determines whether this instance [can load customers] the specified parameter.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns>
///     <c>true</c> if this instance [can load customers] the specified parameter;
///     otherwise, <c>false</c>.
/// </returns>
private bool CanLoadCustomers(object parameter)

    return true;
}

Implementation of UI (XAML)

As of now, our back end code implmentation is ready and now we have to create our UI to show the customer information. First of all we will create the static instance of the viewmodel as a resource of the UserControl. We named it as “vmCustomer”. Now we will design our UI with a ListBox and a Button. Once we click on the button it should execute the command and load the data in the ListBox.

The ListBox should point it’s ItemSource to the CustomerCollection inside the ViewModel. The button will have the LoadCustomersCommand associated with it. If the canExecute method returns false, you will notice the button as disabled and when it returns true, it will become enabled.

Here is the full XAML implementation:

<UserControl x:Class="Silverlight4.CommandBinding.Demo.MainPage" 
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation 
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml 
    xmlns:d=http://schemas.microsoft.com/expression/blend/2008 
    xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
   
xmlns:local="clr-namespace:Silverlight4.CommandBinding.Demo.ViewModel" 
    Width="500" Height="300">

    <UserControl.Resources> 
        <local:CustomerViewModel x:Key="vmCustomer"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <Border CornerRadius="10,10,0,0" Background="Black" 
                Height="30" VerticalAlignment="Top" Margin="20,20,20,0">
            <TextBlock Text="Silverlight 4 Command Binding Demo" Foreground="White" 
                       FontWeight="Bold" Margin="5"/> 
        </Border> 
        <ListBox ItemsSource="{Binding CustomerCollection, Source={StaticResource vmCustomer}}" 
                 Margin="20,50,20,40"> 
            <ListBox.ItemTemplate> 
                <DataTemplate> 
                    <Grid> 
                        <Grid.ColumnDefinitions> 
                            <ColumnDefinition Width="150"/> 
                            <ColumnDefinition Width="150"/> 
                            <ColumnDefinition Width="*"/> 
                        </Grid.ColumnDefinitions> 
                        <TextBlock Text="{Binding Path=Name}" Width="100" Grid.Column="0"/> 
                        <TextBlock Text="{Binding Path=Address}" Width="200" Grid.Column="1"/> 
                        <TextBlock Text="{Binding Path=ContactNumber}" Width="100" Grid.Column="2"/> 
                    </Grid> 
                </DataTemplate> 
            </ListBox.ItemTemplate> 
        </ListBox> 
        <Button Command="{Binding LoadCustomersCommand, Source={StaticResource vmCustomer}}" 
                Content="Load Customers" Height="25" Margin="380,267,20,8" /> 
    </Grid>
</UserControl>

Now, you can run the application and press F5 to run it. Try it.

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight Hosting :: Using Dynamic Objects in Silverlight 4

clock July 15, 2010 06:32 by author Darwin

This article gives brief explanation about Silverlight 4. If you’re looking for Silverlight 4 hosting, you can get the professional hosting at ASPHostDirectory. Only with $ 3.99/month to get SL 4 hosting. What are you waiting for?

One of the cool new features in Silverlight 4 is the ability to data bind to indexed properties. This means that even if you don’t know at design time what properties you data object has you can still data bind to them.

The syntax is very similar to a normal data binding, only in this case you need to use the [key] syntax instead. For example in example below the FirstName is a regular property while the LastName below is an indexed property.

<StackPanel Name="LayoutRoot"> 
    <StackPanel Orientation="Horizontal" Margin="1"> 
        <TextBlock Text="FirstName" Width="150"></TextBlock> 
        <TextBox Text="{Binding FirstName, Mode=TwoWay}" Width="500"></TextBox> 
    </StackPanel> 
    <StackPanel Orientation="Horizontal" Margin="1"> 
        <TextBlock Text="LastName" Width="150"></TextBlock> 
        <TextBox Text="{Binding [LastName], Mode=TwoWay}" Width="500"></TextBox> 
    </StackPanel>
</StackPanel>

Creating the class to data bind to is simple. All you need to do is add a property with the following syntax:

public object this[string key] 
    { get; set; }

In this example we are using a Peron class with a regular FirstName property and all others are dong using indexed properties. The complete class, including INotifyPropertyChanged looks like this:

public class Person : INotifyPropertyChanged

    public Person() 
   
        PropertyChanged = (s, e) => { };

        FirstName = "Maurice"; 
        this["LastName"] = "de Beijer";
        this["BabyName"] = "Kai"; 
    }

    private Dictionary<string, object> _data = new Dictionary<string, object>(); 
    public object this[string key] 
   
        get 
       
            if (!_data.ContainsKey(key)) 
                _data[key] = null;

            return _data[key]; 
       
        set 
       
            _data[key] = value; 
            PropertyChanged(this, new PropertyChangedEventArgs("")); 
       
    }

    public IEnumerable<string> Keys 
    {
        get 
        {
            return _data.Keys; 
        }
    }

    private string _firstName; 
    public string FirstName
   
        get
       
            return _firstName;
       
        set 
       
            _firstName = value; 
            PropertyChanged(this, new PropertyChangedEventArgs("FirstName")); 
       
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

While not having to know the objects structure at design time is nice but in the XAML above we still hard coded the data bindings so that doesn’t buy us much yet. So fully utilize this we need to dynamically generate the UI as well. Fortunately that is quite easy to do with the following code:

void MainPage_Loaded(object sender, RoutedEventArgs e)

    var person = new Person(); 
    DataContext = person; 
    foreach (var item in person.Keys) 
   
        var lbl = new TextBlock(); 
        lbl.Text = item; 
        lbl.Width = 150;

        var txt = new TextBox(); 
        var binding = new Binding("[" + item + "]"); 
        binding.Mode = BindingMode.TwoWay; 
        txt.SetBinding(TextBox.TextProperty, binding); 
        txt.Width = 500;

        var line = new StackPanel(); 
        line.Orientation = Orientation.Horizontal; 
        line.Children.Add(lbl); 
        line.Children.Add(txt); 
        line.Margin = new Thickness(1); 
        LayoutRoot.Children.Add(line); 
    }
}

And now you can see the result. Try it!
Happy Programming!

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!



ASPHostDirectory Silverlight Hosting :: Virtualization in Silverlight 4 RC

clock July 10, 2010 10:20 by author Darwin

Introduction

There are several container controls in Silverlight . One of them is panel. Container control like for example StackPanel host another controls. Data presentation controls like ListBox inherits from ItemsControl. ItemsControl contains set of items to display and has ItemsSource property.ItemsControl is responsible for creating visuals for each item and placing them in a panel.

Main panel that holds items in ItemsControl is ItemsHost property. If we set this panel to be StackPanel for large datasets, ItemsContainerGenerator will generate containers that are off visible screen. Our ListBox will instantiate containers that aren't visible witch can take time and consume memory depending how large is dataset. Scrolling will also be much slower because we constantly computes the size and position of all of the containers.

Best solution for this problem is using UI virtualization. UI virtualization means that generation of items is deferred until we scroll items into visible zone. How it works? When we enable virtualization ItemHost property of ItemsControl is set to be VirtualizingStackPanel.


VirtualizingStackPanel calculates number of visible items and helps to create UI elements only for visible items. Scrolling on large datasets now will be much faster.


Another technique that can improve performance when working with large datasets is called Data virtualization. What does it mean? It means that we not load all data on client side rather only data that user can see at the moment. For example user in ListBox can see only 20 or 30 items. After that it must scroll. Here we can use technique called “deferred scrolling”. This technique you can see on Google Reader for example. We only loads 30 items from database and that user see. When user scroll down we load another 30 items from database. This technique can significantly improve performance of our application depend how large set of data we load on the client side.


Another example of Data virtualization is data pager control.We load 30 items in DataGrid control and when user click on link for next page then we load another 30 items.

2. UI virtualization

UI virtualization in Silverlight is accomplished by using VirtualizingStackPanel. As we have sad before VirtualizingStackPanel is that control that calculates the number of visible items to create UI elements only for visible items.

Virtualization in a StackPanel  occurs when the items control contained in the panel creates its own item containers. This happens when we use data binding. In case where item containers are created and added to the items control, a VirtualizingStackPanel offers no  advantage over a regular StackPanel.


VirtualizingStackPanel has two virtualization modes : standard and recycling. When we set standard mode containers are generated when items entering visible area. On the other hand when we set virtualization mode to be recycling we reuse containers that we have created before instead of generating new ones. Performance benefits of enabling recycling on VirtualizingStackPanel are significant especially for scrolling.

3. Data virtualization

Because off lack deferred scrolling on ScrollViewer it is not easy to implement “deferred scrolling”  in Silverlight 4 RC. In WPF we have this possibility to set deferred scrolling to true so we can make application that loads data when user releases scroll bar thumb.


But Silverlight has support for Data Virtualization using DataPager control and PagedCollectionView class. If we have DataGrid for example and we need to load large dataset with 500000 items in DataGrid maybe is better solution to implement paging on DataGrid using DataPager control.


We can use  a PagedCollectionView to provide grouping, sorting, filtering, and paging functionality for any collection that implements the IEnumerable interface. We just wrap IEnumerable collection with PageCollectionView and we have all this functionality. For example :


List<string> list = new List<string>();
//just provide to PagedCollectionView any IEnumerable datasource
PagedCollectionView p = new PagedCollectionView(list);
dataPager.Source = p;

PagedCollectionView has collection of GroupDescriptiors and SortDescriptiors that describes how items are group or sorted in view. It also contains methods for navigation between pages.

Code for grouping and sorting is simple. We just need to add new GroupDescription where we specify witch property in model will be used for grouping. For sorting code is similar. We just need to add new SortDescription and specify witch property will be used for sorting and in witch direction.

p.GroupDescriptions.Add(new PropertyGroupDescription("CustomerName"));
p.SortDescriptions.Add(new SortDescription("CustomerName",ListSortDirection.Ascending));

For filtering you need to define predicate that point to the method that will be used for filtering data.

p.Filter= new Predicate<object>(ExampleMethod);

4. Summary

As we have seen Silverlight 4 RC has very good support for UI virtualization. Using this technique we can improve performance of our Silverlight applications significantly.This give us tools to build high performance large business applications.

On the other hand Silverlight 4 RC does not support DeferredScrolling on ScrollViewer like WPF does. That makes difficult to implement “deferred scrolling” solutions in Silverlight. But probobly in later version of Silverlight this feature will be added because Silverlight and WPF eventually probably will become same platform. Silverlight also have very good support for paging through PagedCollectionView  that give us lot of functionality in simple way.

If you want to get professional Silverlight 4 RC hosting with low price, click here.

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory.com Silverlight Hosting :: Build a Simple Application with .Net RIA Services (Silverlight 3)

clock June 19, 2010 07:39 by author Darwin

This article describe Build a Simple Application with .Net RIA Services in Silverlight 3. If you’re looking for more information about Silverlight, you can visit ASPHostDirectory. We always ready to host your site. You can start from only $ 3.99/month to get this hosting. So, what are you waiting for?

Use a DomainDataSource to easily connect the data

Remove the code that retrieves the data from the server. Open Views\HomePage.xaml and comment out all the code in the Page_Loaded method.

Instead of loading the data manually, add a DomainDataSource control to the page. To do this, add a reference to System.Windows.Ria.Controls.dll, and add the Xml namespace that relates to its contents:

<navigation:Page x:Class="BankApp.HomePage"

  ...
  xmlns:ria="clr-namespace:System.Windows.Controls;
    assembly=System.Windows.Ria.Controls"

  Loaded="Page_Loaded"

  Title="HomePage Page">   ...


</navigation:Page>

Add the DomainDataSource to the page

<navigation:Page x:Class="BankApp.HomePage"
  ...

  <Grid x:Name="LayoutRoot" Background="White">

    <ria:DomainDataSource x:Name="customersDataSource"

                          LoadMethodName="GetCustomers"

                          AutoLoad="True"

                          LoadSize="5">

    </ria:DomainDataSource>

   ...

  </Grid>

</navigation:Page>

Reminder: After creating the DomainService in the server side, Visual Studio has generated a client side DomainContext that does all the magic of connecting to the server for us.

Assign the DomainContext to the DomainDataSource so it can use it to pull data from the server. To do that, add a local xml namespace:

<navigation:Page x:Class="BankApp.HomePage"

   ...

   xmlns:local="clr-namespace:BankApp.Web"

   Title="HomePage Page"> 
   ...


</navigation:Page>

And do the assignment:

<ria:DomainDataSource x:Name="customersDataSource"

                      LoadMethodName="LoadCustomers"

                      AutoLoad="True"

                      LoadSize="5">

  <ria:DomainDataSource.DomainContext>

    <local:BankDomainContext />

  </ria:DomainDataSource.DomainContext>

</ria:DomainDataSource>


The last thing we need to do is to bind the DataGrid to the DomainDataSource.

<data:DataGrid MinHeight="200"

              x:Name="dataGrid"

              ItemsSource="{Binding Data, ElementName=customersDataSource}">

</data:DataGrid>

Run the application, and see how the data is being loaded in chunks according to the LoadSize property of the DomainDataSource.

Add a DataPager Control to enable paging through the data. To do that, add a reference to System.Windows.Controls.Data.DataForm.dll the following xml namespace:

xmlns:dataControls=
    "clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm”

Add the DataPager control and bind it to the DomainDataSource:

<data:DataGrid MinHeight="200" ...>

</data:DataGrid>

<dataControls:DataPager PageSize="3"

              Source="{Binding Data, ElementName=customersDataSource}" />

Data Grouping

Add Grouping support to the DataGrid. Add the following xml namespace:

xmlns:riaData="clr-namespace:System.Windows.Data;assembly=System.Windows.Ria.Controls"

Then, add a group descriptor to group the results by the property City.

<ria:DomainDataSource ...>
  <ria:DomainDataSource.GroupDescriptors>
    <riaData:GroupDescriptor PropertyPath="City" />
  </ria:DomainDataSource.GroupDescriptors>
</ria:DomainDataSource>

Data Sorting

To add sorting support, add a SortDescriptor:

<ria:DomainDataSource ...>

  <ria:DomainDataSource.SortDescriptors>

    <riaData:SortDescriptor PropertyPath="CustomerID"

                            Direction="Descending" />

  </ria:DomainDataSource.SortDescriptors>

</ria:DomainDataSource>

Rich Data Filtering

Add a dynamic filtering support based on a selected value of a CheckBox. Add a Checkbox above the DataGrid.

<CheckBox x:Name="chkBusiness"

          Content="Business Customer ?" />

<data:DataGrid x:Name="dataGrid" ...> </data:DataGrid>

Add a FilterDescriptor that filters data according to the IsBusiness property of each item. Bind the FilterDescriptor  to the IsChecked property of the above checkbox.

<ria:DomainDataSource x:Name="customersDataSource" ... >

  ...

  <ria:DomainDataSource.FilterDescriptors>

    <riaData:FilterDescriptorCollection>

      <riaData:FilterDescriptor PropertyPath="IsBusiness"

                                Operator="IsEqualTo">

        <riaData:ControlParameter ControlName="chkBusiness"

                                  PropertyName="IsChecked"

                                  RefreshEventName="Click" />

      </riaData:FilterDescriptor>

    </riaData:FilterDescriptorCollection>

  </ria:DomainDataSource.FilterDescriptors>

</ria:DomainDataSource>

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!

 



ASPHostDirectory Silverlight Hosting :: How to Command Control

clock June 15, 2010 07:17 by author Darwin

In this article we will take this proof of concept and demonstrate how through the use of commanding and binding we can virtually eliminate all code behind and implement to a strong MVVM architectural pattern. For more information about silverlight 4 hosting, visit http://www.asphostdirectory. At ASPHostDirectory, we guarantee you will get the best price at an affordable price. Only $ 3.99/month, you will get Silverlight 4 hosting.

Getting Started

We think few would argue with the value of a strong separation of concerns within the design of an application.  Over the last year the MVVM pattern has gained popularity in the Silverlight development community.  One of the challenges that developers faced in previous versions of the framework was the lack of commanding support in Silverlight.  Without commanding many developers had to write there own attached properties, or worse  yet, resort to event handling in their code behind, just to deal with responding to a button being clicked.  Today both the button and HyperlinkButton support commanding.

Model-View-ViewModel

Even though our sample application will only be a single page, we will still implement the MVVM pattern to eliminate any code in code behind of our MainPage.xaml.  MVVM requires that for every View we have a corresponding ModelView (MV) class.  Our View will set its DataContext equal to this class and bind all of the views data through public properties.

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

using System.ComponentModel;

namespace VideoCaptureExample
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
    . . . . .
    }
}

In our mainPage.xaml we will initialize our ViewModel class and set our LayoutRoot DataContext to this resource.  If our ViewModel required additional context or possibly aservices be injected into its constructor we would opts to use a ViewModel locator that has been stored as a ApplicationResource.

<UserControl x:Class="VideoCaptureExample.MainPage"
    . . . .
    d:DesignHeight="360" d:DesignWidth="610">
    <UserControl.Resources>
        <local:MainPageViewModel x:Key="MainViewModel"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White"         DataContext="{Binding Source={StaticResource MainViewModel}}">
    . . . . . .
    </Grid>
</UserControl>

SaveCommand

One of the great advantages to commanding is encapsulation.  When an application has a function like “Save” its very likely that more then one action can trigger this behavior.  In our example we intend to allow the save to be triggered from a button, right click context menu as well a something being dragged to a specific location on the screen.  Creating a command has two parts.  First we need to write a class that implements the ICommand interface and second expose it through our view model..  The following is the general format of such a class.  When we create commands in Silverlight we like to inject our ViewModel in the event we need to check the state of our view before executing the command.

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Input;

namespace VideoCaptureExample
{
    public class SaveCommand : ICommand
    {
        private MainPageViewModel _viewModel;

        public SaveCommand(MainPageViewModel viewModel)
        {
            _viewModel = viewModel;
        }

        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter)
        {
            return (_viewModel.SelectedCapture != null) ? true : false;
        }

        public void Execute(object parameter)
        {
            Capture capture = parameter as Capture;
            if (capture != null)
            {
             . . . . .
            }
        }

        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }

        public void RaiseCanExecuteChanged()
        {
            OnCanExecuteChanged(EventArgs.Empty);
        }
    }
}

In the above snippet there are three requirements when implementing the ICommand interface.  First we need to define a function called CanExecute.  This will be called to determine if a buttons enabled state is set to true or false.  What is great about CanExecute is that it eliminates custom business logic to determine if a command can be fired.  The second is an Execute method that is called when the user clicks a button referenced by the command.  All of our “Save” logic will be placed inside of this method.  A argument is passed to this method that allows data to be injected into the call. Setting CommandParameter on a Button will define what gets passed during the execute. The last requirement is the CanExecuteChanged event.  We can fire this event anytime we want buttons that are bound to this command to re-evaluate there enabled state.

To implement this command in our ViewModel, we need to expose the class as a property.

private SaveCommand _saveCommand;
public SaveCommand Save
{
    get
    {
        if (_saveCommand == null)
            _saveCommand = new SaveCommand(this);
        return _saveCommand;
    }
}


Once exposed, we can reference the SaveCommand through simple binding applied to the Button’s Command property and CommandParameter.  Now each time that a user clicks the “Save” button our command will be fired.

 

<Button x:Name="saveBtn" Content="Save"
    Width="70" Height="22" Margin="10,0,0,0"
    HorizontalAlignment="Right" VerticalAlignment="Center"
    Command="{Binding Save}"
    CommandParameter="{Binding ElementName=listImages, Path=SelectedItem}"/>


DelegateCommand

More often than not our command is not needed outside of the context of a single view.  If this is the case, we can delegate the implementation of the CanExecute and Execute to the ViewModel.  Lets say for example you have a command like “StartCapture” that is only appropriate for a single View.  In this scenario its a lot easier to have the business logic directly in the ViewModel than in a separate class. 

Using the same ICommand interface, we can create a reusable class that delegates both of these methods.  The following is the most popular approach.

using System;
using System.Windows.Input;

namespace VideoCaptureExample
{
    public class DelegateCommand : ICommand
    {
        private Predicate<object> _canExecute;
        private Action<object> _method;
        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<object> method)
            : this(method, null)
        {
        }

        public DelegateCommand(Action<object> method, Predicate<object> canExecute)
        {
            _method = method;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }

            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _method.Invoke(parameter);
        }

        protected virtual void OnCanExecuteChanged(EventArgs e)
        {
            var canExecuteChanged = CanExecuteChanged;

            if (canExecuteChanged != null)
                canExecuteChanged(this, e);
        }

        public void RaiseCanExecuteChanged()
        {
            OnCanExecuteChanged(EventArgs.Empty);
        }
    }
}

To implement this DelegateCommand class we do the following in our ViewModel.  Notice how our constructor gets passed two delegates, one for  CanExecute and one for Execute.  Calling this command from XAML is identical to our SaveCommand class.

private DelegateCommand _captureCommand;
public DelegateCommand Capture
{
    get
    {
        if (_captureCommand == null)
            _captureCommand = new DelegateCommand(OnCapture, CaptureCanExecute);

        return _captureCommand;
    }
}
. . . .
private void OnCapture(object parameter)
{
    UIElement element = parameter as UIElement;
    if (this.CaptureSource != null)
    {
    . . . .
    }
}
. . . .
private bool CaptureCanExecute(object parameter)
{
    return (_isCapturingVideo) ? true : false;
}

Using Binding to Avoid Commanding

One of the things that we think a lot developers forget is that TwoWay binding can be a great way to avoid having to create a command or event handler to respond to a user click.  Commands are great, but if you don’t need them don’t use them. 

If we examine the code below, you will see a bunch of bindings.  First, our ListBox.ItemSource is bound to an ObservableCollection<Effect> of effects.  This allows us to add effects to the ListBox by simply updating our collection.  Second, our ListBox.IsEnabled is bound to a property in our ViewModel.  Notice the use of TargetNullValue and FallbackValue.  These new properties on the binding extension method allow us to override what gets used in the event the property we are binding to is NULL value.  In this example we have a ViewModel property that stores a reference to a capture that has been selected in the ListBox of captures.  If nothing is selected, the property is null.  Since a null is not a boolean, we use TargetNullValue and FallbackValue to ensure we have a true/false response.

<ListBox Height="50" Name="listEffects" Width="Auto"  HorizontalAlignment="Stretch"
     ItemsSource="{Binding Path=Effects}"
     IsEnabled="{Binding TargetNullValue=true, FallbackValue=false, Path=SelectedCapture}"
     ItemTemplate="{StaticResource EffectItemTemplate}"
     ItemsPanel="{StaticResource WrapItemPanel}"
     ScrollViewer.HorizontalScrollBarVisibility="Disabled"
     ScrollViewer.VerticalScrollBarVisibility="Auto" >
</ListBox>

Another place we use binding is in the DataTemplate of this list box.  Here we will bind both the Effect of the rectangle and its Fill.  Our Effect will get bound to the ShaderEffect property of this item being rendered , while the Fill will navigate back to the main DataContext and bind to a property called Brush located within our  MainPageViewModel.  This property might be a SolidBrush, VideoBrush or even an ImageBrush of an existing capture.

<DataTemplate x:Key="EffectItemTemplate">
    <Border BorderThickness="1" BorderBrush="Black" CornerRadius="2"
        HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,0,3,0">
        <Rectangle Width="48" Height="36" Stretch="Fill"
            Effect="{Binding ShaderEffect}"
            Fill="{Binding Source={StaticResource MainViewModel}, Path=Brush}" />
    </Border>
</DataTemplate>

So that ensures that our list of effects looks correct, but how exactly does our rectangle displaying our live webcam video with the correct ShaderEffect applied? 

Again we lean on Binding to avoid any procedural code.  using ElementName binding we bind the styled buttons Effect property to the SelectedItem of our ListBox of effects.  Now each time a user clicks on an item in our list of effects the rectangles will change immediately.

<Button Name="rectVideo"
    Style="{StaticResource RectangleButtonStyle}"
    Width="320" Height="240"
    Effect="{Binding ElementName=listEffects, Path=SelectedItem.ShaderEffect, Mode=TwoWay}"
    Command="{Binding Capture}"
    CommandParameter="{Binding ElementName=rectVideo}"/>

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!