Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Monday, 4 July 2011

Passing Objects between ASP.NET and Silverlight Controls.

This is Part –2 of my previous post “Passing parameters between Silverlight and ASP.NET – Part 1”

In my previous post I have showed how to pass parameters between Silverlight and ASP.NET using Query Strings, Init Parameters and HtmlPage.Document. These techniques are good as long as you are dealing with small amount of data and have certain limitation. There are some scenario where we have to pass large number of data from asp.net to Silverlight and back from Silverlight to asp.net and our architecture design does not permit us to connect to Database directly from Silverlight component.

Today I am going to show you how we can use Object Serialization to achieve the same. but remember using this also poses some serious performance issues, so use this only when you really need this scenario. Internally this technique uses the HtmpPage.Document method only.

Just to give you a fair idea how I can do this I have created a sample Silverlight Application using Visual Studio Web Developer 2010, and added a class file called Employee.cs. This file just holds few entities of Employee and EmployeeDetails. Just to give you a feel of actual scenario I have created the Employee and EmployeeAddress as a separate class and written a method to return the sample data from this classes.

EmployeeAddress Class

   1: public class EmployeeAddress



   2: {



   3:     [XmlAttribute]



   4:     public string Address { get; set; }



   5:     



   6:     [XmlAttribute]



   7:     public string City { get; set; }



   8:  



   9:     [XmlAttribute]



  10:     public string PinCode { get; set; }



  11: }




Employee Class





   1: [XmlRoot("Employee")]



   2: public class Employee



   3: {



   4:     [XmlElement]



   5:     public string EmployeeName { get; set; }



   6:  



   7:     [XmlElement]



   8:     public EmployeeAddress EmployeeAddresses { get; set; }



   9:  



  10:     [XmlElement]



  11:     public int Age { get; set; }



  12:  



  13:     public List<Employee> GetEmployeeData()



  14:     { 



  15:         List<Employee> employees = new List<Employee>();



  16:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "V.B.Layout", City = "Bangalore", PinCode = "560076" }, Age = 33, EmployeeName = "Brij Mohan" });



  17:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Beauty Layout", City = "Delhi", PinCode = "111111" }, Age = 33, EmployeeName = "Arun Dayal Udai" });



  18:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Mumbai Filmcity Layout", City = "Mumbai", PinCode = "444444" }, Age = 33, EmployeeName = "Sarosh Kumar" });



  19:         employees.Add(new Employee { EmployeeAddresses = new EmployeeAddress { Address = "Dimna Road", City = "Jamshedpur", PinCode = "831018" }, Age = 33, EmployeeName = "Bharti Priyadarshini" });



  20:  



  21:         return employees;



  22:     }



  23:  



  24:     public string GetSerializedEmployeeData()



  25:     {



  26:         MemoryStream mem = new MemoryStream();



  27:         System.Xml.Serialization.XmlSerializer xs = new XmlSerializer(typeof(List<Employee>));



  28:         mem.Seek(0, SeekOrigin.Begin);



  29:         xs.Serialize(mem, GetEmployeeData());



  30:         byte[] data = mem.GetBuffer();



  31:         string xmlString = Encoding.UTF8.GetString(data, 0, data.Length);



  32:         return xmlString;



  33:     }



  34:  



  35:     public List<Employee> GetDesializedEmployeeObject(string xmlData)



  36:     {



  37:         StringReader sr = new StringReader(xmlData);



  38:         XmlSerializer xs = new XmlSerializer(typeof(List<Employee>));



  39:         object employees = xs.Deserialize(sr);



  40:  



  41:         return (List<Employee>)employees;



  42:     }



  43: }






In the employee class above I have also written few helper methods to Serialize and de-serialize the objects, using XMLSerializer.



Now coming back to the code behind of my default.aspx page, here I am only trying to simulate the actual scenario. On Page load I am getting my dummy data and putting this data into a Hidden Filed. In actual environment you may get this data from Database and then putting this into some hidden field.





   1: protected void Page_Load(object sender, EventArgs e)



   2: {



   3:     Employee emp = new Employee();



   4:     txtValue.Text = HttpUtility.HtmlEncode(emp.GetSerializedEmployeeData());



   5: }






You may notice that I have used HttpUtility.HtmlEncode, this is very important because we are passing XML Data during Postbacks, failing to use this may give you the following error, which you may not like to see.



Server Error in '/' Application.



A potentially dangerous Request.Form value was detected from the client (txtValue="<?xml version="1.0"?...").



image



Ok now my asp.net is ready to send data to Silverlight Control, its now Silverlight turn to get this data and parse it into Silverlight recognized format which Silverlight controls will understand.



First I am adding the same employee class to Silverlight project for de serializing the received serialized data from ASP.NET. To avoid duplication of data, I am adding the same class file to my Silverlight Project using Add as Link option from file dialogue.



First right click you Silverlight Project and Select Add –> Existing Item



image



Now, locate you Employee.cs file from the ASP.NET website project, and select Add As Link option from Add. This wil basically create a shortcut to Employee.cs from your ASP.NET Application to your Silverlight Project, basically both are same copy so before make any ASP.NET only specific changes to this file make sure this should compile in your Silverlight application too, or  Vice Versa.



image









Now once the shortcut of the Employee is created in your Silverlight Application, we can use this class just like the normal class file. Now coming back to my Silverlight Application open the MainPage.xaml, open the XAML View. To display the data I have added a DataGrid and ListView of the Address Item on the XAML Page.





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



   2:         <sdk:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" ItemsSource="{Binding}" Name="employeeDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="361" SelectionChanged="employeeDataGrid_SelectionChanged">



   3:         <sdk:DataGrid.Columns>



   4:             <sdk:DataGridTextColumn x:Name="ageColumn" Binding="{Binding Path=Age}" Header="Age" Width="SizeToHeader" />



   5:             <sdk:DataGridTextColumn x:Name="employeeNameColumn" Binding="{Binding Path=EmployeeName}" Header="Employee Name" Width="SizeToHeader" />



   6:         </sdk:DataGrid.Columns>



   7:     </sdk:DataGrid>



   8:     <Grid x:Name="employeeDetailList" HorizontalAlignment="Left" Margin="454,19,0,0" VerticalAlignment="Top">



   9:         <Grid.ColumnDefinitions>



  10:             <ColumnDefinition Width="Auto" />



  11:             <ColumnDefinition Width="Auto" />



  12:         </Grid.ColumnDefinitions>



  13:         <Grid.RowDefinitions>



  14:             <RowDefinition Height="Auto" />



  15:             <RowDefinition Height="Auto" />



  16:             <RowDefinition Height="Auto" />



  17:         </Grid.RowDefinitions>



  18:         <sdk:Label Content="Address:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />



  19:         <TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="addressTextBox" Text="{Binding Path=EmployeeAddresses.Address, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />



  20:         <sdk:Label Content="City:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />



  21:         <TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="cityTextBox" Text="{Binding Path=EmployeeAddresses.City, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />



  22:         <sdk:Label Content="Pin Code:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />



  23:         <TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="3" Name="pinCodeTextBox" Text="{Binding Path=EmployeeAddresses.PinCode, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />



  24:     </Grid>



  25: </Grid>






In the code behind of MainPage.xaml I have just added few lines of code to load and bind the Data from the ASP.NET page hidden field where we have kept our employee Serialized data.





   1: public partial class MainPage : UserControl



   2: {



   3:     List<Web.Employee> employees = null;



   4:     public MainPage()



   5:     {



   6:         InitializeComponent();



   7:     }



   8:  



   9:     private void UserControl_Loaded(object sender, RoutedEventArgs e)



  10:     {



  11:         if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))



  12:         {



  13:             var result = HttpUtility.HtmlDecode(HtmlPage.Document.GetElementById("txtValue").GetProperty("value").ToString());



  14:  



  15:             SLAppCommunication.Web.Employee employee = new Web.Employee();



  16:             employees = employee.GetDesializedEmployeeObject(result.ToString());



  17:             employeeDataGrid.ItemsSource = employees;



  18:         }



  19:  



  20:     }



  21:  



  22:     private void employeeDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)



  23:     {



  24:         Web.Employee emp = ((DataGrid)sender).SelectedItem as Web.Employee;



  25:         employeeDetailList.DataContext = emp;



  26:     }



  27: }






Here after the Load event of Silverlight Control I am reading the Data from the HTML Page textbox and then using HttpUtility.HtmlDecode to decode the Encoded string from the textbox. This will give me the actual Serialized String. Now since we want our data into an Object format so we are actually doing the reverse of what we already did in ASP.NET application. We are going to pass this XML Data into our function  GetDesializedEmployeeObject this function will basically return me the List<Employee> which we can directly bind it to our DataGrid control. Now lets run the application.



image



Ok so this gives me all the data which we have created in our ASP.NET application, Just I have added a employeeDataGrid_SelectionChanged event so that when we select any rows in our Grid it displays the detailed information of the same. And yes using this method we can avoid any calls to DB directly from Silverlight component. Here Silverlight is just a component plugged in into our ASP.NET page container.



Hope you liked this Post, to get the proper formatted and running example to the source code, you can download from here.



Source Code.

Share:

Monday, 23 May 2011

Tuesday, 5 April 2011

Silverlight 5 Roadmap Announced



I know it's too late to publish this post, by this time most of you guys must be already aware of this.



But anyways for those who are not much aware of the updates you can refer to this. 

Beta release of Silverlight 5 is expected for spring 2011, and the final release for the end of 2011.

I won't re-post the list of planned features here. You can get all the details on Scott Guthrie's blog.


Share:

Wednesday, 31 March 2010

List of Software and Tips, to Prepare your new System (Only for MS Silverlight Dev)

I was planning to format my system and upgrade to latest OS and Software’s. I am left out with only 15GB HDD Space, don’t know where other 135 GB Vanished. It usually happens in long term with registry size and other unwanted files we keep accumulating.

Particularly I was not searching for anything in Internet as I know what exactly I need from my new setups, but accidently I got a nice link which gave me an extensive links and lists of very good software’s which I can install in my latest setups. I thought to save this list in my bookmarks as well as share with you guys too.

http://timheuer.com/blog/archive/2010/03/30/repaving-my-machine-my-baseline-dev-workstation-tools.aspx

Interesting thing is I was never expecting like in this blog I can also get something related to hardware related stuffs, Specially this is one of my favorite blog where I usually look out for my Silverlight Codes and other programming related stuffs.

Hope this helps !!!

Share:

Saturday, 1 August 2009

Silverlight 3 DataGrid Columns Grouping using PagedCollectionView

In this post I am showing how to implement Column Grouping in SIlverlight 3 DataGrid,

Before starting make sure you have SIlverlight3_Tools installed in your system, not SIlverlight 3 Beta, as there are lost of changes in Grouping of Columns from SIlverlight 3 Beta to Silverlight 3 RTW.

image

You can follow the few simple steps below to get the Grouping for your Silverlight 3 DataGrid.

Else you can also download the code demonstrated from here.

1. Create an Silverlight Application using you Visual Studio 2008 IDE, and add a hosting web application in the project.

2. Once you have done with this, you will get an two projects in your Solution, you need to code only in your silverlight project.

3. Now add a C# class file called Person.cs in your Silverlight Project. This class is used to provide some sample data to Silverlight DataGrid, you can change this to your other datasources like SQL, XML, etc.

I have added the following lines of code in Person.cs

   1: public class Person



   2:     {



   3:         public string FirstName { get; set; }



   4:         public string LastName { get; set; }



   5:         public string City { get; set; }



   6:         public string Country { get; set; }



   7:         public int Age { get; set; }



   8:  



   9:         public List<Person> GetPersons()



  10:         {



  11:             List<Person> persons = new List<Person>



  12:             {



  13:                 new Person



  14:                 { 



  15:                     Age=32, 



  16:                     City="Bangalore", 



  17:                     Country="India", 



  18:                     FirstName="Brij", 



  19:                     LastName="Mohan"



  20:                 },



  21:                 new Person



  22:                 { 



  23:                     Age=32, 



  24:                     City="Bangalore", 



  25:                     Country="India", 



  26:                     FirstName="Arun", 



  27:                     LastName="Dayal"



  28:                 },



  29:                 new Person



  30:                 { 



  31:                     Age=38, 



  32:                     City="Bangalore", 



  33:                     Country="India", 



  34:                     FirstName="Dave", 



  35:                     LastName="Marchant"



  36:                 },



  37:                 new Person



  38:                 { 



  39:                     Age=38,



  40:                     City="Northampton",



  41:                     Country="United Kingdom", 



  42:                     FirstName="Henryk", 



  43:                     LastName="S"



  44:                 },



  45:                 new Person



  46:                 { 



  47:                     Age=40, 



  48:                     City="Northampton", 



  49:                     Country="United Kingdom", 



  50:                     FirstName="Alton", 



  51:                     LastName="B"



  52:                 },



  53:                 new Person



  54:                 { 



  55:                     Age=28, 



  56:                     City="Birmingham",



  57:                     Country="United Kingdom",



  58:                     FirstName="Anup", 



  59:                     LastName="J"



  60:                 },



  61:                 new Person



  62:                 { 



  63:                     Age=27,



  64:                     City="Jamshedpur",



  65:                     Country="India", 



  66:                     FirstName="Sunita", 



  67:                     LastName="Mohan"



  68:                 },



  69:                 new Person



  70:                 { 



  71:                     Age=2, 



  72:                     City="Bangalore", 



  73:                     Country="India", 



  74:                     FirstName="Shristi", 



  75:                     LastName="Dayal"



  76:                 }



  77:             };



  78:  



  79:             return persons;



  80:         }



  81:     }





4. Now since my data is ready, I will add the DataGrid control in my XAML page, to make the presentation more attractive, I have added few more lines of code.




5. I have also added a ComboBox Control to Select the Grouping Columns name.



My XAML code will look something like this below.







   1: <UserControl 



   2:     xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  



   3:     x:Class="Silverlight3DataGrid.MainPage"



   4:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 



   5:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"



   6:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 



   7:              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 



   8:     mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">



   9:     <Grid x:Name="LayoutRoot">



  10:         <Grid.RowDefinitions>



  11:             <RowDefinition Height="0.154*"/>



  12:             <RowDefinition Height="0.483*"/>



  13:             <RowDefinition Height="0.362*"/>



  14:         </Grid.RowDefinitions>



  15:  



  16:         <StackPanel Orientation="Horizontal">



  17:             <TextBlock Text="Select Sort Criteria" 



  18:                        VerticalAlignment="Center" />



  19:  



  20:             <TextBlock Text="    " />



  21:             



  22:             <ComboBox Grid.Row="0" 



  23:                       HorizontalAlignment="Left" 



  24:                       Width="200" 



  25:                       Height="30" x:Name="SortCombo" 



  26:                       SelectionChanged="SortCombo_SelectionChanged">



  27:                 



  28:                 <ComboBoxItem Content="Country" ></ComboBoxItem>



  29:                 <ComboBoxItem Content="City" ></ComboBoxItem>



  30:                 <ComboBoxItem Content="Age" ></ComboBoxItem>



  31:             </ComboBox>



  32:         </StackPanel>



  33:         



  34:         <data:DataGrid x:Name="PersonGrid" Grid.Row="1"></data:DataGrid>



  35:  



  36:     </Grid>



  37: </UserControl>





6. Now as my Data and Presentation is ready, its time for me to write some lines of code to Retrieve my sample data, group them into columns and then Bind it to the Grid.




Please find below the rest of the Code which demonstrates how I have Grouped the Columns using PagedCollectionView and PropertyGroupDescription.





   1: public partial class MainPage : UserControl



   2:     {



   3:         PagedCollectionView collection;



   4:  



   5:         public MainPage()



   6:         {



   7:             InitializeComponent();



   8:             BindGrid();



   9:         }



  10:  



  11:         private void BindGrid()



  12:         {



  13:             Person person = new Person();



  14:             PersonGrid.ItemsSource = null;



  15:             List<Person> persons = person.GetPersons();



  16:             collection = new PagedCollectionView(persons);



  17:             collection.GroupDescriptions.Add(new 



  18:                 PropertyGroupDescription("Country"));



  19:  



  20:             PersonGrid.ItemsSource = collection;



  21:         }



  22:  



  23:         private void SortCombo_SelectionChanged(object sender, 



  24:             SelectionChangedEventArgs e)



  25:         {



  26:             ComboBoxItem person = SortCombo.SelectedItem as ComboBoxItem;



  27:             collection.GroupDescriptions.Clear();



  28:             collection.GroupDescriptions.Add(new 



  29:                 PropertyGroupDescription(person.Content.ToString()));



  30:  



  31:             PersonGrid.ItemsSource = null;



  32:             PersonGrid.ItemsSource = collection;



  33:         }



  34:     }







Yes its that simple, and its done. I know I have not given much description here, because nothing much to explain here. In the code above I am loading the Grid with my sample data coming from my Person class and default grouping the Person with Country.




Later on SortCombo_SelectionChanged, I am dynamically fetching the Selected column names from the ComboBox and Sorting on that.



Once you will run this application the screen will look something like this as given below.





Grouped by Country




image




Grouped by City




 image 




 Grouped by Age



image



 



You can group according to your requirement, like Grouping Active and Deleted items, etc.



 




You can also download the sample code from here.





I know the code here is not very well formatted, you can also refer the following location for the more better formatted version.


Silverlight 3 DataGrid Columns Grouping using PagedCollectionView



 



Cheers



~Brij

Share: