Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, April 4, 2011

Doing the dynamic thing (Part III)

In the first part of this series I gave an introduction to what the dynamic keyword can do for you. The second part of this series showed you how this dynamic keyword can be pretty handy when interoperating with javaScript code. in this third part we will look into interoperating with Excel. This part will be brief, though, mainly because there are already quite a lot of examples to be found concerning this subject.
In this post I will extend the example I started in the previous post. There, we've seen I get a list of Person data from a WCF service. This Person list is shown in a DataGrid control of a Silverlight application. The latest version of Silverlight, supports running out of browser and once you run out of browser you get some extra possibilities for your application. One of these possibilities is interacting with automation objects, like Excel. So, let's extend our example so it can run out of browser and also, so it can generate an Excel document.
Running out of browser is actually not that hard to do. The user of your application can right click on the Silverlight application and choose 'Install NameOfYourApplication onto this computer'.


To offer this right click functionality to your users you need to check the 'Enable running application out of the browser' checkbox in the project settings of your Silverlight application.


The button control under this checkbox will show a popup window with some extra settings. One of these extra settings, 'require elevated trust', is important if you want to offer automation functionalities in your out of browser Silverlight application, so you should check this as well. 


Once you have done this, your users can install your application. 
In code it is possible to test whether or not you are running out of browser. I, for instance, added some code to disable a button that generates HTML if we are running out of browser, since generating HTML is pretty useless if you're not running in a browser window (and if you do execute the generation of HTML out of browser you will get a runtime error, so better disable it).
btnHTML.IsEnabled = !Application.Current.IsRunningOutOfBrowser;

We can also test whether or not we can use the automation capabilities.
if (AutomationFactory.IsAvailable)

Once we know we have automation available, we can create a new Excel object. The return type of the GetObject and CreateObject calls is dynamic, so this is a good choice for the type of your variable.
dynamic ExcelApp;
try
{
    ExcelApp = AutomationFactory.GetObject("Excel.Application");
}
catch (Exception exc)
{
    try
    {
        ExcelApp = AutomationFactory.CreateObject("Excel.Application");
    }
    catch (Exception exc2)
    {
        txtStatus.Text = exc2.Message;
        return;
    }
}

The reason I use both GetObject and CreateObject is that if Excel is already running, we can get a reference to the application with GetObject. If Excel is not already running, we need to start, or create the application with CreateObject.
Once we have the Excel application at our disposal, we can create workbooks, we can add data to cells, etc. The good news is that, since version 4.0 of the .NET framework all objects in Excel (and in the other Office automation frameworks) are of type dynamic. This simply means you can omit a lot of casting operators. Where previously you needed to write code like this:
var ExcelApp = new Excel.Application();
ExcelApp.Visible = true;
Workbook workbook = ExcelApp.Workbooks.Add();
int rowCounter = 1;
foreach (DataService.Person p in dataGrid1.ItemsSource)
{
    ((Range)((Worksheet)workbook.Sheets[1]).Cells[rowCounter, 1]).Value = p.FirstName;
    ((Range)((Worksheet)workbook.Sheets[1]).Cells[rowCounter, 2]).Value = p.LastName;
    rowCounter++;
}
((Range)((Worksheet)workbook.Sheets[1]).Columns[1]).AutoFit();
((Range)((Worksheet)workbook.Sheets[1]).Columns[2]).AutoFit();

You can now write this much more briefly like this:
ExcelApp.Visible = true;
dynamic workbook = ExcelApp.Workbooks.Add();
int rowCounter = 1;
foreach (DataService.Person p in dataGrid1.ItemsSource)
{
    workbook.Sheets[1].Cells[rowCounter, 1].Value = p.FirstName;
    workbook.Sheets[1].Cells[rowCounter, 2].Value = p.LastName;
    rowCounter++;
}
workbook.Sheets[1].Columns[1].AutoFit();
workbook.Sheets[1].Columns[2].AutoFit();

As you can see, there is a lot of casting going on in the first example, primarily to the Worksheet type and to the Range type. This is something we can completely omit when using dynamic. Which, in my opinion is a good thing!
The bad news, however, is, that with these dynamic types, your intellisense is gone. You need to know which operation calls are valid on which objects. But than again, who cares, because previously you needed to know which type you needed to cast to. If you got that one wrong, you'd get a runtime exception as well.
If you want to know even more on automation, this article in the MSDN library can give you some extra info.
That's it for the Office automation part of this series. Be ready to do some serious stuff with ExpandoObjects in the next post.

Sunday, April 3, 2011

Doing the dynamic thing (Part II)

After the basic intro given in the first part of this series, it is time for something more advanced. It won’t be rocket science, yet, but you will get more insight into what dynamic coding can do for you.
As mentioned in the previous post, dynamic programming can help you a lot when working with COM objects. I will give an example of this for JavaScript objects in a small Silverlight application. In the next post I will extend this simple example and I will explain interaction with Excel. But first, let’s talk about JavaScript.
Interacting with JavaScript might be something you need in real life. For instance if you have a Silverlight app that is hosted on a page that relies on JQuery a lot. JQuery can provide you with objects your SilverLight application does not know about. How can you interact with these objects if your managed code doesn’t know their type? The answer is to utilize dynamic.
To illustrate this, suppose we have a service running that can give us data about persons. A Person being just a DTO class with a FirstName and LastName property. Plain and simple.

[ServiceContract]
public interface IDataService
{
    [OperationContract]
    List<Person> GetData();
}
 
[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { getset; }
    [DataMember]
    public string LastName { getset; }
}

I also have a HTML page that includes a SuperPerson object. A SuperPerson being the same as a Person, but with one extra property, 'somethingextra'.
function SuperPerson(firstname, lastname, somethingextra)
{
    this.firstname = firstname;
    this.lastname = lastname;
    this.somethingextra = somethingextra; 
}
There is also a JavaScript function that can create one of these SuperPerson objects with the extra data.
function GetSuperPerson(firstname, lastname, somethingextra) {
    var person = new SuperPerson(firstname, lastname, somethingextra);
    return person; 
}
To illustrate how to work with such a JavaScript object, I’ve made a small Silverlight application that receives a list of person objects from the WCF service described above. The Silverlight application will display this list of persons in a DataGrid control. 
public MainPage()
{
    InitializeComponent();
    DataService.DataServiceClient client = new DataService.DataServiceClient();
    client.GetDataCompleted += new EventHandler<DataService.GetDataCompletedEventArgs>(client_GetDataCompleted);
    client.GetDataAsync();
}
 
void client_GetDataCompleted(object sender, DataService.GetDataCompletedEventArgs e)
{
    dataGrid1.ItemsSource = e.Result;
}
This is the basic set up I will use in this example. The Silverlight application will be hosted on an HTML page that has the above mentioned JavaScript code present. 
In this example, to keep it simple, I will build a HTML table. It will be the Silverlight code that builds this table, not the JavaScript code. For this, first thing will be to get hold of a specific div tag on the HTML page in which we will build our table. Silverlight lets you interact with the hosting page through the HtmlPage class. This class gives you a Document property that behaves pretty much the same as the document object in JavaScript, which makes it very easy to use.

HtmlElement theDiv = HtmlPage.Document.GetElementById("dynamicDiv");
HtmlElement table = HtmlPage.Document.CreateElement("table");
Next, we will iterate over all Person objects in the DataGrid.

foreach (DataService.Person p in dataGrid1.ItemsSource)
{
For each of these Person objects we will execute the GetSuperPerson function, present in the JavaScript of the hosting page. Since the Silverlight application has no knowledge of the SuperPerson type, we will use the capabilities of .NET 4.0.

    dynamic superperson = HtmlPage.Window.Invoke("GetSuperPerson", p.FirstName, p.LastName, System.DateTime.Now.Millisecond);
With the dynamic keyword in place our compiler does not complain about the SuperPerson type it does not know about. And since we know a SuperPerson has a firstname, lastname and somethingextra, we can interact with it though these operations with no problem.

    HtmlElement row = HtmlPage.Document.CreateElement("tr");
    dynamic td = HtmlPage.Document.CreateElement("td");
    td.innerHTML = superperson.firstname;
    row.AppendChild(td);
    td = HtmlPage.Document.CreateElement("td");
    td.innerHTML = superperson.lastname;
    row.AppendChild(td);
    td = HtmlPage.Document.CreateElement("td");
    td.innerHTML = superperson.somethingextra;
    row.AppendChild(td);
    table.AppendChild(row);
}
 
theDiv.AppendChild(table);
Two things are notable about the code above. First of all, I use firstname and lastname, not FirstName and LastName (mind the casing). This is because we are interacting with the JavaScript object, not with the original Person object. I purposely used other casing in the JavaScript code to make my point on this clear.
A second thing you may have noticed is a second use of the dynamic keyword. When I create a new td element, I do not use the HtmlElement type (which is valid for a td tag), but instead I use the dynamic keyword. I do this because I know for sure it is possible to call the innerHtml operation on a td tag. The HtmlElement, however, does not have this operation present (you can check this in your intellisense). There is also no specific type for a td element that does have this operation present. With dynamic there is no problem at all to call innerHtml, not at compile time and not at run time.
There you have it, two good reasons to use dynamic when you're interacting with JavaScript. You can get around unknown objects in managed code and you can call operations managed code has no clue of.
Be ready for the next two parts, first on dynamic and Excel and next about ExpandoObjects (this is where the fun begins!).

Thursday, March 31, 2011

Doing the dynamic thing (Part I)

A while ago I was asked to give a presentation to co-workers about the new features in the 4.0 .Net framework. Being a bit of a language geek, this job, of course, was cut out for me. A lot of topics passed the revue, but the most interesting one, in my eyes, was the new dynamic keyword and the new dynamic features in version 4.0 of the framework.

However it's a bit sad that, when searching the web for good examples of dynamic programming, you get so few practical answers. Most sites stay on the surface of really discussing dynamics and how they can be employed in real life problems. Also, most blog posts about the topic were made 2 to 3 years ago. I'm guessing that means dynamics didn't really kick in as expected. Why, you would ask? In my opinion (and according to the reactions I've heard), people really don't like to live without their code completion for starters. They feel dynamics is a step back (towards plain old scripting languages aka VBScript, JavaScript, ... just to name a few). So in this, and next, post(s), let's look at dynamic programming, what it is, and how it can help solve some of our more practical issues in programming. Because, let's face it, a language like Ruby does the dynamic thing and is widely popular, there must be some revenue in employing dynamics, no?

First of, let's review a simple example of dynamic (one of the many found out there).

Dynamic can represent any type:
dynamic d1 = 7;
dynamic d2 = "a string";
dynamic d3 = System.DateTime.Today;
dynamic d4 = System.Diagnostics.Process.GetProcesses();
And I can quite easily assign these variables to their statically typed counterparts:
int i = d1;
string str = d2;
DateTime dt = d3;
System.Diagnostics.Process[] procs = d4;
So, I hear you think, that's like var and object. Indeed, like var and object, but with a different flavour. Because with var and object I can also do something like this:
object o1 = 7;
object o2 = "a string";
var v1 = 7;
var v2 = "a string";
Looks the same, right? Yes, but not quite. See, the thing is, object and var are still statically typed, meaning that at compile time their type is checked. The compiler knows o1 is of type integer and o2 is of type string, just as it knows for v1 and v2. The d1, d2, d3 and d4 variables, however, are dynamically typed, meaning their type is not checked at compile time, but at run time.

For a dynamic type I can do this:
int oKButCrashAtRunTime = d2;
At compile time I will get no errors whatsoever for this line of code. The compiler says it is valid.

Something I cannot do for object or var:
int notOkAtCompileTime = o2; //compile time error
int alsoNotOkAtCompileTime = v2; //compile time error
At run time however, the line of dynamic code will give me a big fat runtime exception. It's not because something is dynamic you can suddenly assign a string to an integer. So with dynamic types, you need to be extra careful.

These runtime exceptions are part of the reason why people don't like dynamic programming. You only know you've done bad once it crashes (in the user's face). But then why are there tons of programs written in dynamic languages like Ruby? Well, mainly, because Ruby programmers employ a slightly different way of writing code. And if you want the same confidence for your (partly) dynamic .Net code as Ruby programmers have for their (totally) dynamic Ruby code, you will have to learn some of those best practices. Those however, together with a practical .Net example, I will leave for a next post.

Also, dynamic programming brings in new possibilities when developing code. For starters, you get a much easier experience when working with COM objects (eg. in Excel, Word, but also objects from JavaScript). Another pro is the ability to add dynamic behaviour to your static programs. This as well I will leave for one of my next posts.