Sunday, June 13, 2010

COM Interop with silverlight 4.0

Silverlight 4 has a feature for accessing COM components which is installed /available in client machines.
I will walk through how to access a Excel application through silvelight .
For developing this application , we need VS 2010 , Silverlight 4 SDK.
Create a silverlight project using VS2010
image
Take the properties of SL project under silverlight tab for enabling Out Of Browser support.
image
We need to check ‘require elevated permission’ under Out of browser settings button.
Now am creating a datagrid(dgName) in MainPage.xaml and binding some data.
below code is used for setting datasource to datagrid.
private void UserControl_Loaded(object sender, RoutedEventArgs e)
       {
           ModelClass m = new ModelClass();
           dgName.ItemsSource = m.SetDataSource();
       }
image
preview : data grid.
Now i am putting a button which invokes ‘excel’ application and write all the data from the above data grid to the excel app.
private void Button_Click(object sender, RoutedEventArgs e)
       {
           dynamic excelObj = AutomationFactory.CreateObject("Excel.Application");
           excelObj.Visible = true;
           // add a workbook to the instance  
           dynamic workbook = excelObj.workbooks;
           workbook.Add();
           dynamic sheet = excelObj.ActiveSheet;
           sheet.Name = "Sample Sheet";
           // get the active sheet  
           dynamic cell = null; int i = 1;
           // iterate through our data source and populate the excel spreadsheet 
           foreach (ModelClass item in dgName.ItemsSource)
           {
               cell = sheet.Cells[i, 1]; // row, column   
               cell.Value = item.ID;
               cell.ColumnWidth = 25;
               cell = sheet.Cells[i, 2];
               cell.Value = item.Name;
               i++;
           }
       }
we are using AutomationFactory ( static class under System.Windows.Interop) for invoking Excel app . we can use this class for invoking apps like ‘Outlook’ , ‘Text to Speech’ COMs’.
‘dynamic’ is object whose operations will be resolved at run time.Intellisence will not be available while coding using ‘dynamic’ object.
image
I am attaching a sample application , can be download from here

No comments:

Post a Comment