Archive for the ‘.Net’ Category.

Book Review-Foundations of F#

“Foundations of F#” is written by Robert Pickering who is a programmer and author living and working in Paris, France as he says. I think his enthusiasm in F# and .NET Framework made him to write this book. I really enjoyed reading his book and learned some new tricks in F# as well.

Review

fsfound.jpg

“Foundations of F#” is a great introductory book for F# with some advanced samples. For those who are unfamiliar with functional programming, this book gives the notions of functional programming in all aspects while giving samples in the greatest platform with great language F#.

This book includes functional, imperative and object oriented programming paradigms giving great samples. Robert Pickering also focuses to the imperative programmers by giving the usage differences in F#. He introduces a wide range F# data structures from simple arrays to quotations with great explanations.

This book gives a lot of information on .NET Framework including the latest additions .NET Framework 3.0 and 3.5. Samples with LINQ and Windows Presentation Foundation fulfil this area. If you are unfamiliar with .NET Framework, don’t worry this book gives what you need to know about .NET framework in many different areas including network programming, web programming, database programming, and windows programming with clear and explanatory samples using relevant screenshots. The samples are unique and useful, it’s not the examples that you can find on the web, and it’s more specialised and focused on techniques specific to F#

Personally I most liked Language Oriented Programming chapter which gives very specific features and usage tricks to F# to make the most of the language. It’s a must have book in your bookshelf if you are interested in functional programming on .NET Framework

Silverlight and DLR

SilverlightBack to my previous post, WPF/Everywhere recently become Silverlight with the addition of new languages and new platform. Actually it’s not a new platform it’s a subset of IronPhyton programming language and it’s called DLR Dynamic Language Runtime. So more to .NET static typed languages, we have some new dynamic languages to be used for scripting in Silverlight. Moreover they will support IronPhyton, IronRuby, JavaScript and VB as dynamic language. It is still possible to use the Silverlight to code using the class library.

I think this is a different move and strategy from Microsoft to target more platforms with completely new and immature languages. However it is very promising in terms of technology it provides, cross platform cross browser flash like environment for different programming languages. We had .NET in different platforms like ASP.NET in the web server, Windows Forms and WPF in Windows and now we have .NET in the browser. You don’t have to have .NET framework to be installed because it comes with a small subset of .NET Framework in the plug-in.

So what it adds more browsing experience is of course the usage of .NET languages and a subset of .NET framework. It means that we can write multithreaded Javascript or C# in the browser plug-in. Different than server client model, the application executes in the client and uses their resources. The silverlight plug-in watches for user interaction and a call-back is being sent to the plug-in or to the browser. JavaScript serialisation, JASON, and marshalizing stuff are handled by Silverlight as well. It allows using asp.net style declarative programming, LINQ and WPF in the browser.

The platforms officially supported are Mac and Windows of course. In a very early stage (in 2 weeks after release) Mono has been released their implementation of Silverlight called Moonlight. This was quick because of the open source and BSD style license of Silverlight. So it is becoming a real cross platform in that case, just like flash does with more programming languages and techniques.

Silverlight is very good at advertising as well. A new developer platform space for sharing Silverlight projects is open, PopFly. It is the area to put silverlight applications and see what is possible with Silverlight. Moreover it is also possible to get 4GB free hosting space from Microsoft Silverlight Streaming. However we don’t know how much they will charge later on.

Silverlight might compete with flash in very short time. Flash is de facto standard for most of the browsers.A lot of web applications run flash to provide rich client features, now Silverlight come to the area with the power of .NET framework and your favourite languages.

Emulated Managed Windows Pipes with Standard Input and Output

Pipes are around since Unix, Linux and Windows 95. Pipes are a way of communication between two programs. It’s a virtual channel to the process. Normally it is a system function call in the kernel.dll.

A pipe is a one way channel that you can write or read. So to write and read basically we need to have a two channels. One for reading and one for writing.

In managed world, we don’t have spawn (Windows) function or fork (Linux) function to create a copy of the process. So the first trick is to create the same process with different arguments. Than redirect the standard input and output to our current process. Basically these are kind of pipes. You may know the pipe operator (|) available from the shell which redirects the standard output of the program to the standard input of the main process. What’s more in this is we write to the child process’ standard output. So we program in a way that the child process waits some commands from the parent process, execute the command and output results to parent process.

In this sample there are two processes, talking to each other.

using System;
using System.Collections.Generic;
using System.Text;
 
namespace WinPipes
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                //parent
                Console.WriteLine("Parent");
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
 
                proc.StartInfo.Arguments = "child";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardInput = true;
 
                proc.Start();
                System.IO.StreamReader str = proc.StandardOutput;
 
                Console.WriteLine("How many messages ?");
                int messageCount ;
                int.TryParse(Console.ReadLine(), out messageCount);
 
                proc.StandardInput.WriteLine(messageCount);
 
                for (int i = 0; i < messageCount; i++)
                {
                    Console.WriteLine("Sending Hello" + (i + 1));
                    proc.StandardInput.WriteLine("hello" + (i + 1));
                    Console.WriteLine(str.ReadLine());
                }
                Console.ReadLine();
            }
            else
            {
                // child
                int count = Convert.ToInt32(Console.ReadLine());
                for (int i = 0; i < count; i++)
                {
                    Console.WriteLine("Re - " + Console.ReadLine());
                }
 
            }
        }
    }
}

Parent
How many messages ?
3
Sending Hello1
Re – hello1
Sending Hello2
Re – hello2
Sending Hello3
Re – hello3

Pipes are not available in .Net Framework 2.0 and 3.0. However .Net Framework 3.5 will include managed classes for pipes. The best way to do pipes in a system level to invoke the system calls using some unmanaged code. For kernel the function name is CreatePipe or CreateNamedPipe. There is also a function int the standard C library called _pipe. Pinvoke.net is the best reference for calling kernel functions from the managed environment.

Microsoft AJAX 1.0 RTM

It has been more than a year since Atlas is out. I remember playing with the first hands-on-labs for doing a search query. I also really liked the Ajax Control Toolkit since the first day, still using two controls in a project. Now that baby is out of CTP, BETA and ASP.NET AJAX 1.0 is released. A lot has changed since it’s first release. The objects in javascript library, the method names, object names and the product name have changed. As a result, we have 2 separate products. ASP.NET 2.0 AJAX Extensions 1.0 (Client and Server), ASP.NET AJAX Control Toolkit . There is one more product which is ASP.NET AJAX Futures January CTP. This is the additional javascript library to provide additional functionality.

Interestingly, it has been shipped with source code.  There is no escape for the client source code release but they also include the server side controls which is good. Although we don’t have the server side controls code, Scott Guthrie announced the server side controls source code will  be released shortly. Client side is released with Microsoft Permissive License (Ms-PL) and server side with Microsoft Reference License (Ms-RL) The client side is more flexible in terms of license to extend the library.  

Thanks to the team…

WebDD – conference in Reading for web developers and web designers – Registration is Open

WebDD , a free confence in Reading for web developers and web designers, registration is open. It is organized by community and hosted by Microsoft. It is on Saturday 3rd February 2007 at Microsoft Reading, UK. Scott Guthrie will be there. You can find the speakers list and sessions.

There will be also a Geek Dinner like previous DDD events. The registration for the dinner is wiki style as previously. I will be there as well.

See you there.

Reflection for Properties and Fields with DynamicMethod

Lastly I posted about the coolest exception while working with System.Reflection.Dynamicmethod class. I found the solution for my bug, and now it works like a charm. There are two classes for accessing properties or fields, one with the generic implementations and one with object implementation. Using the reflection with dynamicmethod reflection we can get 80% more performance compared to traditional reflection. 

Be careful if you are about to use classes that have generic classes as properties. There are some problems with it.

Property that might cause problems of a class

 public class aField<T>
	{
		private T m_Value;
 
 
        public override string ToString()
        {
            return Value.ToString();
        }
 public interface IEntity
    {
         aField<string> CREUSER
        {
            get;
            set;
        }

.

Code for object

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
 
namespace CE.Reflection
{
    public class DynamicReflectionHelper
    {
        public delegate object GetPropertyFieldDelegate(object obj);
        public static GetPropertyFieldDelegate GetPropertyorField(PropertyInfo pi, FieldInfo fi)
        {
            if (pi != null && fi != null)
                throw new NotSupportedException("one of the parameters should be null");
 
            if (pi != null || fi != null)
            {
                string methodName = string.Empty;
                if (pi != null)
                    methodName = pi.Name;
                else
                    methodName = fi.Name;
 
                Module mod = null;
                if (pi != null)
                    mod = pi.Module;
                else
                    mod = fi.Module;
 
 
                DynamicMethod dm = new DynamicMethod("GetPropertyorField_" + methodName, typeof(object), new Type[] { typeof(object) }, mod, true);
                ILGenerator il = dm.GetILGenerator();
 
                il.Emit(OpCodes.Ldarg_0);
                if (pi != null)
                {
                    il.EmitCall(OpCodes.Callvirt, pi.GetGetMethod(), null);
                    if (pi.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Box, pi.PropertyType);
                    }
                }
                else if (fi != null)
                {
                    il.Emit(OpCodes.Ldfld, fi);
                    if (fi.FieldType.IsValueType)
                    {
                        il.Emit(OpCodes.Box, fi.FieldType);
                    }
                }
 
 
                il.Emit(OpCodes.Ret);
 
                return (GetPropertyFieldDelegate)dm.CreateDelegate(typeof(GetPropertyFieldDelegate));
 
            }
            else
                throw new NullReferenceException("no field or property");
        }
        public static GetPropertyFieldDelegate GetPropertyorField(object o, string memberName)
        {
            Type v = o.GetType();
            PropertyInfo pi = v.GetProperty(memberName);
            FieldInfo fi = v.GetField(memberName);
 
            return GetPropertyorField(pi, fi);
 
        }
 
        public delegate void SetPropertyFieldDelegate(object obj, object m_Value);
 
        public static SetPropertyFieldDelegate SetProperyorField(object o, string memberName)
        {
            Type v = o.GetType();
            PropertyInfo pi = v.GetProperty(memberName);
            FieldInfo fi = v.GetField(memberName);
 
 
            return SetProperyorField(pi, fi);
 
        }
 
        public static SetPropertyFieldDelegate SetProperyorField(PropertyInfo pi, FieldInfo fi)
        {
            if (pi != null && fi != null)
                throw new NotSupportedException("one of the parameters should be null");
            if (pi != null || fi != null)
            {
                string methodName = string.Empty;
                if (pi != null)
                    methodName = pi.Name;
                else
                    methodName = fi.Name;
 
                DynamicMethod dm = new DynamicMethod("SetPropertyorField_" + methodName, typeof(void),
                    new Type[] { typeof(object), typeof(object) }, pi.Module, true);
                ILGenerator il = dm.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
 
 
                if (pi != null)
                {
                    il.EmitCall(OpCodes.Callvirt, pi.GetSetMethod(true), null);
 
                    if (pi.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Unbox_Any, pi.PropertyType);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Stfld, fi);
                    if (pi.PropertyType.IsValueType)
                    {
                        il.Emit(OpCodes.Unbox_Any, pi.PropertyType);
                    }
                }
 
 
                il.Emit(OpCodes.Ret);
 
                return (SetPropertyFieldDelegate)dm.CreateDelegate(typeof(SetPropertyFieldDelegate));
            }
            else
            {
                throw new NullReferenceException("no field or property");
            }
        }
    }
}

Code for generic object

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
 
namespace CE.Reflection
{
    public class DynamicReflectionHelperforObject<V>
    {
        public delegate T GetPropertyFieldDelegate<T>(V obj);
 
 
        public static GetPropertyFieldDelegate<C> GetP<C>(string memberName)
        {
            Type v = typeof(V);
            PropertyInfo pi = v.GetProperty(memberName);
            FieldInfo fi = v.GetField(memberName);
 
            if (pi != null || fi != null)
            {
                DynamicMethod dm = new DynamicMethod("GetPropertyorField_" + memberName, typeof(C), new Type[] { v }, v.Module);
                ILGenerator il = dm.GetILGenerator();
 
                il.Emit(OpCodes.Ldarg_0); // loaded c, c is the return value
                if (pi != null)
                    il.EmitCall(OpCodes.Call, pi.GetGetMethod(), null);
                else if (fi != null)
                    il.Emit(OpCodes.Ldfld, fi);
                il.Emit(OpCodes.Ret);
 
                return (GetPropertyFieldDelegate<C>)dm.CreateDelegate(typeof(GetPropertyFieldDelegate<C>));
 
            }
            else
                throw new NullReferenceException("No Property or Field");
        }
 
        public delegate void SetPropertyFieldDelegate<T>(V obj, T m_Value);
 
        public static SetPropertyFieldDelegate<C> SetP<C>(string memberName, C mValue)
        {
            Type v = typeof(V);
            PropertyInfo pi = v.GetProperty(memberName);
            FieldInfo fi = v.GetField(memberName);
            if (pi != null || fi != null)
            {
                DynamicMethod dm = new DynamicMethod("SetPropertyorField_" + memberName, typeof(void),
                    new Type[] { v, typeof(C) }, v.Module);
                ILGenerator il = dm.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                if (pi != null)
                    il.EmitCall(OpCodes.Callvirt, pi.GetSetMethod(), new Type[] { typeof(C) });
                else if (fi != null)
                    il.Emit(OpCodes.Stfld, fi);
                il.Emit(OpCodes.Ret);
 
                return (SetPropertyFieldDelegate<C>)dm.CreateDelegate(typeof(SetPropertyFieldDelegate<C>));
            }
            else
                throw new NullReferenceException("No Property or Field");
        }
    }
}

This project has two main classes, one is generic for working with a specified type, and the other is normal object class in which you need to deal with conversion after using it.