Saturday, June 23, 2007

How to build a Silverlight control?

Very recent I build a web top in Silverlight. As this is a new technology I have to build lot of control for myself. And I find some difficulty to building control. As I have very short memory I write my findings in my blog so that they will be accessible from anywhere…

I build my project with Orcas so that the entire feature I am writing related to Orcas. Right Button click to your Silverlight project and click add New Item; from Silverlight project choose Silverlight User Control. Give a name to your control, let Button so you will get two file

  1. Button.xaml
  2. Button.xaml.cs

Button.xaml is used to render your graphics and Button.xaml.cs is used as code behind file. By default it will gives you a canvas and you can draw your necessary items. Add your necessary items to render the button. Let I add two more canvas inside it. And I give them name OuterCanvas and InnerCanvas.

In default page given with Silverlight project you can find any Control by

this.FindControl(“ControlName”);

But in case of control you cannot find any control by

this.FindControl(“ControlName”);

You have to write two lines in your control’s constructor.

Stream ioStream = typeof(Button).Assembly.GetManifestResourceStream("Button.xaml");

FrameworkElement fe= this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());

And now you have to write

fe.FindControl(“ControlName”);

Now you can subscribe any event, and what ever you want.

Again you can add other rendering item by code. This is very simple and you don’t have to write any xaml for this.

TextBlock block = new TextBlock();

block.SetProperty<double>(Canvas.LeftProperty,5);

block.SetProperty<double>(Canvas.TopProperty,5);

Canvas innerCanvas = fe.FindControl(“innerCanvas”) as Canvas;

innerCanvas.Children.Add(block);

This is as simple as it is…

Cautions:

1. Don't try to subscribe GetFocus() this is restricted only for root element.

2. Don't make canvas full screen in any event it can be done only in MouseUpEvent and MouseDownEvent.

So, lets have fun with Silverlight.

Feel free to contact me for any convenience.

Wednesday, June 20, 2007

Consume Web service from Silverlight

Calling web service from silverlight is as simple as in C#. In the following article I build a web service and call the web service from Microsoft silverlight. And I will discuss the the problem in the road to these sort of things.

First I build a Web service:

Add a ASP.NET Web Service application in your solution, and you will get an asmx file, write the services you want to expose in the service class. Here I write a simple service which shows child directory and files according to given parent directory.

All exposed service must have an attribute named [WebMethod].

As you want to call the web service from silverlight which is an scripting language you must add System.Web.Extension.dll into references and you must add the following attribute to your service class,

[System.Web.Script.Services.ScriptService]

So that you can call these services from any of the scripting language. These are the things all you have to do in web service project.

Now came to the silverlight application. Let we make a simple silverlight application which print the file and directory list in the canvas.

So you have to add web references to this web service. Mostly all there is an option find web services into this solution. And if your web service is not hosted in IIS then silverlight cannot use this web service. If the web service is hosted by runtime server then the port will be different other than 80, so silverlight handle it as different server and as it cannot handle cross domain call so you get an exception that you are trying to call cross domain services.

So, what you have to do is host your web services into IIS, and when you add web service reference you find web service from local host, and you will get the web service and hopefully you can call it without any exception. Adding web service reference will build a web service proxy in silverlight, you have to build an instance of these proxy and you can call these services in synchronous or asynchronous manner.

I write the following code in my default Page.xaml.cs in Page_load()

TextBlock block = new TextBlock();

block.SetValue<double>(Canvas.LeftProperty,5);

block.SetValue<double>(Canvas.TopProperty,5);

block.FontSize = 10;

block.Foreground = new SolidColorBrush(Colors.White);

localhost.WebServiceProxy proxy = new localhost.WebServiceProxy();

try

{

FileSystemData[] data = proxy.Contents(@"C:\Content");

// FileSystemData is my defined structure

for (int index = 0; index < data.Length; index++)

block.Text += data[index].FileName + "\r\n";

}

catch (Exception ex)

{

block.Text += ex.Message;

block.Text += ex.StackTrace;

}

this.Children.Add(block);

// all the codes are so simple that I don't write description about that.

the following code will print the content of directory C:\Content or it will print the exception. And finally the last trick you have to do is not run this project by F5 or run button, because it runs from file system, so that once again you will get cross domain exception. Just create a virtual directory in IIS for your silverlight project and run from localhost, hopefully all these will work fine.

Nothing is new in calling web service from silverlight just you have careful about cross domain and script permission that's it.

Saturday, June 16, 2007

Another runtime Class/Type generator using System.CodeDom

Another simple way to generate runtime class using codeDom.

C# library exposed different compiler for runtime compilation and anyone can use it for runtime type generation.

System.CodeDom is a library for runtime compilation, you can compile any code written for any language.

Lets, generate same set of functionality in class using system.CodeDom

Recall,

I have a interface actually I have type which is an interface and I want to generate a class implementing that interface.

Original code should be :

//interface
public interface IEcho
{
string Echo(string message);

string NetworkEcho(string message);
}
//Implementer
public class EchoProxy : IEcho
{
public string Echo(string message);

public string NetworkEcho(string message);
}

now I write a method which will take the type of interface as parameter and return the object of dynamic class.

object GetObject(Type interfaceType)

{

StringBuilder codeBlockBuilder = new StringBuilder();

// take new string builder to generate code.

codeBlockBuilder.AppendLine("using System;");

codeBlockBuilder.AppendLine("using System.Collections.Generic;");

codeBlockBuilder.AppendLine("using System.Text;");

codeBlockBuilder.AppendLine("using Interface;");

codeBlockBuilder.AppendLine("using System.Net;");

// Add necessary library for the code.In common java synonym import this libraries.

codeBlockBuilder.AppendLine("class " + interfaceType.Name + "DynamicProxy : " + interfaceType.FullName);

// Declare the class, here I don't use any name space, that is all this type goes to global namespace.

codeBlockBuilder.AppendLine("{");

MethodInfo[] methods = interfaceType.GetMethods();

// Get list of method define in the namespace

for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++)

{

MethodInfo currentMethod = methods[methodIndex];

StringBuilder methodBuilder = new StringBuilder();

string typeName = currentMethod.ReturnType.FullName;

string declareString = null;

if (typeName == "System.Void")

// void is defined as System.Void which does not work as it is, so use void instead of System.Void

declareString = "void";

else

declareString = currentMethod.ReturnType.FullName;

methodBuilder.Append("public " + declareString + " " + currentMethod.Name + "(");

// define return type and method name.

for (int parameterIndex = 0; parameterIndex < currentMethod.GetParameters().Length; parameterIndex++)

{

methodBuilder.Append(currentMethod.GetParameters()[parameterIndex].ParameterType.FullName + " ");

methodBuilder.Append(currentMethod.GetParameters()[parameterIndex].Name);

if (parameterIndex < currentMethod.GetParameters().Length - 1)

methodBuilder.Append(", ");

}

// Here I build method parameter as defined in the interface..

methodBuilder.Append(")");

methodBuilder.AppendLine();

methodBuilder.AppendLine("{");

if (currentMethod.Name == "Echo")

{

methodBuilder.AppendLine("Console.WriteLine(\"Echo(Proxy)\");");

methodBuilder.AppendLine("return " + currentMethod.GetParameters()[0].Name + ";");

// return the parameter itself.

}

else if (currentMethod.Name == "NetworkEcho")

{

methodBuilder.AppendLine("Console.WriteLine(\"NetworkEcho(Proxy)\");");

methodBuilder.AppendLine("return " + currentMethod.GetParameters()[0].Name + " + \"[\" + Dns.GetHostName() + \"(\" + (Dns.GetHostByName(Dns.GetHostName())).AddressList[0].ToString() + \")]\";");

// Return the parameter appending network address.

}

methodBuilder.AppendLine("}");

codeBlockBuilder.AppendLine(methodBuilder.ToString());

}

codeBlockBuilder.AppendLine("}");

// Here ends my class generation, this is simple code so I don't describe it rigorously

Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();

// Take new Csharp provider class, this is the source of CSharp compiler.

System.CodeDom.Compiler.ICodeCompiler compiler = cp.CreateCompiler();

// Take new CSharp compiler, and assign it to the ICodeCompiler...

System.CodeDom.Compiler.CompilerParameters compilerParam = new System.CodeDom.Compiler.CompilerParameters();

// You can set different option for your compiler, with compiler parameter class.

compilerParam.GenerateInMemory = true;

// Generate the types in memory.

compilerParam.GenerateExecutable = false;

// Here is no executable start point, this is not executable.

compilerParam.ReferencedAssemblies.Add("system.dll");

compilerParam.ReferencedAssemblies.Add("Interface.dll");

// Add assembly to your runtime compiler.

System.CodeDom.Compiler.CompilerResults compilerResult = compiler.CompileAssemblyFromSource(compilerParam, codeBlockBuilder.ToString());

// Compile the code and get result from you runtime compiler

foreach (System.CodeDom.Compiler.CompilerError compilerError in compilerResult.Errors)

{

throw new Exception(compilerError.ErrorText);

}

// for each error I throw an exception.

if (compilerResult.Errors.Count == 0 && compilerResult.CompiledAssembly != null)

{

Type ObjType = compilerResult.CompiledAssembly.GetType(serviceClass.Name + "DynamicProxy");

// Now I am looking for my generated class

try

{

if (ObjType != null)

{

return Activator.CreateInstance(ObjType);

// If I found I create an object with activator and return that instance.

}

else

{

throw new Exception("Dynamic type not found.");

return null;

}

}

catch (Exception ex)

{

throw ex;

}

}

else

{

throw new Exception("Failed to compile");

return null;

}

// Others error handling

}

This is another way to generate runtime class, in this procedure you can generate runtime class but you cannot modify exiting class.

Again, you can save the code as well as compiled assembly.

So this is helpful for code generator, rather than dynamic proxy.

Again, this is very much slower than System.Reflection.Emit

So, it is better choice for code generation or assenbly generator because you don't have to write IL rather you are writing normal C# code.

Monday, June 11, 2007

3-Tier Architecture of Data Server on Grid: Implemented using Globus Toolkit

Grid System is one of the newest versions of distributed System. In a distributed System, we often hope to distribute the overheads of the entire system to different PCs. Parallel execution is one of the major features of Grid System as well as we can share RAM or any other resources. But it is quite challenging to design a data server on Grid. To get the full performance of a Grid System the traditional Database Management System (DBMS) fails and so here we propose a modified version of Data Server architecture using existing Database System. Also this implementation base paper includes some comparisons, figures and tables indicating the performance of the Data Server on Grid with the traditional DBMS. We have used Globus Toolkit in our implementation and all the terms in this paper are similar to the terms used on Globus Toolkit.

"published at GCA'07- The 2007 International Conference on Grid Computing and Applications"

ALCHEMI VS GLOBUS: A PERFORMANCE COMPARISON

Alchemi and the Globus Toolkit are open source software toolkits for implementing a Grid. Although both toolkits are designed for the same purpose, their architecture and underlying technology are completely different. Thus, a performance comparison of a Grid implementation in Alchemi with a similar Grid implementation in the Globus Toolkit will be interesting. We built a test bed to compare the performance of the two toolkits. This paper includes tables and graphs to illustrate the comparison.
published at
4th International Conference on Electrical and Computer Engineering, BUET, Dhaka, Bangladesh, Dec, 2006.

Implementation of Server on Grid System: A Super Computer Approach

The Internet technology has already changed the Information Society in profound ways, and will continue to do so. Nowadays many people foresee that there is a similar trajectory for the next generation of Internet - Grid Technology. As an emerging computational and networking infrastructure, Grid Computing is designed to provide pervasive, uniform and reliable access to data, computational and human resources distributed in a dynamic, heterogeneous environment. Also the development of Grid Security provides a secured field for work. That’s why; we have used the Grid Technology for implementing a server that response to many Clients for any database queries or any other database applications. Our design provides single level distribution of Grid Applications that make the faster response time and faster throughput than the normal server application and even that of distributed application. Here we have used the open source software “Alchemi” in all through our work. This document summarizes the design and implementation of a server using Grid Technology and compares its performance.

published at 15th International Conference of Information System and Development, Budapest, Hungary, Aug, 2006.

Runtime Type/Class generator or modifier with System.Reflection.Emit

Hi,
C# gives you so much flexibility to generate runtime type or modify any type at runtime.
Recently i explore runtime type generation or modification.
Hope every body found it interesting.

What i want to do is,
I have a interface actually i have type which is an interface and I want to generate a class implementing that interface.

Original code should be :

//interface
public interface IEcho
{
string Echo(string message);
}
//Implementor
public class EchoProxy : IEcho
{
public string Echo(string message);
}

now I write a method which will take the type of interface as parameter and return the object of dynamic class.


object GetObject(Type interfaceType)
{
AppDomain proxyDomain = Thread.GetDomain();
// Get the domain of the current thread
AssemblyName proxyAssemblyName = new System.Reflection.AssemblyName();
// You must create a runtime assembly for the type, so you need a name for that assembly
// declare assembly name for dynamic types.
proxyAssemblyName.Name = "ProxyAssembly";
// The name of the newly created assembly is ProxyAssembly.
AssemblyBuilder proxyAssemblyBuilder = proxyDomain.DefineDynamicAssembly(proxyAssemblyName, System.Reflection.Emit.AssemblyBuilderAccess.Run);
// Now you have to create assembly builder to build the assembly builder access option here I use just Run
ModuleBuilder proxyModuleBuilder = proxyAssemblyBuilder.DefineDynamicModule("ProxyModule");
// Now I build a module to hold my dynamic type from assembly builder.
TypeBuilder proxyBuilder = proxyModuleBuilder.DefineType("EchoProxy"
);
// And finally I create a type builder from module builder for dynamic type. The name of the new type is EchoProxy.
proxyBuilder.AddInterfaceImplementation(
interfaceType);
// Here I add the interface to the class, now my dynamic type implement the interface
MethodInfo[] methods =
interfaceType.GetMethods();
// Retrive the collection of methods from the interface.
for (int methodIndex = 0; methodIndex <
methods.Length ; methodIndex++)
{
MethodInfo currentMethod = methods[methodIndex];
// Obtain the current method.
Type[] paramType = new Type[realMethod.GetParameters().Length];
// Create an array of type which will passes as parameter.
for (int parameterIndex = 0; parameterIndex <
realMethod.GetParameters().Length; parameterIndex++)
paramType[parameterIndex] = currentMethod.GetParameters()[parameterIndex].ParameterType;
// Assign the type from interface
MethodBuilder proxyMethodBuilder = proxyBuilder.DefineMethod(
currentMethod.Name, currentMethod.Attributes, currentMethod.CallingConvention, currentMethod.ReturnType, paramType);
// Now create a method builder from type builder, with the specific parameter and return type.
// And the most annoying portion of the total work begin here.
// you have to write IL/OpCode here.
ILGenerator codeBlockGenerator = proxyMethodBuilder.GetILGenerator();
// Create a ILGenerator from Method builder
// Which helps you to flush the IL into IL stream.
codeBlockGenerator.Emit(OpCodes.Nop);
// OpCode = NOP
// It is practice to start a method with nop
codeBlockGenerator.EmitWriteLine("This is Proxy");
// OpCode = Print Line
codeBlockGenerator.Emit(OpCodes.Ldarg_0);
// Load the argument into evolution stack
codeBlockGenerator.Emit(OpCodes.Ret);
// Just return
// Return statement always pop last item from evolution stack and return it
}
return System.Activator.CreateInstance(
proxyBuilder.CreateType());
// Create a dynamic type from proxy builder and I create an instance from that with activator
// And return the instance of that type.
}

Now I am ready to use this method
public UseDynamicInstance()
{
IEcho simpleEcho =
GetObject(typeof(IEcho)) as IEcho;
if(
simpleEcho != null)
{
simpleEcho.Echo("Are you Ok");
}
}

Now what I am trying to show is that you can create runtime type and create an instance of it.
I find this helpful to create dynamic proxy Item
Hope you will find it so.
And you must include System.Reflection.Emit for these classes.