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

Friday, May 3, 2013

Creating a smoke using Particle System in Silverlight

Here’s what we’re trying to achieve: demo 

One of a fellow programmer came up with a question of “How do you create Smoke effect using Silverlight?” Well there may be plenty of code, third-party tools and plug-ins strewn over the internet for this, but out of a professional curiosity I got into the business of creating one out of my own hands.

The whole concept of creating smoke (without fire ;) ) can be done through what they call as Particle System. It’s a technique where in you employ very small graphical objects in large numbers to simulate effects like say Smoke, Fire, Snow, Dust, etc…

We need the smoke to be moving freely, so a canvas would be a best bet for the layout.
<Canvas x:Name="myCanvas" Background="White">
</Canvas>

From this point on the rest of the Smoke effect would be programmed in code behind file (C-Sharp in my case)

Let’s think a minute about smoke, shall we? Smoke starts at a point, very concentrated (Generation Point). According to the complex laws of physics, it simply rises up becoming dilute all the way. Finally blending well with the air where it seems to disappear (Vanishing Point).


Understanding the dynamics of smoke

Our approach would be to consider smoke as made up of small particles, which would originate at the Generation Point. These particles as time passes would simply rise up, becoming transparent by smaller percentages as it goes and finally becoming invisible at the Vanishing Point.

These particles are going to be ellipses. Let’s have a method which does just that.

public static Ellipse createEllipse()
{
Ellipse objEllipse = new Ellipse();
//Smaller sized particles
objEllipse.Width = 1;
objEllipse.Height = 1;

//Giving the particles a Smokey look
RadialGradientBrush rgbObj = new RadialGradientBrush();

GradientStop gsObj1 = new GradientStop();
gsObj1.Color = Colors.Transparent;
gsObj1.Offset = 2;
GradientStop gsObj2 = new GradientStop();
gsObj2.Color = Colors.DarkGray;
gsObj2.Offset = 0.5;
GradientStop gsObj3 = new GradientStop();
gsObj3.Color = Colors.Black;
gsObj3.Offset = 0.001;

rgbObj.GradientStops.Add(gsObj1);
rgbObj.GradientStops.Add(gsObj2);
rgbObj.GradientStops.Add(gsObj3);

objEllipse.Fill = rgbObj;

//Set the position of the ellipses to the Generation Point
Canvas.SetTop(objEllipse, 300);
Canvas.SetLeft(objEllipse, 150);
return objEllipse;
}

While the Silverlight application initializes, we’d simply call the following line to add a new smoke particle:
myCanvas.Children.Add(createEllipse());
Well, this is just one particle. By every tick of the clock, new particles should be generated to give the effect of the smoke billowing. This calls for a DispatcherTimer instance which would give me an event for say every 2 millisecond.
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = new TimeSpan(2);
timer.Tick += timer_Tick;
timer.Start();
At every tick, we need to be doing a set of tasks based on a few decisions.

Firstly, we cannot afford to overload the memory/screen with infinite number of particles. When a smoke particle simply disappears beyond the vanishing point, we can move them down to the generation point and reuse them. For this purpose, let’s have a limit of 1000 particles that can be freshly generated. If the screen has less than 1000 of them, we can go ahead and generate a new one.
if (myCanvas.Children.Count < 1000){
generateFireParticles();
}
Secondly, at every instant – *all* the smoke particles should perform the following tasks:
  • Rise up
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
  • Grow and become lighter in visibility
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
  • And take a wavy path up. Smoke particles take a simply chaotic path up, they just don’t go up in a straight line.
Random randObj = new Random(10);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));
Thirdly, Move every vanished particle back to its original point.
if (item.Opacity < 0.0001){
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, 150);
Canvas.SetLeft(item, 300);
}
So, considering all above, my timer tick event would look like this:
void timer_Tick(object sender, EventArgs e)
{
if (myCanvas.Children.Count < 1000)
{
generateFireParticles();
}
foreach (Ellipse item in myCanvas.Children)
{
if (item.Opacity < 0.0001)
{
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, Y);
Canvas.SetLeft(item, X);
}
else
{
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));
}
}
}
Thus, was how we can generate a smoke effect in Silverlight using Particle System. With a minor change in the color and nature of the ellipse, you can create Fire or other similiar effects.

Thursday, May 2, 2013

Export Silverlight DataGrid to Excel XML/CSV

There are several reasons for the end user to export data from an application into an Excel compatible format (mostly for further analysis/usage or data). This article explains how to include data export capability to Silverlight DataGrid.

I am working on migrating some ASP.NET code to a Silverlight application. One of the features that I felt lacking in Silverlight is the ability to export the contents of a DataGrid to the end user. To address this issue, I created an extension for DataGrid control. When the attached file (DataGridExtensions.cs) is included in a project, the "Export" extension is automatically made available to all the DataGrid controls used in the project.

This module exposes two methods:
  • Export (this DataGrid dg) - extends the DataGrid control by providing the export functionality.
  • ExportDataGrid (DataGrid dGrid) - this method is internally called by the "Export" DataGrid extension. However, this method can be directly called too.
public static void Export(this DataGrid dg)
{
    ExportDataGrid(dg);
}
public static void ExportDataGrid(DataGrid dGrid)
{
    SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "csv", 
        Filter = "CSV Files (*.csv)|*.csv|Excel XML (*.xml)|*.xml|All files (*.*)|*.*", 
        FilterIndex = 1 };
    if (objSFD.ShowDialog() == true)
    {
        string strFormat = 
          objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
        StringBuilder strBuilder = new StringBuilder();
        if (dGrid.ItemsSource == null) return;
        List<string> lstFields = new List<string>();
        if (dGrid.HeadersVisibility == DataGridHeadersVisibility.Column || 
            dGrid.HeadersVisibility == DataGridHeadersVisibility.All)
        {
            foreach (DataGridColumn dgcol in dGrid.Columns)
                lstFields.Add(FormatField(dgcol.Header.ToString(), strFormat));
            BuildStringOfRow(strBuilder, lstFields, strFormat);
        }
        foreach (object data in dGrid.ItemsSource)
        {
            lstFields.Clear();
            foreach (DataGridColumn col in dGrid.Columns)
            {
                string strValue = "";                    
                Binding objBinding = null;
                if (col is DataGridBoundColumn)
                    objBinding = (col as DataGridBoundColumn).Binding;
                if (col is DataGridTemplateColumn)
                {
                    //This is a template column...
                    //    let us see the underlying dependency object
                    DependencyObject objDO = 
                      (col as DataGridTemplateColumn).CellTemplate.LoadContent();
                    FrameworkElement oFE = (FrameworkElement)objDO;
                    FieldInfo oFI = oFE.GetType().GetField("TextProperty");
                    if (oFI != null)
                    {
                        if (oFI.GetValue(null) != null)
                        {
                            if (oFE.GetBindingExpression(
                                   (DependencyProperty)oFI.GetValue(null)) != null)
                                objBinding = 
                                  oFE.GetBindingExpression(
                                  (DependencyProperty)oFI.GetValue(null)).ParentBinding;
                        }
                    }
                }
                if (objBinding != null)
                {
                    if (objBinding.Path.Path != "")
                    {
                        PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);
                        if (pi != null) strValue = pi.GetValue(data, null).ToString();
                    }
                    if (objBinding.Converter != null)
                    {
                        if (strValue != "")
                            strValue = objBinding.Converter.Convert(strValue, 
                              typeof(string), objBinding.ConverterParameter, 
                              objBinding.ConverterCulture).ToString();
                        else
                            strValue = objBinding.Converter.Convert(data, 
                              typeof(string), objBinding.ConverterParameter, 
                              objBinding.ConverterCulture).ToString();
                    }
                }
                lstFields.Add(FormatField(strValue,strFormat));
            }
            BuildStringOfRow(strBuilder, lstFields, strFormat);
        }
        StreamWriter sw = new StreamWriter(objSFD.OpenFile());
        if (strFormat == "XML")
        {
            //Let us write the headers for the Excel XML
            sw.WriteLine("<?xml version=\"1.0\" " + 
                         "encoding=\"utf-8\"?>");
            sw.WriteLine("<?mso-application progid" + 
                         "=\"Excel.Sheet\"?>");
            sw.WriteLine("<Workbook xmlns=\"urn:" + 
                         "schemas-microsoft-com:office:spreadsheet\">");
            sw.WriteLine("<DocumentProperties " + 
                         "xmlns=\"urn:schemas-microsoft-com:" + 
                         "office:office\">");
            sw.WriteLine("<Author>Arasu Elango</Author>");
            sw.WriteLine("<Created>" +  
                         DateTime.Now.ToLocalTime().ToLongDateString() + 
                         "</Created>");
            sw.WriteLine("<LastSaved>" + 
                         DateTime.Now.ToLocalTime().ToLongDateString() + 
                         "</LastSaved>");
            sw.WriteLine("<Company>Atom8 IT Solutions (P) " + 
                         "Ltd.,</Company>");
            sw.WriteLine("<Version>12.00</Version>");
            sw.WriteLine("</DocumentProperties>");
            sw.WriteLine("<Worksheet ss:Name=\"Silverlight Export\" " + 
               "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">");
            sw.WriteLine("<Table>");
        }
        sw.Write(strBuilder.ToString());
        if (strFormat == "XML")
        {
            sw.WriteLine("</Table>");
            sw.WriteLine("</Worksheet>");
            sw.WriteLine("</Workbook>");
        }
        sw.Close();
    }
}
The ExportDataGrid method prompts to the user to select the output save file name. Based on the user selection, the method determines the format to save -- XML or CSV. The Excel XML format used is not compatible with Microsoft Excel 2003 or earlier.
The row contents are built by a method named BuildStringOfRow.
private static void BuildStringOfRow(StringBuilder strBuilder, 
        List<string> lstFields, string strFormat)
{
    switch (strFormat)
    {
        case "XML":
            strBuilder.AppendLine("<Row>");
            strBuilder.AppendLine(String.Join("\r\n", lstFields.ToArray()));
            strBuilder.AppendLine("</Row>");
            break;
        case "CSV":
            strBuilder.AppendLine(String.Join(",", lstFields.ToArray()));
            break;
    }
}
The above method builds the row contents string as per the output format. Formatting of individual fields is done by a method named FormatField.
private static string FormatField(string data, string format)
{
    switch (format)
    {
        case "XML":
            return String.Format("<Cell><Data ss:Type=\"String" + 
               "\">{0}</Data></Cell>", data);
        case "CSV":
            return String.Format("\"{0}\"", 
              data.Replace("\"", "\"\"\"").Replace("\n", 
              "").Replace("\r", ""));
    }
    return data;
}
The FormatField method returns the data formatted as per the output format.

After including the attached code (DataGridExtensions.cs) to your project, you can initiate the export of theDataGrid contents by calling the Export() method of the DataGrid. For example, if the DataGrid name isobjDataGrid, you will be calling objDataGrid.Export() to invoke the export.

This code generates the Excel file in XML format. I found exporting in XML much easier than exporting into the XLS or XLSX format.

Interoperability with Excel using the COM Object

Silverlight 4 has the capability of accessing the COM object using the COM API. You can access any program installed in your PC using those APIs in Silverlight. You can open Notepad, Word, Excel or Outlook from a Silverlight application. Here I will demonstrate using the step-by-step tutorial on opening an Microsoft Excel book followed by data sharing between the Silverlight application and the Excel Sheet. Here, we will use a DataGrid which will load some customer information. Then we will pass the data to the Excel Sheet and then we will modify the data in the external application (i.e. inside the Excel sheet). You will see that the modified data will reflect automatically to the Silverlight Application.

See the below figure that we are going to demonstrate:


Prerequisite

To develop this simple application, you need the following tools installed in your development environment:
  • Microsoft Visual Studio 2010
  • Silverlight 4 Tools for Visual Studio 2010
Remember that the Silverlight 4 applications can be developed only in Visual Studio 2010. Hence, if you have Visual Studio 2008 installed in your PC, you can install Visual Studio 2010 side-by-side for exploring Silverlight 4.


If your development environment is ready, then we can proceed towards creating a new Silverlight Application project. At the end of this part, we will be able to run our first Silverlight application inside the browser.
  1. Open your Visual Studio 2010 IDE
  2. Select File > New Project or just press CTRL + SHIFT + N to open up the New Project dialog
  3. Expand the “Visual C#” node and then go to sub node “Silverlight”
  4. Select “Silverlight Application” in the right pane
  5. Select proper location to store your application (let’s say, “D:\Sample Apps\”)
  6. Now enter a proper name for your project (call it as: “Silverlight4.Interop.Excel.Demo”)
  7. Select the .NET Framework version from the combo box at the top (I am using .NET Framework 4.0)
  8. Click OK to continue
  9. In the next dialog, make sure that “Host the Silverlight application in a new Web site” option is selected
  10. Choose “Silverlight 4” as the Silverlight Version and hit OK
Wait for a while, Visual Studio will now create the Silverlight solution for you to use which will contain a Silverlight Project and one Web Application Project to host your Silverlight application. In your Silverlight project, you will find a “MainPage.xaml” & an “App.xaml” file which are already created for you by the IDE Template.
Once you are done with setting up the project, you need to add an Assembly Reference to the Silverlight project. We will use the “dynamic” keyword, and for this we need to add the “Microsoft.CSharp” assembly reference.

Right click on the “Reference” folder inside the Silverlight project and click on the “Add Reference” menu item from the context menu.

This will open up the “Add Reference” dialog on the screen. Scroll the window to find the assembly named “Microsoft.CSharp” from the .NET tab. Select it and click “OK”. This will add the Microsoft.CSharpassembly reference into your Silverlight project. Once added, your project will support dynamic variable declaration.



Once you are done with setting up your Silverlight project, we are ready to implement custom Out-of-Browser Window for our application. You can read the complete article on Creating Silverlight 4 Custom Out-of-Browser window from CodeProject.

Once you design your out-of-browser Window, go to the properties of the Silverlight project. From the Silverlight pane, be sure that you are using “Silverlight 4” as target version. Now select the “Enable running application out of browser” which will make the “Out-of-Browser Settings…” button enabled. Click on it for more settings.




From the Settings dialog window, select “Show install menu” which will create a Menu Item inside the Silverlight context menu. Once you run your application and right click on the application, you will see an “Install” menu item on it. I will come to this section later.

Now, check the “Require elevated trust when running outside the browser” as mentioned below and choose “Window Style” as “No Border”. This will make the default Chrome Window visibility to collapsed and if you run OOB, you will not see any Window border by default. Once you are done with these settings, click ok to save the configurations. You can also change the “Window Title”, “Size” and other options available there.

Now we will design our MainPage.xaml file with a DataGrid which will fetch Customer details from theDataProvider and generate the columns for it. We will make the DataGrid as Readonly, so that we can't directly edit the data inside it.

<sdk:DataGrid AutoGenerateColumns="True"
        Height="295"
        IsReadOnly="True"
        HorizontalAlignment="Left"
        VerticalScrollBarVisibility="Auto"
        Margin="0,30,0,0"
        x:Name="customerDataGrid"
        VerticalAlignment="Top"
        Width="576" 
        ItemsSource="{Binding CustomerCollection, 
		ElementName=userControl, Mode=TwoWay}" />

We will also set two different buttons in the Window. One for installing the application out of the browser window and the other to export the datagrid content to an Excel application. Here is the XAML code for the buttons:

<Button Height="28"
        HorizontalAlignment="Left" Click="exportToExcelButton_Click"
        Margin="244,333,0,0"
        x:Name="exportToExcelButton"
        Content="Export To Excel"
        VerticalAlignment="Top"
        Width="109" />

<Button Height="28"
        HorizontalAlignment="Left" Click="installButton_Click"
        Margin="244,333,0,0"
        x:Name="installButton"
        Content="Install"
        VerticalAlignment="Top"
        Width="109" />

Once your design is ready and you are done with data binding with your datagrid by fetching the customer information from the CustomerDataProvider, we can run the application inside the browser Window. Once loaded with fetched data, our application will look like the below figure:


Here, you will notice the “Install” button enabled at the bottom of the DataGrid. Click the button to install this application outside the browser as a standalone application, so that, you can launch it from desktop or startmenu. When you start the installation procedure, it will pop up the Security Warning dialog. Click “Install” to continue.


This will install the application in your local drive and automatically launch it out-of-browser. Here you will see a bit different view. You will notice that the “Install” button is no more available now and a new button named “Export to Excel” has been added to the view.

The following code block is responsible for changing the look of the application in different view:

if (App.Current.InstallState == InstallState.Installed)
{
    if (App.Current.IsRunningOutOfBrowser)
    {
        // write the code for out-of-browser window to make the
        // export to excel button visible
    }
    else
    {
        // write the code for the browser window to disable the install button
        // when the application is already installed
    }
}
else
{
    // write the code for the default view
}

“Export to Excel” Event Implementation

  1. Let us now go for the code implementation for exporting data from the datagrid to the Excel application instance.
    First of all, we will create the instance of an Excel application and will set the visibility to true, so that, others can view it.
    excel = AutomationFactory.CreateObject("Excel.Application");
    excel.Visible = true;
  2. Now create a workbook for the instance of the opened Excel application:
    dynamic workbook = excel.workbooks;
    workbook.Add();
  3. Get the ActiveSheet from the Excel Workbook and iterate through each row and column of the datagridcollection and set the values to the Excel sheet.
    dynamic sheet = excel.ActiveSheet;
    dynamic cell = null;
    int i = 1;
     
    // iterate through the data source and populate the excel sheet
    foreach (Customer item in customerDataGrid.ItemsSource)
    {
        cell = sheet.Cells[i, 1];
        cell.Value = item.Name;
        cell.ColumnWidth = 50;
     
    
        cell = sheet.Cells[i, 2];
        cell.Value = item.ID;
     
        cell = sheet.Cells[i, 3];
        cell.Value = item.Age;
     
        i++;
    }
  4. For the first instance of the application, we will now register the SheetChange event notification to our application. This will fire the event when you modify the content of the sheet.
    if (newInstance)
    {
        App.Current.MainWindow.Closing += (MainWindow_Closing);
        excel.SheetChange += new SheetChangedDelegate(SheetChangedEventHandler);
        newInstance = false;
    }
  5. Now go for the SheetChange event implementation. Here we will get the excelSheet which we will first store as a local instance for further access to it. Then get the range of the items to update from the Excel app to our application and iterate through the items and update. Below is the code for the event implementation:
    private void SheetChangedEventHandler(dynamic excelSheet, dynamic rangeArgs)
    {
        // copy the excelsheet to a local instance for further processing
        dynamic sheet = excelSheet;
     
        // get the range of the items to update
        dynamic col2range = sheet.Range("A1:A" + CustomerCollection.Count);
     
        for (int i = 0; i < CustomerCollection.Count; i++)
        {
            // update each and every row of the datagrid with the updated column
            // the first column in our case
            CustomerCollection[i].Name = col2range.Item(i + 1).Value.ToString();
        }
    }

“Export to Excel” Demo

We are done writing the code. Now, it is time to demo it. We will now see our application to actually talk with the Microsoft Excel application. From our application, we will transfer the datagrid content to the Excel Sheet. Hence click on the “Export to Excel” button from your out-of-browser application. You will notice that one Excel sheet has been created and the data is populating in the sheet row by row.



Let us drag our application on top of the Excel book to see the live demo. You can now see the Silverlight application on top of Excel while editing the sheet.


Now start editing any Row of the Excel sheet. In our example, we will use the first column for editing purposes because our code checks only the first column.
// get the range of the items to update
dynamic col2range = sheet.Range("A1:A" + CustomerCollection.Count);


Once you are done modifying the cell of the Excel sheet, just press Enter, so that it will come out from the edit mode. Hey what happened? Did you notice anything in our application? Yes right, in our application, the corresponding cell got updated with the modified cell content.


I think you now got the idea of Silverlight - Excel messaging through the COM API. This was a small demonstration of the new feature. You can now modify it for a bigger range of cell to update the Silverlight datagrid from Excel sheet. Be sure that it will only work for Silverlight trusted Out-of-Browser applications.