Posted on July 26, 2008 21:47 by swilliams

Delegates have come a long way since they were introduced in .NET 1.0. Back then they were only a way to refer to existing methods as variables. 2.0 allowed methods to be inlined, making them "anonymous." The 3.5 Framework does not introduce any new concepts regarding delegates, but it makes writing them much, much quicker and cleaner.

Let's reuse the example from the last post. C# 2.0's syntax for anonymous methods looked like this:

private delegate void ItemAction(ListViewItem item, int index);

private void ActOnListView(ItemAction action) {
    for (int i = 0; i < this.listView1.Items.Count; i++) {
        ListViewItem item = this.listView1.Items[i];
        action(item, i);
    }
}

public void HighliteEven() {
    this.ActOnListView(delegate(ListViewItem item, int index) {
        item.BackColor = index % 2 == 0 ? Color.Red : item.BackColor;
    });
}

The HighliteEven() method can be written with C# 3.0 as:

public void HighliteEven() {
    this.ActOnListView((x, y) => x.BackColor = y % 2 == 0 ? Color.Red : x.BackColor);
}

Whoa, where did that => thing come from? That's the new shorthand for creating an anonymous method. All it does is compresses delegate(Type object){ into something smaller. The (x, y) parameters do not need Type declarations because they are inferred from the delegate's signature as a ListViewItem and a Int32 (you'll even get intellisense on them).

This is what allows you to use all of the slick extension methods added to the standard collection classes:

List<string> stuff = new List<string>();
if (stuff.All(s => s.Length > 10)) {
    Console.WriteLine("all strings have at least 10 characters.");
}
string[] myName = stuff.Where(n => n.StartsWith("Scott"));

Single object parameters do not need parentheses, and delegates with no parameters use empty ones: ().

This type of expression is often called a Lambda. Technically, you can have multiple line lambdas, the convention is to stick with a single one1. Multiple lines of code with this syntax can quickly become messy and hard to read. Stick with the old delegate() { } syntax instead if you need it.

[1. I'm not even going to show or link to the syntax, since you shouldn't use it.]

If you are familiar with Python or Ruby (and others) this style should be familiar to you.

	# a lambda in Python
	sq = lambda x: x * x
	sq(5)
	# returns 25

	# a lambda in Ruby
	sq = lambda {|x| x * x}
	sq.call(5)
	# returns 25

.NET also provides a few prefab helper delegates. Action was provided in the 2.0 framework. It's signature looks like this:

public delegate void Action(T obj);

It has a few overloads to take up to four parameters. So, our sample code up top can be rewritten as:

private void ActOnListView(Action<ListViewItem, int> action) {
	// snip
}

Removing the ItemAction definition.

For methods that need to return something, .NET 3.5 offers several versions of a delegate called Func. The most basic is Func<TResult>(), which takes no parameters and returns an instance of whatever TResult is set to. Func<T, TResult> takes a single parameter, of type T, and also returns a TResult. Like Action, Func provides overloads for up to four parameters. These can all be backported to .NET 2.0, since they don't use any 3.5-only features:

public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T obj);
// and so on

The various forms of Func are used throughout the LINQ enabled extension methods of the 3.5 Framework.

The single biggest thing to be aware of is that overuse of delegates makes code difficult to read, especially for the neophyte. If you have a particularly hairy situation, say one that has three or more nested generics and a few lambdas, all on one line, consider splitting it apart in order to increase readability. The compiler won't care, but maintainers will appreciate it.

If you have never encountered them before, delegates can feel a little awkward at first, but once you get used to them, especially with C# 3.0's lambda syntax, you won't want to go back.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on July 24, 2008 10:13 by swilliams

Back in Part 1, we covered the history of Delegates in the .NET Framework. As stated, in 1.1, they were a little too confined to be exceptionally useful. However, in the 2.0 Framework, Delegates were given the ability to be "Anonymous" and could be created on the fly. This allows for more elegant coding, and serves as an introduction to some concepts previously relegated to Functional Programming.

First, an example. In the previous post, this was our basic demonstration of a delegate:

public delegate void SomeFunction(int num);

public void PrintHello(int num) {
    for (int i = 0; i < num; i++) {
        Console.WriteLine("Hello."); 
    }
}

public void Main() {
    SomeFunction func = new SomeFunction(this.PrintHello);
    func(10);
}

Anonymous Methods mean that we do not have to define the PrintHello method as a part of the class, it can be created inline:

public delegate void SomeFunction(int num);

public void Main() {
    SomeFunction func = delegate(int num) {
        for (int i = 0;, i < num; i++) {
            Console.WriteLine("Hello.");
        }
    };
    func(10);
}

This in and of itself is useful; it cuts down a few lines of code, but doesn't necessarily add too much value.

Enter Closures. A Closure is "a [method] that is evaluated in an environment containing one or more bound variables." (I'll use OO terminology since this is C# related). What this means is that an anonymous method can refer and use variables defined in the scope surrounding it. Thus:

public delegate void SomeFunction(int num);

public void Main() {
    string s = "This is what will print.";

    SomeFunction func = delegate(int num) {
        for (int i = 0;, i < num; i++) {
            Console.WriteLine(s); // not defined in the delegate, but still valid
        }
    };
    func(10);
}

This of course begs the question of the ages, so what? Why would I possibly want to do something like that? Well, for a simple example, let's say you have a collection of items, say, the items in a ListView, and you have a bunch of operations you want to perform on them at different times. The non-delegate way would be to have separate methods that iterate through the list and do its thing.

public void HighliteEven() {
    for (int i = 0; i < this.listView1.Items.Count; i++) {
        ListViewItem li = this.listView1.Items[i];
        if (i % 2 == 0) {
            li.BackColor = Color.Red;
        }
    }
}

public List<ListViewItem> ExtractLong() {
    List<ListViewItem> items = new List<ListViewItem>();
    foreach (ListViewItem item in this.listView1.Items) {
        if (item.Text.Length > 50) {
            items.Add(item);
            this.listView1.Items.Remove(item);
        }
    }
    return items;
}

These are only two methods, but it's not uncommon to have upwards of a dozen, depending on how robust the UI is. If you have an ExtractLong, there's a good chance you'll need an ExtractShort, and probably more ExtractX methods too. Already you can see code duplication in the loops. Anonymous methods let you refactor this code to:

private delegate void ItemAction(ListViewItem item, int index);

private void ActOnListView(ItemAction action) {
    for (int i = 0; i < this.listView1.Items.Count; i++) {
        ListViewItem item = this.listView1.Items[i];
        action(item, i);
    }
}

public void HighliteEven() {
    this.ActOnListView(delegate(ListViewItem item, int index) {
        if (index % 2 == 0) {
            item.BackColor = Color.Red;
        }
    });
}

public List<ListViewItem> ExtractLong() {
    List<ListViewItem> items = new List<ListViewItem>();
    this.ActOnListView(delegate(ListViewItem item, int index) {
        if (item.Text.Length > 50) {
            items.Add(item);
            this.listView1.Items.Remove(item);
        }
    });
    return items;
}

This is better, but we can refactor the Extract method even more. .NET 2.0 also introduces a special delegate called Predicate<T>. If you have used the Array.Find method before, you've used Predicate<T>. A predicate simply executes an expression that returns a boolean. In Array.Find()'s case, it evaluates the object at each index of the array. If the object passes the test provided, it adds it to the return set.

We can use the same idea here to create a generic Extract method which we can give any number of comparers, greatly shortening each ExtractX method.

private List<ListViewItem> Extract(Predicate<ListViewItem> comparer) {
    List<ListViewItem> items = new List<ListViewItem>();
    this.ActOnListView(delegate(ListViewItem item, int index) {
        if (comparer(item)) {
            items.Add(item);
            this.listView1.Items.Remove(item);
        }
    });
    return items;
}

public List<ListViewItem> ExtractLong() {
    return this.Extract(delegate(ListViewItem item) {
        return item.Text.Length > 50;
    });
}

Making an ExtractShort method is just another 3 liner, who's payload is return item.Text.Length < 5; So, rather than having 8 lines of code (at least) per Extract method, you can have 3, which can be a huge savings, and makes testing far easier.

These concepts, and the syntax, may look a little intimidating, but once you have used them for a little bit, you won't want to go back. In the next post, I'll cover the updates to .NET 3.5, and show similar features in a couple other languages.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on June 30, 2008 10:26 by lbrown

Ever wonder how that magical tag called ‘[Serializable]’ placed at the top of a class enables it to be deconstructed into XML that can be tranmitted through firewalls or persisted in a files or database tables? Not to get too technical but attribute classes are embedded into the tagged classes’ metadata at compilation and can be reflected on to perform any function you desire. 

The following example provides a real world scenario where custom attributes can enhance one’s  coding experience.  I can’t tell you how many times I have to use stored procedures that have a million parameters each having the capacity to be null.  Think of a search procedure that has ten criteria.  If I was coding this with the SqlCommand class, I would have to write a method that creates each SqlParameter and populates it with DBNull or some value. There are over ninety nine combinations in this scenario.  That really cuts into my ebay time.

If I wrote an attribute that could turn a class into a SqlCommand with populated values and could be serialized in session or view state and reduce my time coding, life would be wonderful.  In addition, if I wrote a tool that generated the code for the attributed class, my evil plan to do no work would be complete!

I have attached a solution that contains all the code mentioned above.

AtrributeSolution.zip (51.43 kb)



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on June 20, 2008 13:14 by swilliams

Delegates are a big part of the .NET Framework. They were included since the beginning with .NET 1.0 and have matured since then, but in my experience I don't see them used intentionally too often.

I think the reason for this is because the concept of a delegate is kind of foreign if you have a more procedural background, using mainly languages like Visual Basic or Java, and to a certain extent, C. I certainly hadn't encountered anything like that until I started using C#, and had a difficult time wrapping my head around the concept.

To understand them better, let's take a look at the history of delegates, starting with the positively ancient and crusty .NET 1.0.

At the most basic level, a delegate serves as a way to treat a method as a variable. This means that it can be passed around to different methods, or have its execution delayed until deemed fit. A common reaction to this is "Why would I ever want to do that?" Well, it lets you do some interesting things. For starters, it makes it easier to perform certain kinds of logic at runtime without having to write a great deal of code.

And since every explanation is better with a little bit of code, let's get to it. As stated, delegates have been around for a while. With .NET 1.0, a delegate could only wrap an existing method, nothing on-the-fly:

// This is the definition of the delegate. The return type (void) and 
// arguments (int num) are the signature for any methods that 
// will be wrapped by this delegate.
public delegate void SomeFunction(int num);

// A standard method
public void PrintHello(int num) {
    for (int i = 0; i < num; i++) {
        Console.WriteLine("Hello."); 
    }
}

public void Main() {
    // PrintHello's signature matches what was declared by the 
    // delegate, so it can be used as a variable if needed.
    SomeFunction func = new SomeFunction(this.PrintHello);
    func(10);
}

Again, why does this even matter? The most useful thing about delegates is that you don't need to know which method needs to be called at compile time. One of the classical Design Patterns is the Command Pattern, which let's you abstract a common piece of functionality out to a variable, and pass it around... sound familiar? Delegates are not a complete substitute for the pattern, but can perform similar functionality with far less code. And less code is always better.

Additionally, .NET's event model is based on delegates. The EventHandler is really just a delegate that returns null and takes an Object and an EventArgs. They are also used with some of the asynchronous logic in the framework, BeginInvoke being primary.

For a real-world example, I've seen them used as a neat solution for some of the shortcomings with a Windows Form ToolBar. Back in .NET 1.1, the ToolBar still had many COM underpinnings, and the ToolBarButtons that made up the Bar did not have individual OnClick events on them; you had to handle the ToolBar's ButtonClick event, and pull the Button property from the event's arguments (this was a mess that was replaced with the ToolStrip in .NET 2.0). Once you got this, then you would need to perform some sort of test to determine the appropriate action method. Rather than have a 20 line select statement, one bright co-worker just wrapped the desired method in a delegate and dropped it into the button's Tag property. In just two lines he was able to accomplish what my 20+ did. I call that a bargain.

Here is an example of using delegates to implement a State Machine. This is just the framework for a machine, the strength of it lies in its ability to declare the edges of the graph dynamically.

public delegate Node EvalOp(State s);

public abstract class State {
    // State contains all information about the current position in the graph.
}

public class Node {
    private string _name;
    public EvalOp[] ops;

    public Node(string name) {
        this._name = name;
        this.ops = new EvalOp[] { };
    }

    public string Name {
        get { return this._name; }
    }

    public Node Evaluate(State s) {
        foreach (EvalOp op in this.ops) {
            Node n = op(s);
            if (n != null) {
                return n;
            }
        }
        // If we reach this point, we are at the end.
        return null;
    }

    private static Node _end = new Node("End");

    public static Node EndNode {
        get { return _end; }
    }
}

public abstract class Graph {
    protected Node[] nodes;
    protected Node currentNode;
    protected State state;

    public Graph() {
        this.Init();
    }

    public void Start() {
        for (this.currentNode = nodes[0]; this.currentNode != Node.EndNode; this.currentNode = this.currentNode.Evaluate(this.state)) { 
            this.Step();
        }
    }

    protected abstract void Step();

    // Create nodes and state here
    protected abstract void Init();
}

The basic operation is that each node contains an array of delegates (EvalOp) to define the edges to a new node. The EvalOp takes a State object and determines if it satisfies the requirements of the edge. If it does, it returns the next node to travel to. Each EvalOp is evaluated until the first valid Node is returned. It's not the most robust State Machine ever created, but I wanted to demonstrate delegates rather than State Machines.

I wrote a simple implementation to demonstrate it. There are three nodes, including the EndNode already created by the framework. One is called Odd, and the other is Even, and they switch back and forth depending on the value of State, which is incremented each step of the way, until 100 is reached.

public class ConcreteState : State {
    private int _count;

    // Note the lack of auto-properties in 1.0. Argh.
    public int Count {
        get { return this._count; }
        set { this._count = value; }
    }
}

public class ConcreteGraph : Graph {
    protected override void Init() {
        this.state = new ConcreteState();
        Node odd = new Node("Odd");
        Node even = new Node("Even");

        EvalOp oddTest = new EvalOp(this.OddOp);
        EvalOp evenTest = new EvalOp(this.EvenOp);
        EvalOp finishTest = new EvalOp(this.CountOp);

        odd.ops = new EvalOp[] { finishTest, oddTest };
        even.ops = new EvalOp[] { finishTest, evenTest };
        this.nodes = new Node[] { odd, even };
    }

    protected override void Step() {
        ((ConcreteState)this.state).Count++;
    }

    private Node OddOp(State s) {
        if (((ConcreteState)s).Count % 2 == 1) {
            Console.WriteLine("Odd");
        }
        return this.nodes[1]; // move to the even op
    }

    private Node EvenOp(State s) {
        if (((ConcreteState)s).Count % 2 == 0) {
            Console.WriteLine("Even");
        }
        return this.nodes[0]; // move to the odd op.
    }

    private Node CountOp(State s) {
        return ((ConcreteState)s).Count == 100 ? Node.EndNode : null;
    }
}

More complicated functionality could be added by just creating a new EvalOp delegate (like say, MultipleOfFourOp) and adding it to the proper node[s].

Delegates are not all roses of course. Their biggest shortcoming in 1.1, was that they were too rigid. You needed to have a method defined elsewhere in the app, and you couldn't do some of the neat things that other languages were able to do with similar constructs (typically called lambdas). Fortunately, .NET 2.0 significantly improved delegate's abilities and 3.5 made them extra delicious. I'll write more about them later.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 16, 2008 00:34 by jpager

Two days ago, I posted an example of a way to apply IronPython scripting in .NET. At the very end of my post, I wondered about the possibility of compiling the script as a .NET assembly.

I'm happy to say, I have found a way to implement this functionality (and I might mention at this point that this is my last post about IronPython). First, I'll explain how I was able to do it, and then I'll explore whether we really gain anything from having a pre-compiled script.

First, compiling the script. The idea is that we only want to recompile our script if (a) the DLL does not exist or (b) our script is more recent than the DLL (i.e., it has been edited). We'll examine our files using the System.IO.FileInfo class. If we need to compile the script, we'll use IronPython's implementation of System.CodeDom.Compiler.CodeDomProvider, which will allow us to compile a python script into MSIL, and save the assembly as a DLL (this is located in the IronPython.CodeDom namespace):

FileInfo fi_in = new FileInfo(exportScript);
FileInfo fi_out = new FileInfo("BatchExport.dll");
if (!fi_out.Exists || (fi_in.LastWriteTimeUtc >= fi_out.LastWriteTimeUtc))
{
   PythonProvider p = new PythonProvider();
   CompilerParameters _params = new CompilerParameters(new string[] { }, "BatchExport.dll");
   CompilerResults r = p.CompileAssemblyFromFile(_params, new string[] { exportScript });
   if (r.Errors.Count > 0) throw new Exception("Compiler error.");
}


This is fairly straightforward. We create a compiler, call CompileAssemblyFromFile(), which is configured to save the assembly as BatchExport.dll and compile the file containing our python script. The compilation takes a short amount of time, so we only want to compile if absolutely necessary.

The next step is actually calling into the compiled assembly. As I mentioned last time, calling a Python assembly from C# is non-trivial. That python assembly contains dynamic types, which are not easily reflected into useful C# objects. So my approach was to create a PythonEngine, import the assembly into said PythonEngine, and call the method using Python.

To do this, I first altered my script so that my Export() method is contained in a class called BatchExport, rather than being a global method. Then, in my C# code, I created an instance of the BatchExport class, and called the Export() method on that object.

using (PythonEngine engine = new PythonEngine())
{
   engine.AddToPath(AppDomain.CurrentDomain.BaseDirectory);
   engine.Import("clr");
   engine.Execute("clr.AddReference('BatchExport.dll')");
   engine.Execute("import BatchExport");
   engine.Execute("be = BatchExport()");
   List<string> _params = new List<string>();
   _params.Add("order");
   ExportDelegate exMethod = engine.CreateMethod<ExportDelegate>("return be.Export(order)", _params);
   bool res = exMethod(order);
}


Our first step was to actually load our assembly into our python engine. To do that, we call clr.AddReference(). This allows us to include any .NET assembly in our script.

Then, we instantiated our BatchExport object, and use the CreateMethod() method to actually call the object's Export() method. Now the compile-script-only-if-it-has-changed functionality works perfectly.

Of course, after doing this, I made a big mistake--I decided to see how much time this actually buys us. So I created a simple script that processes a batch 500 times using the old method (that simply calls ExecuteFile()) and the same batch 500 times using the new method (I also created a new Export() python script that doesn't write to any files, in order to avoid any bias involving file sizes). The result was at least a little surprising--it took the method that pre-compiles the script 15 times as long to process the batches as it does the method that executes the script anew each time.

Possible culprits? Probably the cost of reflection is the main one. I don't think the check on the file times could make that big a difference. Clearly this little operation is quite expensive:

engine.Import("clr");
engine.Execute("clr.AddReference('BatchExport.dll')");
engine.Execute("import BatchExport");

So, I guess what we can take out of this is that compiling python scripts to .NET DLLs comes at a considerable cost, both in performance and complexity, at least if the script is simple. It may be cheaper to precompile the assembly if our script is hundreds (or thousands) of lines long, but for fairly basic scripts, you might as well just leave them as scripts.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 14, 2008 01:07 by jpager

Last week I explored the PythonEngine object in IronPython. We didn't get any deeper than simply using the API--this week I figured I'd actually put it to use in a real application.

Here is our scenario. You are a developer for a software company that writes a Point of Sale application on the .NET platform. You have hundreds of clients, each with their own in-house IT departments. You'll install everything for them, provide some support when needed, but you simply don't have time to offer each client major customizations. The problem is, each client has its own billing system--some legacy, some more modern--and there is no way for your development team to write a module to interface with each individual system. So, our approach will be to use scripting for the export module. This will allow our clients' in-house development teams to make changes to the export module on their own (or even rewrite the whole thing to their hearts' desire!) without having to even recompile the application. And, you guessed it, we'll use Python for our scripting (the solution and the scripts are attached).

Our first step is to actually build our point of sale application. Sparing all the technical details, I've created a simple Windows Form with a list of products, some fields for quantity, totals, etc., and a "Process" button. When the button is clicked, it will use our python script to send the order out to the billing system. To make things even more customizable, I'll also create an app.config file to store the location of the export python script.

Actually loading the python script is trivial--even more trivial than anything we discussed last week. We need nothing more than a call to the PythonEngine's ExecuteFile() method:

public static void Process(Batch order)
{
   // Do some stuff... Save to database, logs, etc.
   // Send outbound
   string exportScript = ConfigurationManager.AppSettings["ExportScript"];
   using (PythonEngine engine = new PythonEngine())
   {
      engine.ExecuteFile(exportScript);
      bool res = (bool)((IronPython.Runtime.Calls.PythonFunction)engine
         .Globals["Export"]).Call(order);
   }
}

And viola, we're finished with our C# code. We can package this and send it our for our clients. Just to be nice, we'll also provide two simple export scripts. One will be a flat file format that will be dropped off for a legacy system to pick up, and the other will generate simple XML for a more modern system.

Here is our first script:

def Export(batch):
   f = file('export.txt', 'a')
   f.write('BATCH BEGIN [[')
   f.write(str(batch.SubTotal) + '|' + str(batch.Tax) + '|' + str(batch.Total) + '\r\n')
   for item in batch.Items:
      f.write(item.Description + '\r\n')
      f.write('BATCH END ]]\r\n')
   f.close()
   return True

When we run this a couple of times, we get the following output:

BATCH BEGIN [[1.0|0.0850|1.0850 
Mountain Dew 
Mountain Dew 
BATCH END ]] 
BATCH BEGIN [[56.99|4.84415|61.83415 
Mountain Dew 
Mountain Dew 
Arrested Development (DVD) (entire series) 
BATCH END ]]   

And we'll also provide a script that exports it in a simple XML format:

def endl(file):
   file.write('\r\n')
def Export(batch):
   f = file('export.xml', 'a')
   f.write('<batch ')
   f.write('subtotal="'+str(batch.SubTotal)+'" ')
   f.write('tax="'+str(batch.Tax)+'" ')
   f.write('total="'+str(batch.Total)+'">')
   endl(f)
   if(len(batch.Items) == 0):
      f.write('\t<items />')
      endl(f)
   else:
      f.write('\t<items>')
      endl(f)
      for item in batch.Items:
         f.write('\t\t<item description="'+item.Description+'" />')
         endl(f)
      f.write('\t</items>')
      endl(f)
   f.write('</batch>')
   endl(f)
   f.close()
   return True  

This gives us the following output:

<batch subtotal="42.0" tax="3.5700" total="45.5700">
   <items>
       <item description="DVD Player" />
      <item description="Novelty Frisbee" />
      <item description="Novelty Frisbee" />
      <item description="Novelty Frisbee" />
      <item description="Novelty Frisbee" />
   </items>
</batch>
<batch subtotal="19.75" tax="1.67875" total="21.42875">
   <items>
      <item description="Novelty Frisbee" />
      <item description="Novelty Frisbee" />
      <item description="Novelty Frisbee" />
      <item description="Nebraska Replica License Plate" />
      <item description="Erick Dampier jersey (XXL)" />
      <item description="Erick Dampier jersey (XXL)" />
   </items>
</batch>    

And these are just two of the possibilities. Our clients can interact with their external system in any way imaginable--TCP, Message Queue, Web Service, Database--anything that is possible with .NET or python can be done.

Our last consideration is one of efficiency. It would be nice if we could save our compiled script in an assembly and use the pre-compiled version as long as the script is not updated. IronPython allows us to easily create a DLL with our python script using the IronPython.CodeDom namespace, but it is difficult to invoke the compiled code in C#, if it is even possible. A possible workaround may be to write a python script that references the assembly and invoke that script instead. I'll let you know if I ever get that to work.

PythonInterface.zip (15.66 kb)



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 10, 2008 19:03 by swilliams

Last time, we tweaked our code to make it a little easier to understand and maintain. So that means we get to dirty it up again!  Our current object model has very simple mapping of one table to one class, with no associations between them. In the real world, this doesn't happen too often (and if it does, you are probably doing something wrong). A relational database has relations. Crazy, yes, but it means our model must be able to handle that.

Let's say then, that the Person object can possess all of the TpsReport objects they have created. To represent that, we'll need to update three things, our table structure, the classes, and the mapping file.

More...

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 7, 2008 22:44 by jpager

I don't know about you, but I am a fan of python. It has the advantages of flexibility that come from weakly typed languages, but maintains many of the functions of typical object-oriented languages. Though it feels like a scripting language, you can even write fully-featured standalone applications if you feel so inclined. So, naturally, I thought it would be fun to explore the possibility of using Python with .NET.

The de-facto standard .NET implementation of Python is IronPython. IronPython is a Python implementation that is written in .NET, and has use of all of the .NET CLR functionality. This allows us a couple of possibilities. We can use it as a python interpreter that has access to .NET functionality (for example, Windows Forms). However, as Scott has pointed out, if you're looking for a Python interpreter, you might as well use the native one, and if you're writing a .NET application, you might as well use C#. The other way we can use IronPython is purely as a scripting language that can be embedded in a C# (or VB, if you swing that way) application. (Particular ways to use scripting in .NET, while perhaps the most practical aspect of this discussion, will be reserved for some other time. My focus will be nothing more than using IronPython in a C# application.) So, without further ado...

Using IronPython in C#

At the center of the IronPython module is the PythonEngine object. So, the first thing we need to do is import our IronPython dll and create our PythonEngine object. Let's start by importing the IronPython.Hosting namespace:

using IronPython.Hosting;  

We create our object like so:

     using (PythonEngine engine = new PythonEngine()) {
     }  

Now that we have our PythonEngine, we can explore some of its basic functions.

The most basic function of PythonEngine is the Evaluate() method. Evaluate simple executes a single Python expression (note: by this I really mean expression, not statement. If you try an assignment, it will complain about bad python syntax.) and returns the result as an object (there is also a strongly-typed version, EvaluateAs, which I will use in my examples).

Let's try approximating PI using a python expression:

     double pi = engine.EvaluateAs<double>("4/1.0 - 4/3.0 + 4/5.0 - 4/7.0 + 4/9.0 "
          + "- 4/11.0 + 4/13.0 - 4/15.0 + 4/17.0 - 4/19.0 + 4/21.0 - 4/23.0 + 4/25.0 "
          + "- 4/27.0 + 4/29.0 - 4/31.0 + 4/33.0 - 4/35.0 + 4/37.0 - 4/39.0 + 4/41.0 "
          + "- 4/43.0 + 4/45.0 - 4/47.0 + 4/49.0 - 4/51.0");   

When we check the value of our pi variable, we get the value 3.1031453128860127, just as we expect.

Obviously, our value of pi is a little off, so we probably want to use the value of pi in python's math module. So, let's change our expression to this:

     double pi2 = engine.EvaluateAs<double>("math.pi"); 

If you try this, you'll get a runtime error: PythonNameErrorException: name 'math' not defined (and yes, the Exception class is "PythonNameErrorException"). This brings us to our next feature of the PythonEngine: Import. To get this to work, we need to import the math module, like so:

     engine.Import("math");
     double pi2 = engine.EvaluateAs<double>("math.pi"); 

Now, as we would expect, our pi2 variable now contains the value 3.1415926535897931. If you want to use your native python implementation's modules, you need to add those modules' path to your PythonEngine before it could find them:

     engine.AddToPath("C:\\Python25\\Lib");  

Let's move on to something a little more complicated: CreateMethod<TDelegate>(). CreateMethod is a strongly-typed function that returns a delegate. So, obviously, we need to define our delegate, with a contract that the function must adhere to:

     public delegate string DoSomethingDelegate (string param); 

CreateMethod has four overloads, but the one we'll deal with is the one that takes a python statement as the first parameter and a list of type names (the function signature) as the second:

     List<string> _params = new List<string>(new string[]{"param"});  
     DoSomethingDelegate function = engine.CreateMethod<DoSomethingDelegate>(@"
return 'Did you say \'' + param + '?\''  
          ", _params); 
     string rtn = function("TEST"); 

The last feature we'll look at is PythonEngine's Execute method. Execute is pretty self-explanatory--it simply executes Python code. The difference between Execute and the previous functions we've discussed is that Execute does not return anything--it only has side effects. It is important to understand that the PythonEngine works similarly to a native Python shell: any names that are defined while executing code are stored in the engine for future use. That is, if you define a name when you call Execute(), that name will be available to every subsequent Execute() call. Here is a simple example:

      engine.Execute(@"
def Foo():
     return 'Bar'
          ");
     string foo = engine.EvaluateAs<string>("Foo()"); 

In our execute() call, we defined a function called Foo(), and then referenced that same function when we called EvaluateAs().

Next, we'll actually call one of our Python functions from C# code. All of the global names in our PythonEngine are publicly accessible through the PythonEngine's Globals property. Any name that is a function is represented by the C# type IronPython.Runtime.Calls.PythonFunction, which has a method called, aptly enough, Call():

      engine.AddToPath("C:\\Python25\\Lib");
     engine.Import("os");
     engine.Execute(@" 
def RunCommand(command):
     p = os.popen(command)
     output = p.read()
     return output
          ");
     string ipconfig = (string)((IronPython.Runtime.Calls.PythonFunction)engine.Globals["RunCommand"])
          .Call(new object[] { "ipconfig" }); 

This does nothing more than create a process with the command sent through the parameter (which in this case is ipconfig) and read the output stream of the process. Because it uses the native Python os module, I added the path to that module to the PythonEngine's path. After this code executes, the ipconfig variable contains the output of the Windows ipconfig utility.

Now, let's put this to use and create something with it. We'll build a simple web form containing a panel, a text box, and a button. When the button is clicked, the command in the text box will be executed, and the output displayed in the panel (Disclaimer: Whatever you do, do not deploy this page to a network facing web site, for reasons that should be obvious to you).

Here's a snippet of our .aspx page:

     <asp:Panel ID="pnlOutput" runat="server" />
     <asp:TextBox ID="txtCommand" runat="server" Width="600" />
     <asp:Button ID="btSubmit" Text="Execute" runat= server  /> 

Here's our button's event handler:

     void btSubmit_Click(object sender, EventArgs e)
     {
          using (PythonEngine engine = new PythonEngine())
          {
               engine.AddToPath("C:\\Python25\\Lib");
               engine.Import("os");
               engine.Execute(@"
def Execute(command):
     pipe = os.popen(command)
     return pipe.read()
                    ");
               PythonFunction command = (PythonFunction)engine.Globals["Execute"];
               string res = (string)command.Call(new object[] { txtCommand.Text });
               pnlOutput.Controls.Add(new LiteralControl("<pre>" + res + "</pre>"));
          }
     } 

And there you have it. Try it out and play with it; we've only barely touched the possibilities.



Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 2, 2008 08:19 by mcollins

ASP.NET AJAX in Action by Alessandro Gallo, David Barkol, and Rama Krishna Vavilala, is one of the best books that I've seen covering AJAX from the Microsoft perspective.  Their book is wonderful at giving the reader the exact details that they need to know about how to take advantage of Microsoft's AJAX technologies on both the client and the server, as well as getting the client and the server to work together.

When you think of Microsoft AJAX, most developers would probably think first of the UpdatePanel control in ASP.NET.  Using UpdatePanel is easy.  The developer drops it onto a page, adds one or more ASP.NET server controls as content for the UpdatePanel, and instantaneously those nasty page refreshes go away.

What most developers, in my opinion, are not thinking about when they hear the term Microsoft AJAX is the rich client-side library written in JavaScript that allows developers to do so much more on the client side.  The authors recognize this problem and spend significant time explaining the richness of the JavaScript environment before introducing the concept of the UpdatePanel control.  The end result of this book is that the developer has started to master the client-side development aspects of developing with JavaScript and calling web services on the server by the time the developer starts looking into the server-side aspects of AJAX.

Special attention in the second half of the book is placed on the component and control model of the Microsoft AJAX library.  Developers will learn how to create new non-visual JavaScript components, behavior extenders in JavaScript, and new JavaScript-based HTML controls.  Once the client-side aspects of these components and controls have been covered, the authors then explain and demonstrate how to wrap your new JavaScript components in ASP.NET server controls to enable the drag-and-drop designer experience.

This book is easy to read.  I found very few errors in it (none that I can actually recall).  Overall, this book really helped me to better understand and advance my use of Microsoft's AJAX technologies and pushed me into spending a lot more time learning how to develop in JavaScript on the browser, something which I admittedly was not very good at.  I definitely recommend buying this book the next time that you're at Borders.

Amazon.com: ASP.NET AJAX in Action

ISBN: 1933988142
ISBN-13: 9781933988146

Technorati tags: , , , ,


Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted on March 1, 2008 07:57 by mcollins

In this post, I wanted to introduce you to a new feature that is definitely more than welcome in .NET 3.5: auto-implemented properties.  Auto-implemented properties are a shorthand notation for declaring simple properties in classes.

Let's say that I'm developing a class representing a student for an educational software package.  In the past, I would have defined the class using the following code:

   1: public enum Gender {
   2:     Female,
   3:     Male
   4: }
   5:  
   6: public class Student {
   7:     private DateTime birthDate;
   8:     private string firstName;
   9:     private Gender gender;
  10:     private string lastName;
  11:  
  12:     public DateTime BirthDate {
  13:         get { return birthDate; }
  14:         set { birthDate = value; }
  15:     }
  16:  
  17:     public string FirstName {
  18:         get { return firstName; }
  19:         set { firstName = value; }
  20:     }
  21:  
  22:     public Gender Gender {
  23:         get { return gender; }
  24:         set { gender = value; }
  25:     }
  26:  
  27:     public string LastName {
  28:         get { return lastName; }
  29:         set { lastName = value; }
  30:     }
  31: }

This is a lot of code for a simple class.  Fortunately, in .NET 3.5, we can reduce this amount of code and make it even simpler:

   1: public enum Gender {
   2:     Female,
   3:     Male
   4: }
   5:  
   6: public class Student {
   7:     public DateTime BirthDate { get; set; }
   8:     public string FirstName { get; set; }
   9:     public Gender Gender { get; set; }
  10:     public string LastName { get; set; }
  11: }

Using