Strategy Pattern

Posted: December 1, 2010 in Design Patterns

The Strategy Pattern is a GOF (Gang of Four) behavioral pattern where the intent is to “define a family of algorithms, encapsulate each one, and make them interchangeable”.

This pattern gives the client the flexibility to solve the same problem using different algorithms. The client can switch to any algorithm.

In the code below, StrategyContext class accepts the SortType parameter which gives the client the flexibility to select the algorithm without knowing the internal implementation. Each algorithm is implemented as a separate class and its contract is defined by an interface. Any new algorithm to be introduced has to obey the contract defined by the interface.

————————————————————————————-
Source Code
————————————————————————————-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
// Interface with alogorithm definition
public interface ISort
{
void Sort();
}

// Class encapsulating algorithm
public class BubbleSort : ISort
{

#region ISort Members

public void Sort()
{
Console.WriteLine(“Bubble Sort”);
}

#endregion
}

public class ShellSort : ISort
{

#region ISort Members

public void Sort()
{
Console.WriteLine(“Shell Sort”);
}

#endregion
}

// Context class for clients to interact and call appropriate
// strategy algorithm
public class StrategyContext
{
private ISort sortType;

public StrategyContext()
{
}

public StrategyContext(ISort _sortType)
{
sortType = _sortType;
}

public ISort SortType
{
get { return sortType; }
set { sortType = value; }
}

// Execute the algorithm
public void PerformAction()
{
if(sortType != null)
sortType.Sort();

else
{
throw new Exception(“Sort type not defined for the Context”);
}
}

}

public class Client
{
static void Main()
{

StrategyContext context = new StrategyContext(new BubbleSort());
context.PerformAction();

context = new StrategyContext();
ShellSort shellSort = new ShellSort();
context.SortType = shellSort;
context.PerformAction();

Console.ReadLine();
}
}
}

Advertisements

Factory and Abstract Factory patterns are creational patterns.

Factory pattern – “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.” This is a loosely coupled model as it returns an instance of one of several possible classes, depending on the data provided to it.The calling object can simply request the factory to return the object it needs, without actually knowing how to create that object i.e. through interface.In order to add or remove a new module, one only needs to modify the decision code in the factory.

Abstract factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. This is one more level of abstraction above the factory pattern. Abstract factory is a factory object that returns one of the several factories.

Code snippet for both patterns is as seen below :

——————————————————————————————————————————————
Factory pattern sample

using System;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
IConnection connection1 = ConnectionFactory.GetConnection(ConnectionType.Sql);
connection1.Connect();

IConnection connection2 = ConnectionFactory.GetConnection(ConnectionType.Oracle);
connection2.Connect();

Console.ReadLine();
}
}

public enum ConnectionType
{
Sql = 0,
Oracle = 1

// Add new Providers
// Provider = 2….
} ;

// Factory class to create objects at runtime based on user selection
public class ConnectionFactory
{

public static IConnection GetConnection(ConnectionType connType)
{
if (connType == ConnectionType.Oracle)
return new OracleConnection();

// need to add more cases if our Connection providers are more
// else if(connType == )
//return new Provider();

// default
return new SqlConnection();
}
}

// Common factory interface for interacting with classes at runtime
public interface IConnection
{
void Connect();
void DisConnect();
}

public class SqlConnection : IConnection
{

#region IConnection Members

public void Connect()
{
Console.WriteLine(“Connected to Sql”);
}

public void DisConnect()
{
Console.WriteLine(“Disconnected from Sql”);
}

#endregion
}

public class OracleConnection : IConnection
{

#region IConnection Members

public void Connect()
{
Console.WriteLine(“Connected to Oracle”);
}

public void DisConnect()
{
Console.WriteLine(“Disconnected from Oracle”);
}

#endregion
}

}

——————————————————————————————————————————————
Abstract Factory Pattern

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
IBreadFactory indianBreadfactory = new IndianBreadFactory();
IndianVegBread indianVegBread = indianBreadfactory.GetBread(0) as IndianVegBread;
IndianNonVegBread indianNonVegBread = indianBreadfactory.GetBread(1) as IndianNonVegBread;

IBreadFactory americanBreadFactory = new AmericanBreadFactory();
AmericanPlainBread plainBread = americanBreadFactory.GetBread(0) as AmericanPlainBread;
AmericanBreadWithCheese cheeseBread = americanBreadFactory.GetBread(1) as AmericanBreadWithCheese;

Console.ReadLine();
}
}

// Common factory interface for interacting with classes at runtime
public interface IBread
{
void Bake();
}

public interface IBreadFactory
{
IBread GetBread(int i);
}

// First Factory
public class IndianBreadFactory : IBreadFactory
{
public IBread GetBread(int i)
{
IBread bread;
if (i == 0)
bread = new IndianVegBread();

bread = new IndianNonVegBread();
return bread;
}
}

// Second Factory
public class AmericanBreadFactory : IBreadFactory
{
public IBread GetBread(int i)
{
IBread bread;
if (i == 0)
bread = new AmericanPlainBread();

bread = new AmericanBreadWithCheese();
return bread;
}
}

// American Bread products
public class AmericanPlainBread : IBread
{
public void Bake()
{
Console.WriteLine(“American Plain Bread baked”);
}
}

public class AmericanBreadWithCheese : IBread
{
public void Bake()
{
Console.WriteLine(“American Bread With Cheese baked”);
}
}

// Indian Bread Products
public class IndianVegBread : IBread
{
public void Bake()
{
Console.WriteLine(“Indian Veg Bread baked”);
}
}

public class IndianNonVegBread : IBread
{
public void Bake()
{
Console.WriteLine(“Indian Non Veg Bread baked”);
}
}
}

Builder Design Pattern

Posted: December 1, 2010 in Design Patterns

Builder pattern falls under the Creational design pattern. The Builder pattern separates the construction phase of a complex object from its representation so that the same construction logic can be used for different objects and the output representation may be different. Using the same construction logic, we will get different object representations.

I have used the scenario for creation of reports as the example. We can create either PDF or Excel reports. ReportBuilder class has the construction logic for building the individual parts of the Report. Director takes
ReportBuilder as argument and then defines the sequence for building the report. The end result is the Report which can either be Excel or PDF.

The code snippet for this pattern is as seen below :

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
// Create a PDF report
ReportBuilder pdfBuilder = new PDFBuilder();
Director dir = new Director();
Report pdfReport = dir.GenerateReport(pdfBuilder);

// Print content
Console.WriteLine(pdfReport.Header);
Console.WriteLine(pdfReport.Content);
Console.WriteLine(pdfReport.Footer);

// Create a Excel report
ReportBuilder excelBuilder = new ExcelBuilder();
Report excelReport = dir.GenerateReport(excelBuilder);

// Print content
Console.WriteLine(excelReport.Header);
Console.WriteLine(excelReport.Content);
Console.WriteLine(excelReport.Footer);

Console.ReadLine();
}
}

// Report or Product
public class Report
{
public string ReportType;
public string Header;
public string Footer;
public string Content;

}

// Report Builder – Builder is responsible for defining
// the construction process for individual parts. Builder
// has those individual processes to initialize and
// configure the report.
public abstract class ReportBuilder
{
public Report report;
public void CreateReport()
{
report = new Report();
}
public abstract void SetReportType();
public abstract void SetHeader();
public abstract void SetFooter();
public abstract void SetContent();

public Report DispatchReport()
{
return report;
}

}

// PDF Report class
public class PDFBuilder : ReportBuilder
{

public override void SetReportType()
{
report.ReportType = “PDF”;
}

public override void SetHeader()
{
report.Header = “PDF Header”;
}

public override void SetFooter()
{
report.Footer = “PDF Footer”;
}

public override void SetContent()
{
report.Content = “PDF Content”;
}

}

// Excel Report class
public class ExcelBuilder : ReportBuilder
{

public override void SetReportType()
{
report.ReportType = “Excel”;
}

public override void SetHeader()
{
report.Header = “Excel Header”;
}

public override void SetFooter()
{
report.Footer = “Excel Footer”;
}

public override void SetContent()
{
report.Content = “Excel Content”;
}
}

///

/// Director takes those individual processes from the builder
/// and defines the sequence to build the report.
///

public class Director
{
public Report GenerateReport(ReportBuilder reportBuilder)
{
reportBuilder.CreateReport();
reportBuilder.SetReportType();
reportBuilder.SetHeader();
reportBuilder.SetContent();
reportBuilder.SetFooter();
return reportBuilder.DispatchReport();
}
}
}

Singleton and Prototype patterns fall under Creational Design Patterns which deal with object creation.

Singleton – The purpose behind Singleton pattern is to ensure that one and only instance of the class is present at any time. We usually create the instance of the object on demand i.e delay loading and then ensure that once it is created, no more instances are allowed to be created.

Classical example would be a Menu in case of Winows application. Menu will be common for all pages and we make sure it is not recreated again and again.

Basic fundaa behind singleton is to have a class with private constructor and expose a static getter property which will control the object creation…for first access, object has to be created and then for subsequent access, the same object is returned back. For thread safety purpose, we can use lock.

Prototype pattern – The intent behind the usage of Prototype pattern is for creation of object clone.

The cloning again falls under two categories : shallow and deep. Shallow copy is returned by using MemberwiseClone dotnet method. A shallow copy copies only the elements, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new object point to the same objects that the references in the original object points to. In contrast, a deep copy of an object copies the elements and everything directly or indirectly referenced by the elements.

Example below will explain the difference between shallow and deep clone clearly.

Code for the explanation of both the patterns :

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DesignPatterns
{
public class CreationalPatterns
{

public static void Main()
{
// Prototype test
ProtoType p = new ProtoType();
TestA a11 = new TestA();
a11.myList.Add(“1”);
a11.myList.Add(“2”);
a11.name = “Testing”;

TestB b11 = new TestB();
b11.i = 10;
a11.b1 = b11;

p.a1 = a11;

ProtoType p1 = p.ShallowClone();
ProtoType p2 = p.DeepClone();

// Both have values copied now change a bit
a11.myList.Add(“3”);
a11.name = “Testing Again after adding 3”;

// Deep copy will show original values whereas
// Shallow copy shows current values
string nameA1 = p1.a1.name;
string nameA2 = p2.a1.name;

// Singleton Test
// At any moment, only and one instance of the Menu is created
MenuInstance menu = MenuInstance.myMenu;

Console.ReadLine();

}
}

// Singleton class – only one instance
// Has private constructor and a property is exposed
// when trying to access the property, check is made if instance
// is already created and if yes, it is returned else instance is created
// and then returned. This is called lazy instantiation.
// Lock is used to prevent thread synchronication issues…if two threads
// try to create instances simultaneously
public class MenuInstance
{
private static MenuInstance _myMenu;
private static object myLock = new object();
private MenuInstance()
{
}

public static MenuInstance myMenu
{
get
{
// Lock is acquired each time we try to access the instance
lock (myLock)
{
if (_myMenu == null)
{
_myMenu = new MenuInstance();
}
}
return _myMenu;
}
}
}

///

/// Prototype pattern implemenatation
///

[Serializable]
public class ProtoType
{

public TestA a1 { get; set; }

// Creates a shallow copy
// Same copy of the referenced object is taken.
// The original object and its clone refer to the same object.
public T ShallowClone()
{
return (T)this.MemberwiseClone(); ;
}

// Creates a deep copy
// A new copy of the referenced object is created
// The original object and its clone refer to different objects.
public T DeepClone()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T) formatter.Deserialize(stream);
stream.Close();
return copy;
}
}

[Serializable]
public class TestA
{
public List myList = new List();
public string name = string.Empty;
public TestB b1;
}

[Serializable]
public class TestB
{
public int i;
}

}

Design Patterns

Posted: November 30, 2010 in Design Patterns

I am great fan of Design pattern and have been trying hard to understand GOF patterns. Design patterns are the solutions to most common problems faced in the software industry. They are proven solutions to a problem and are again scenario dependent. They are just templates for most commonly occuring problems. As a software engineer, we should not try to code according to a specific pattern in our application just to learn it. We are expected to understand the intent behind a specific pattern and then try to fit that pattern into our application based on needs.

They are broadly classified into 3 types :

1. Creational patterns – deals with object instantiation
2. Structural patterns – deals more with object composition to address functionalities.
3. Behavior patterns – deals with communication between objects.

GOF patterns are as listed below :

Creational Patterns

1. Abstract Factory : Creates an instance of several families of classes
2. Builder : Separates object construction from its representation
3. Factory : Creates an instance of several derived classes
4. Prototype : A fully initialized instance to be copied or cloned
5. Singleton : A class of which only a single instance can exist

Structural Patterns

1. Adapter : Match interfaces of different classes
2. Bridge : Separates an object’s interface from its implementation
3. Composite : A tree structure of simple and composite objects
4. Decorator : Add responsibilities to objects dynamically
5. Facade : A single class that represents an entire subsystem
6. Flyweight : A fine-grained instance used for efficient sharing
7. Proxy : An object representing another object

Behavioral Patterns
1. Chain of Resp : A way of passing a request between a chain of objects
2. Command : Encapsulate a command request as an object
3. Interpreter : A way to include language elements in a program
4. Iterator : Sequentially access the elements of a collection
5. Mediator : Defines simplified communication between classes
6. Memento : Capture and restore an object’s internal state
7. Observer : A way of notifying change to a number of classes
8. State : Alter an object’s behavior when its state changes
9. Strategy : Encapsulates an algorithm inside a class
10. Template : Defer the exact steps of an algorithm to a subclass
11. Visitor : Defines a new operation to a class without change

IComparer / IComparable are interfaces used to compare two objects. The implementing class has to define the logic for sorting. It provides a way to customize the sort order of a collection.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Exception as there is no IComparable implementation for Sorting. Exception message – Failed to compare two elements in the array
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A", Age = 25, Address = "Test StreetA" },
new Emp { Name = "A", Age = 26, Address = "Test StreetA1" },
new Emp { Name = "B", Age = 25, Address = "Test StreetB" },
new Emp { Name = "C", Age = 26, Address = "Test StreetC" },
new Emp { Name = "Z", Age = 25, Address = "Test StreetZ" },
new Emp { Name = "D", Age = 26, Address = "Test StreetD" }});
empList.Sort();

}
}

public class Emp
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}

Implementation of IComparable in WPF. Here, we implement the CompareTo method and sort the Emp objects based on Age property.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A25", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "B35", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "C15", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "D45", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "E5", Age = 5, Address = "Test StreetE5" }});
empList.Sort();

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

#region IComparable Members

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

#endregion
}
}

Note::

List test = new List();
test.Add("B");
test.Add("C");
test.Add("A");
test.Sort();

This will work because by default List and Array implement IComparable.
But below example this won’t work.

public class Emp
{
public string Name { get; set; }
}

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "C25"}, new Emp { Name = "B35"},new Emp { Name = "A15"}});

empList.Sort();

C# compiler is not smart enough to figure out which instance of type “Emp” should come first etc.

IComparer interface :

But sometimes, we may need to sort a list of objects when class does not implement IComparable<> interface and also we may need various kinds of sorting on that class like:

1. Sort Emp by Age in Ascending Order
2. Sort Emp by Age in Descending Order
3. Sort Emp by Name

To solve this problem, .NET provides a special interface called IComparer<> which has a method Compare(), takes two object parameters X, Y and returns an int. Use of IComparer<> interface tells List how exactly you want to sort.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A25", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "B35", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "C15", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "D45", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "E5", Age = 5, Address = "Test StreetE5" }});

// Default sort as defined by IComparable
empList.Sort();

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox.Items.Add(listTemp);
}

// Create IComparer instance
Emp_SortByAgeByDescendingOrder descSort = new Emp_SortByAgeByDescendingOrder();

// Specify the type
empList.Sort(descSort);

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox1.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

}

class Emp_SortByAgeByDescendingOrder : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
if (x.Age < y.Age) return 1;
else if (x.Age > y.Age) return -1;
else return 0;
}

#endregion
}

class Emp_SortByName : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
return string.Compare(x.Name, y.Name);
}

#endregion
}
}

Special case :: If we have both IComparer and IComparable implemented

Sort will take place based on IComparer logic first and then followed by IComparable logic.

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "A", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "B", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "B", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "C", Age = 5, Address = "Test StreetE5" }});

// Create IComparer instance
// IComparer sorts by Name asc
// IComparable sorts by Age desc
// Sort should be Name asc and Age desc
Emp_SortByName descSort = new Emp_SortByName();

// Specify the type
empList.Sort(descSort);

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox1.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

}

class Emp_SortByName : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
return string.Compare(x.Name, y.Name);
}

#endregion
}

DLR and Iron Python

Posted: September 7, 2010 in Dotnet basics

 

DLR stands for Dynamic Language Runtime. Dotnet 4.0 supports dynamic language interaction along with static languages for which CLR extends support. Currently supported languages are Ruby and Python. The Dynamic Language Runtime enables language developers to more easily create dynamic languages for the .NET platform. In addition to being a pluggable back-end for dynamic language compilers, the DLR provides language interop for dynamic operations on objects. The DLR has common hosting APIs for using dynamic languages as libraries or for scripting in your .NET applications.

IronPython is an implementation of the Python programming language targeting the .NET Framework and Mono ( A cross platform open source Dotnet framework currently targeted for Linux). IronPython is written entirely in C#. Python is implemented on top of the Dynamic Language Runtime (DLR), a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages. Python is mainly used by system administrators for executing scripts who do not have knowledge about .Net. Dotnet has extended support for IronPython in order to resolve this dependency so that programmers and administrators can work in conjunction.

The first step to getting started is to actual download IronPython. The project is hosted on CodePlex with all of the source code available. After the IronPython installation, its interpreter and its libraries will be installed in your Program Files directory. The interpreter is installed in ipy.exe, where ipy is pronounced “Eye-Pie.” The interpreter remains dormant when you call Python from C#. Dotnet projects which want to use Python need to reference dlls.

Sample usage of Python from IronPython console

>>> import System
>>> from System.Collections import *
>>> h = Hashtable()
>>> h["a"] = "IronPython"
>>> h["b"] = "Tutorial"
>>> for e in h: print e.Key, ":", e.Value

Once you install Iron Python, there will be Visual Studio templates available for creating the projects. Creating a sample standalone file is the best option. Create some simple script file as seen below:

File Name : Test.py

def Simple():
print "Hello from Python"
print "Call Dir(): "
print dir()

File Name : pyt.py

def factorial(n):
"factorial(n) -> returns factorial of n"
if n <= 1: return 1
return n * factorial(n-1)

Place these files in your project folder and set "Build Action" to "Content" and "Copy To Output Directory" to "Copy Always".

Now, create another application which will act as the hosting environment. Reference dlls from Program Files \ Python folder namely IronPython.dll, IronPython.Modules.dll, Microsoft.Dynamic.dll, Microsoft. Scripting.dll and Microsoft. Scripting.Debugger.dll .
Now that you have your project set up correctly you need to do two things:

1. Write or find a script containing Python code that you want to run
2. Write C# code to call the script.

Listing 2 shows a very simple IronPython script that contains a single method called Simple() that writes a few strings to a console window. Save this script to a file called Test.py, and add it to your project, as shown in Figure 2. There are several ways to do this. One is to right click on your project in the Solution Explorer, and choose Add | New Item. Add a text file, and call it Test.py. Click on the new node when it is added to your project, and set its Copy to Output Directory property to Copy Always.
Your class file from where you call the Python script will be as seen below.

Note:: The below code didn’t work along with IronPython 2.7. So, i had to setup 2.6 version and then it worked fine.

There are two examples – the first just calls one method from Python script and the second calls method, passes a parameter and captures the return value.

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using System.IO;

namespace PythonHost
{
class Program
{
static void Main(string[] args)
{
//// Creates the python runtime
ScriptRuntime ipy = Python.CreateRuntime();

//// The dynamic keyword is needed
//// here because Python is an interpreted
//// scripting language where calls are bound
//// at run time, not at compile time.
//// There is no simple or practical way to
//// bind calls to Python at compile time
//// because Python is designed to be a
//// dynamic language which is resolved
//// at runtime.
dynamic test1 = ipy.UseFile("Test.py");

// Call function
test1.Simple();

// Sample for passing parameters to Python and getting value
dynamic test2 = ipy.UseFile("pyt.py");
int p = test2.factorial(5);
}
}
}

If all is well…you should be able to run your application.

Also, using 2.7 version I was able to setup SilverLight runtime in conjunction with Python.

I setup Silverlight class library and copied the same two scripts and added the following code to setup the execution.

using System.Windows.Controls;
using Silverlight = Microsoft.Scripting.Silverlight;

namespace SilverlightApplication5
{
public partial class MainPage : UserControl
{
public MainPage() {
InitializeComponent();

var runtime = Silverlight.DynamicEngine.CreateRuntime();
var python = runtime.GetEngine("python");
dynamic script = runtime.UseFile("pyt.py");
int p = script.factorial(5);

script = runtime.UseFile("Test.py");
script.Simple();
}
}
}

For Sliverlight with 2.7 version of IronPython, i didn’t face any issues….