8 March, 2010, 00:21

Real-World functional programming has been written by Tomas Petricek and Jon Skeet.
Tomasz’s and Jon’s book is built around how to think functionally when programming and how to make best use of functional paradigm for real world scenerios. The book is written mainly for the C# programmers who would like to switch/learn more of the functional world. It also features snippets with some technical background of the ideas involved.
As the title suggests the book is not focussed on one language, instead a mix of C# and F#, and it does a great job in bringing these worlds together,which is to me best of both worlds. Although, samples are all in functional style, when the problem needs the functional beauty to express, F# takes place. This gives any .NET developer to see when to use the necessary language for a particular problem.
The book starts slowly with the functional structures, and goes to monads, and to reactive libraries. I found the language of the book clear to understand, and easy to follow. The samples in the beginning of a chapter starts with some really simple constructs, but at the end of a chapter they become more complicated, and a nice programs to reflect the idea of the chapter.
Applied functional programming is probably the most sophisticated part of the book. Some ideas mainly inspired from research papers (cited at the end) blended with modern languages and libraries and applied somewhat differently. Especially composable functional libraries and reactive functional programs were insightful and open the mind with new possibilities.
Finally, I would recommend this book whoever wants to switch to functional programming and also learn new techniques in general. Each sample is crafted well, and represent real value with its tutorial writing style.
20 February, 2009, 16:03
Multiple Inheritance is a feature that a class that can inherit more than one class. Although CLR does not really care about it, it is not possible in the mainstream .NET languages to have multiple inheritance.
It is arguable that why we would ever need multiple inheritance. I think it is the same paradox as having dynamic types in a statically typed language. I am not going into that debate as it is already decided for almost a decade. This is an attempt on how to achieve the same effect using dynamic types easily.
In C++, multiple inheritance can simply be expressed like this :
class Auto {
public:
virtual void Go(int a) {}
virtual ~Auto() {}
};
class Animal {
public:
virtual void Go() {}
virtual ~Animal() {}
};
class SampleClass : public Auto, public Animal{};
int main() {
SampleClass *a = new SampleClass();
//a->Go(5); // Compiler error for ambigouity
//a->Go("going"); // Compiler error for missing method
Animal* an = dynamic_cast<Animal*>(a);
an->Go();
Auto* at = dynamic_cast<Auto*>(a);
at->Go(7);
}
When C# introduced dynamic type system and shared type system with C# 4, I thought it should be possible to express multiple inheritance using the new syntax. More like a forced Javascript prototypal inheritance instead of classical inheritance. However it turned out that it was even easier than that. It is relying on the runtime to operate on the types underlying with dynamic conversions, simply reflection.
Obviously it is not forced by the compiler, and you wouldn’t get intellisense but it will behave like a multiple inherited object. To achieve that the dynamic features of C# 4 has been used.
The same implementation in C# using Minherit object that has been created for reflected multiple inheritance.
So in C#, it would look like this :
public class Auto
{
public string Go(int a) {}
}
public class Animal
{
public string Go() {}
}
public class SampleClass : Minherit<Auto, Animal>
{
static void Main(string[] args)
{
dynamic sample = new SampleClass();
a.Go(4); // this will succeed at runtime and call the first Go(int)
a.Go("going"); // runtime error for missing method
Animal an = (Animal)sample;
Auto x = (Auto)sample;
an.Go();
x.Go(7);
}
}
It uses dynamic sample that has come with .NET Framework 4 CTP. I actually think that sample will go to mscorlib with the final release in the System namespace
As the code got a bit long, I post it as project zip file if you are interested.
Downloads: 389 File Name: cs4trials.zip
It is possible to create multiple inheritance abstraction as shown below. Here are the selected four methods to display how the GetMember and SetMember is implemented.
public override object Call(CallAction action, params object[] args)
{
var objMethod = GetMember<MethodInfo>(this, action.Name).Concat(
GetMember<MethodInfo>(base1, action.Name)).Concat(
GetMember<MethodInfo>(base2, action.Name));
object result = null;
bool executionSuccess = false;
foreach (var item in objMethod)
{
try
{
result = item.Second.Invoke(item.First, args);
executionSuccess = true;
break;
}
catch
{
}
}
if (executionSuccess)
{
return result;
}
else
{
throw new MissingMethodException(action.Name);
}
}
private IEnumerable<Pair<object, T>> GetMember<T>(object obj, string name)
{
return from member in obj.GetType().GetMember(name).OfType<T>()
select new Pair<object, T>(obj, member);
}
public override object GetMember(GetMemberAction action)
{
var property = GetMember<PropertyInfo>(this, action.Name).Concat(
GetMember<PropertyInfo>(base1, action.Name)).Concat(
GetMember<PropertyInfo>(base2, action.Name)).FirstOrDefault();
var field = GetMember<FieldInfo>(this, action.Name).Concat(
GetMember<FieldInfo>(base1, action.Name)).Concat(
GetMember<FieldInfo>(base2, action.Name)).FirstOrDefault();
if (property != null)
{
return property.Second.GetValue(property.First, null);
}
else if (field != null)
{
return field.Second.GetValue(field.First);
}
else
{
throw new MissingMemberException(action.Name);
}
}
public override void SetMember(SetMemberAction action, object value)
{
var properties = GetMember<PropertyInfo>(this, action.Name).Concat(
GetMember<PropertyInfo>(base1, action.Name)).Concat(
GetMember<PropertyInfo>(base2, action.Name));
var fields = GetMember<FieldInfo>(this, action.Name).Concat(
GetMember<FieldInfo>(base1, action.Name)).Concat(
GetMember<FieldInfo>(base2, action.Name));
bool issucceess = false;
foreach (var property in properties)
{
try
{
property.Second.SetValue(property.First, value, null);
issucceess = true;
break;
}
catch { }
}
if (!issucceess)
{
foreach (var field in fields)
{
try
{
field.Second.SetValue(field.First, value);
issucceess = true;
break;
}
catch { }
}
}
if (!issucceess)
{
throw new MissingMemberException(action.Name);
}
}
23 August, 2007, 16:44
Creating a class from a string might be crucial for some very dynamic projects. It’s a single line of code that I wanted to share but I think it has a lot of power.
Simply get the executing assembly and call the GetType method. If your assembly is one of the linked assembly or even a dynamically loaded assembly, you might need to call GetReferencedAssemblies() method as well.
namespace reflectme
{
using System;
public class hello
{
public hello()
{
Console.WriteLine("hello");
Console.ReadLine();
}
static void Main(string[] args)
{
Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
}
}
}
Bear in mind it will be extremely slow. Don’t do that
16 February, 2007, 04:03
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.
Downloads: 76 File Name: winpipes.zip
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.
8 January, 2007, 23:55
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;
}
Downloads: 91 File Name: reflection.zip
.
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.
30 December, 2006, 04:15
I posted an article to The Code Project for an image control. The basic idea for developing that is to write e-mail addresses as images using various formatting options on web applications.
Labels are generated as images instead of text, to have more privacy without any configurations and without HttpHandlers
ImageLabel is an ASP.NET web control for generating labels as images. You might want to do that for providing security for e-mail crawlers or to disallow copy paste of the text. Many similar controls have implemented as HttpHandlers, so you need more configuration to make them work. However this control does not need any configuration. You just need to use just like any other asp.net control like Label. Almost all of the label formatting options are included, like font size, backcolor, forecolor. Although this is not implemented as a CAPTCHA control, that functionality can easily added to image generation method.
ImageLabel Control at CodeProject
I think it is a good way to understand page and control life cycle using that control, if you are wondered about them. Beside that, if you like the article you can vote for me if you want to
Browser View :

Visual Studio Design View :

Tags:
.Net,
ASP.Net,
C#,
code,
codeproject,
control,
Projects,
webcontrol Category:
.Net,
ASP.Net,
C#,
General,
Projects |
1 Comment