DCSIMG
December 2007 - Posts - Alex Golesh's Blog About Silverlight Development

December 2007 - Posts

How to compile C# 3.0 code dynamically

One of major features being shipped with Visual Studio 2008 was new version of C# language.

When one creates new C# project in Visual Studio 2008 it can choose target framework version, which enables functionality/IntelliSense targeted to selected framework. But how some runtime generated code could be compiled with specific framework target?

In .NET v3.5 we got new overload to CSharpCodeProvider class, which takes "providerOptions" argument. This argument type is IDictionary<string, string> which could be used co configure compiler properties. Here is code sample, how to compile some basic runtime generated LINQ query:

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "test.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
using System;

class Program 
{
  public static void Main(string[] args) 
  {
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var numsPlusOne =
        from n in numbers
        select n + 1;
    
    Console.WriteLine(""Numbers + 1:"");
    foreach (var i in numsPlusOne)
        Console.WriteLine(i);

    Console.ReadLine();
  }
}");

Console.WriteLine("Compilation results:\n================================");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
Console.WriteLine("Done.");

The main think here is "CompilerVersion" & "v3.5" parameter passed to code provider.

This also could be controlled via .config file like follows:

<configuration>
  <system.codedom>
    <compilers>
      <!-- zero or more compiler elements -->
      <compiler
        language="c#;cs;csharp"
        extension=".cs"
        type="Microsoft.CSharp.CSharpCodeProvider, System, 
          Version=2.0.3600.0, Culture=neutral, 
          PublicKeyToken=b77a5c561934e089"
        compilerOptions="/optimize"
        warningLevel="1" />
          <providerOption 
            name="CompilerVersion" 
            value="3.5" />
    </compilers>
  </system.codedom>
</configuration>

Enjoy.

Anonymous Delegates vs Lambda Expressions vs Function Calls Performance

Recently I've worked on some project, where I needed to investigate performance issue. After some investigation, some profiling I've got suspicion, that some function being called a lot of times (more than 100,000 calls in some very specific and relatively short execution path) in profiled code part. It was to strange to see, how relatively simple function consuming so much CPU time. The function did some relative simple arithmetic calculations, based on 2-3 received as parameters. While trying to solve this, I've created some test project to simulate the situation.

Lets assume, we have the following function:

private double CalcPurchaseTaxes(double Amount, double localTax, double? additionalTax)
{
    if (null == additionalTax)
        additionalTax = 0;

    return Amount + Amount * localTax + Amount * (double)additionalTax;
}

When executing this in loop of 10,000,000 calls to simulate real function(which is obviously more complex) execution i've got average total of 00:00:00.3689428ms execution time.

Well, because my function is very simple (and also real project function), I decide to rewrite it as anonymous delegate function. That's what I've got:

//Delegate declaration
delegate double TaxCalculator(double Amount, double LocalTax, double AdditionalLocalTax);
///....

//Delegate implementation
TaxCalculator grossPrice = delegate(double Amount, double LocalTax, double AdditionalLocalTax)
{
    return Amount + Amount * LocalTax + Amount * AdditionalLocalTax;
};
///.....

Execution of this delegate for the same 10,000,000 times get me much better average result of 00:00:00.2163977ms. Pretty good improvement in terms of percentage...

I almost stopped there, but decided to try lambda expressions which actually should been translated to IL as anonymous delegates also...

Here is the very same calculation written with new C# 3.0 lambda expressions syntax:

////////////////////////////////////////////////////////////////////////////////////////////
Func<double, double, double> absoluteTax = (amt, tax) => amt * tax;
Func<double, double> grossPrice = amt => amt + absoluteTax(amt, localTax) + absoluteTax(amt, additionalLocalTax);

Well, definitely shortest syntax and for me also pretty nice... But what about performance? Hm... same 10,000,000 iterations, got average of 00:00:00.3349174ms...

Why?!? Shouldn't it be about delegate timing or even faster??? Shouldn't compiler generate more efficient code, that it did for delegates?

From looking on generated IL code, I've got even more strange picture: class generated by compiler from lambdas as expected is smaller, simpler and derives directly from System.Object.

Class created by compiler for delegates as expected derives from System.MulticastDelegate and has a lot of unused (at least in this simple case) stuff.

So, the confusion is still there - why lambdas performance less good comparing to anonymous delegates...

As for me, I expected to get delegates/lambdas with almost same results and function call behind them...

Ideas? Comments?

New Microsoft Download Center in Silverlight

Microsoft created new Download Center site in Silverlight! The site is still in Beta stage, have pretty long loading time and couple of other "imperfections", but already looks very promising.

image

Download Center Beta in Silverlight

Posted by Alex Golesh | 1 comment(s)
תגים:

Preview of ASP.NET 3.5 Extensions CTP was Released

Microsoft released today the first CTP preview of an "ASP.NET 3.5 Extensions".

This first ASP.NET 3.5 Extensions preview release includes:

  • ASP.NET AJAX Improvements: New ASP.NET AJAX features in the ASP.NET 3.5 Extensions release include better browser history support (back/forward button integration, and server-side history management support), improved AJAX content linking support with permalinks, and additional JavaScript library improvements.
  • ASP.NET MVC: This model view controller (MVC) framework for ASP.NET provides a structured model that enables a clear separation of concerns within web applications, and makes it easier to unit test your code and support a TDD workflow. It also helps provide more control over the URLs you publish in your applications, and more control over the HTML that is emitted from them.
  • ASP.NET Dynamic Data Support: The ASP.NET 3.5 Extensions release delivers new features that enable faster creation of data driven web sites.  It provides a rich scaffolding framework, and will enable rapid data driven site development using both ASP.NET WebForms and ASP.NET MVC.
  • ASP.NET Silverlight Support: ASP.NET 3.5 Extensions release deliver support for easily integrating Silverlight within your ASP.NET applications.  Included will be new controls that make it easy to integrate Silverlight video/media and interactive content within your sites.
  • ADO.NET Data Services: In parallel with the ASP.NET Extensions release, ADO.NET Entity Framework (codename "Astoria") will be also released.  This provides a modeling framework that enables developers to define a conceptual model of a database schema that closely aligns to a real world view of the information. 

More info here.

Download the ASP.NET 3.5 Extensions Preview

Posted by Alex Golesh | with no comments

Visual Studio 2008: C# Development Default Keybindings

Here is default keybindings for "C# Development" settings in Visual Studio 2008

image

Full size PDF is here.

Posted by Alex Golesh | with no comments

Silverlight and JavaScript interoperability - it's really simple

I'd like to answer on one of very frequent question I've been asked by great many developers, which playing with Silverlight v1.1 Alpha.

So, how one can execute managed code from JavaScript, and how JavaScript can get notification (event) from Silverlight (and possibly lunch some JavaScript functionality)?

Well, it's pretty simple. First, lets create Silverlight project (I'm using Visual Studio 2008 with Silverlight tools for Visual Studio 2008 installed).

Well... After creating the projects, let's do some coding... First of all, let's add some HTML button to out TestPage...

<input id="Button2" type="button" value="Test JavaScript to Silverlight Interoperability" onclick="JavaScriptToSilverlightInteroperability();"/>

In button "onclick" event I define call to some JavaScript function in my example I've called it "JavaScriptToSilverlightInteroperability".

Lets write such a function definition in JavaScript part of TestPage:

function JavaScriptToSilverlightInteroperability(sender, args)
{

}

Well... So far, so good. Now let's do some basic XAML editing... I'll add some TextBlock to my default Page.xaml and will change background... Here what I've got:

<Canvas x:Name="parentCanvas"
        xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Loaded="Page_Loaded" 
        x:Class="Silverlight_JS_Interoperability.Page;assembly=ClientBin/Silverlight_JS_Interoperability.dll"
        Width="640"
        Height="480"
        Background="LightSalmon"
        >
  <!--Some text block to enable some basic output-->
  <TextBlock x:Name="txtMyText" Canvas.Left="10" Canvas.Top="10" Width="300" Height="25"/>
</Canvas>

Now it is a time to write some real code (C#)... I'll gonna add some class, which will be accessed from JavaScript, implement couple of functions and property, define some Event and fire it. Most important here, is  that every part of managed code, which need to be accessed from JavaScript need to be decorated with [Scriptable] attribute:

 image

Now this is my very simple class:

//Class which will be acessed by Javascript
[Scriptable]
public class ManagedClass
{
    public ManagedClass()
    {
        //Registering class as "Scriptable" object to enable it being called from Javascript - will be used in Event firing from Silverlight to Javascript
        WebApplication.Current.RegisterScriptableObject("ManagedClassInstance", this);
    }

    //Event definition
    [Scriptable]
    public event EventHandler CallbackToBrowser_SomeEvent;

    //Some functions & Properties
    [Scriptable]
    public void VoidFunction(string Param1, string Param2)
    {
        //Some functionality here... For example updating textblock on XAML
        Page.txtBlock.Text = Param1 + " " + Param2;
    }

    [Scriptable]
    public int IntFunction(int Param)
    {
        //Firing event to Javascript
        CallbackToBrowser_SomeEvent(this, new MyEventAtgs() { SomeValue = "This is test message from Silverlight event!" });

        //Some functionality here....
        return Param;
    }

    [Scriptable]
    public int SomeProperty { set; get; }
}

Event arguments definition:

//Event arguments class - pretty simple here
public class MyEventAtgs : EventArgs
{
    [Scriptable]
    public string SomeValue {get; set;}
}

And finally, the main Page class:

public partial class Page : Canvas
{
    //Class being called by Javascript - instanciation
    ManagedClass managedClassExample = new ManagedClass();
    static internal TextBlock txtBlock;

    public void Page_Loaded(object o, EventArgs e)
    {
        // Required to initialize variables
        InitializeComponent();

        //Registering class as "Scriptable" object to enable it being called from Javascript
        WebApplication.Current.RegisterScriptableObject("Silverlight_Test_Class", managedClassExample);

        //simple access to XAML control to eneble class make some changes in Silverlight textblock
        txtBlock = txtMyText;
    }
}

Almost done... Pay attention, that instance of class, which I'm gonna access from JavaScript was initialized in page load event handler, and it was registered as "Scriptable object", which actually gives it access from JavaScript.

Now all I need to do, is actually access it from JavaScript and make JavaScript to "listen" to my CallbackToBrowser_SomeEvent event. Here is "JavaScriptToSilverlightInteroperability" function body:

function JavaScriptToSilverlightInteroperability(sender, args)
{
    //Receives Silverlight control from document
    var silverlightControl = document.getElementById("SilverlightControl").Content;
    
    if (silverlightControl)
    {
      //Silverlight void function call example
      silverlightControl.Silverlight_Test_Class.VoidFunction("Executed from", "HTML button click!");
      
      //Silverlight property set example
      silverlightControl.Silverlight_Test_Class.SomeProperty = 123;
      
      //Silverlight function call with returned value example      
      var IntFunction = silverlightControl.Silverlight_Test_Class.IntFunction(12345);
      alert("Got IntFunction return = " + IntFunction);
      
      //Silverlight property get examples      
      alert("SomeProperty = " + silverlightControl.Silverlight_Test_Class.SomeProperty);      
    }
}

And here is plumbing needed to "connect" managed events to BLOCKED SCRIPT

1. In function "CreateSilverlight" add event handler, which give me an opportunity to do some work:

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
    Silverlight.createObjectEx({
        source: "Page.xaml",
        parentElement: document.getElementById("SilverlightControlHost"),
        id: "SilverlightControl",
        properties: {
            width: "100%",
            height: "100%",
            version: "1.1",
            enableHtmlAccess: "true"
        },
        events: {
            onLoad: onLoaded //Execute function on Silverlight control load
        }
    });

2. Now, lets write this "onLoaded" function  and write actual JavaScript event handler:

//Silverlight control OnLoaded event handler
function onLoaded(sender, args)
{
    sender.Content.ManagedClassInstance.CallbackToBrowser_SomeEvent = OnAlertCallback;
}

//Function to handle Silverlight events
function OnAlertCallback(sender, args)
{
    alert(args.SomeValue);
} 

That's it... We done...

Let's lunch this project and click on HTML button:

image5

 

Everything worked as planned - we got out managed code executed, updated XAML element from code, raised managed event and captured it in JavaScript.

And last, but not least, we able to debug out managed code while executing the project!!!

image9

Hope this helps :)

 Here is sources.

 

Enjoy,

Alex

Parallel Extensions CTP - What and Why?

Recently I've downloaded Microsoft Parallel Extensions to the .NET Framework CTP and installed it on my laptop... From extensions documentation and Extensions Developers blog I've got very a picture of new "nice" additional which could improve performance in some cases in .net applications. Now, after installing, playing with it and launching included samples I'm very confused about very important think: it supposed to work faster, that single threaded application? If yes, why I'm getting such strange behavior:

image

My CPU is worked very hard to calculate those results, and I have pretty strong Dell Precision laptop:

image

Why it should be better, than multithreaded programming we do for years in .NET?

Is it still very premature extensions behavior, or I just miss something?

First Post

Hello and welcome to my blog!
My name is Alex Golesh. I'm .Net consultant and instructor at Sela. I love to develop and love to research new technologies.
This is my first post in blog...
 
Here is short preview of what will be here:
if (You.InterestedIn(new string[] {"Silverlight", "WPF", "LINQ", ".NET Developing", "CSharp"}))
     Console.WriteLine("Welcome to my blog!");
else
     Console.WriteLine("Where do you want to go today?");
 
Will be glad to see you again,
Alex