In my previous post, i enhanced the proxy to support generic calls. In order to minimize IL emit and move more parts to managed code, there is a better way to process the return value rather doing the checks against runtime method and see whether the method’s return type is a value or not for generic calls to un-box the object form that is returned from the interceptor.
Therefore, i replaced the return value processing from my previous with the following
- if (methodInfo.ReturnType != typeof(void))
- {
- ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInvocation).GetMethod("get_ReturnValue"));
-
- if (!methodInfo.ReturnType.IsGenericParameter)
- {
- if (methodInfo.ReturnType.IsPrimitive || methodInfo.ReturnType.IsValueType)
- {
- ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
- ilGenerator.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
- }
- else if (methodInfo.ReturnType.IsValueType)
- {
- ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
- }
- }
- else
- {
- ilGenerator.Emit(OpCodes.Unbox_Any, methodInfo.ReturnType);
- }
- }
Here, for generic return there is a different IL instruction to perform the un-boxing and for that we don’t need the runtime type [done in previous post]. The instruction is same as doing
T ret = (T)returnValue; // where returnValue is in object form
To make the basic proxy look more pretty, i added a silverlight project and added the Xunit tests from C# library that asserts the proxy is compatible in silverlight runtime with no pitfalls.
The Xunit tests are ported to silverlight using the Xunit Light wrapper by Jason Jarett that works seamlessly on top Microsoft Sliverlight Unit Testing Framework and just with an F5 gives you a nice output which can easily be registered by adding the following line in your App.xaml.cs.
- //*******************
- // Register the XUnitTestProvider with the Microsoft.Silverlight.Testing framework.
- UnitTestSystem.RegisterUnitTestProvider(new Microsoft.Silverlight.Testing.UnitTesting.Metadata.XunitLight.XUnitTestProvider());
- //*******************
- this.RootVisual = UnitTestSystem.CreateTestPage();
Finally, its still a simple proxy, plenty of things are missing and i will cover them up overtime but gives a way to get your feet wet with MSIL. You can download the latest proxy here
The link to the previous post follows A basic proxy for intercepting method calls (Part – 3).
Enjoy!!

Tags: Application Packaging, MSIL, Virtualization
In my previous posts, I showed how to create a proxy that can delegate calls. I further modified it to support argument list from original method and handled scenarios for void and non-void calls. In this post, i will further enhance it to introduce generic calls.
Basically proxy overrides the virtual or interface calls dynamically and to consider generic methods we just need to set few things on top of the original interception process. Before we begin, let’s just consider a simple method, may be that will make things more clear in terms of visualization.
- public virtual TRet Echo<T, TRet>(T arg1)
- {
- return default(TRet);
- }
To make the proxy to support this type of calls , before we wrap the method and register it with the user provided interceptor we just need to add the following lines
- if (methodInfo.IsGenericMethod)
- {
- Type [] genParams = methodInfo.GetGenericArguments();
-
- string[] genericParamNames = new string[genParams.Length];
-
- int index = 0;
-
- foreach(Type genParam in genParams)
- {
- genericParamNames[index++] = genParam.Name;
- }
-
- methodBuilder.DefineGenericParameters(genericParamNames);
- }
So, MethodBuilder has a magic function named DefineGenericParamters that actually marks the method as generic with specified generic arguments, similar to do it inside <.. > by hands.
Hmm..Looks like we are almost done, but looking at the method we can see that it can return any value. In that case, we have to make sure that the return value is unboxed properly [you can have a look at the previous post, if not already]. Therefore, we need to get the runtime reference of the method that will actually contain user provided types rather the generic ones. In order to get the runtime method reference, we need to consider two things more specifically
- Nothing special , just get the reference though RuntimeMethodHandle :-|
- If the method uses any generic type that is actually defined by the class then you should consider the RuntimeTypeHandle as well.
Considering this, our code for getting runtime method reference will look like:
- LocalBuilder locMethod = ilGenerator.DeclareLocal(typeof(MethodInfo));
-
- ilGenerator.Emit(OpCodes.Ldtoken, method);
- if (target.IsGenericType)
- {
- ilGenerator.Emit(OpCodes.Ldtoken, target);
- ilGenerator.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new[]
- {
- typeof(RuntimeMethodHandle),
- typeof(RuntimeTypeHandle)
- }));
- }
- else
- {
- ilGenerator.Emit(OpCodes.Call, typeof(MethodBase).GetMethod("GetMethodFromHandle", new[]
- {
- typeof(RuntimeMethodHandle)
- }));
- }
- ilGenerator.Emit(OpCodes.Castclass, typeof(MethodInfo));
- ilGenerator.Emit(OpCodes.Stloc, locMethod);
In the previous post, i did a check for return type like
-
- if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum)
- {
- // unboxing action
- }
Now, we just need to replace this with the following for our new runtime method.
- Label lblExit = ilGenerator.DefineLabel();
- Label lblUnBox = ilGenerator.DefineLabel();
- LocalBuilder locReturnType = ilGenerator.DeclareLocal(typeof(Type));
-
- ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInvocation).GetMethod("get_ReturnValue"));
-
- // store the return type to an intermidiate variable.
- ilGenerator.Emit(OpCodes.Ldloc, locRuntimeMethod);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInfo).GetMethod("get_ReturnType"));
- ilGenerator.Emit(OpCodes.Stloc, locReturnType);
-
- ilGenerator.Emit(OpCodes.Ldloc, locReturnType);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(Type).GetMethod("get_IsValueType"));
- ilGenerator.Emit(OpCodes.Brtrue,lblUnBox);
- ilGenerator.Emit(OpCodes.Ldloc, locReturnType);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(Type).GetMethod("get_IsEnum"));
- ilGenerator.Emit(OpCodes.Brtrue, lblUnBox);
-
- ilGenerator.Emit(OpCodes.Br, lblExit);
-
- ilGenerator.MarkLabel(lblUnBox);
-
- // unbox.
- ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
- ilGenerator.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
-
- ilGenerator.MarkLabel(lblExit);
Looks cryptic , but looking closely you will see that there are just two labels and depending on the boolean result it jumps to the un-boxing block and finally for types like string it just jumps to the end.
Tip 1 : Opcodes.BrTrue/BrFalse conditionally takes the IP(instruction pointer) to a particular memory location defined by MarkLabel() based on the value available on top of evaluation stack.
Finally, we can intercept our target method to see everything works (interception code remains same from previous post)
- int result2 = test.Echo<int, int>(10);
-
- if (result2 != 1)
- throw new Exception("result should equal 10");
The latest version can be downloaded from here and happy Coding!!

Tags: Application Packaging, MSIL, Virtualization
Posted by Jason Jarrett on Jan 28, 2010 in
C & C++,
Dotnet,
Silver Light |
View Original Article
{… Removed big long story about how I ended up writing this post which provides no value to the blog…}
Summary of big long story to at least give a little context as to why (yet another post on optional parameters):
I threw an idea out to the Moq discussion group of how we could use the named/optional parameters in a future version of Moq. (you can read the thread here) In my original feature request I displayed my lack of concrete knowledge in the named/optional parameters support that is eventually coming with .net 4.0.
Once I learned that you could place default values on interfaces it left me with questions… So, what better way to figure them out? Go test it…
Disclaimer: (Shouldn’t every blog have some context enlightening disclaimer?)
I haven’t looked up best practices or lessons learned from people that have had this language feature (VB), so I’m just doing this as an experiment for myself. Hope some of my findings help the other C#’ers wanting to learn a little about the feature.
What are optional parameters?
DimeCasts.Net, Derik Whittaker has a nice intro video # 153 – Exploring .Net 4 Features – Named and Optional Parameters
OR check out – http://tinyurl.com/yz3pc9o
Can an interface define a default value?
Yes!
Can I specify a default in the concrete implementation, if the interface has a default also?
Yes!
What happens when the concrete implementation has a different default value than the interface’s default?
If the interface has a default value specified, that is different from the concrete implementation, then it depends on what reference you’re using when executing the method.
In the case below we are executing the method directly off of the Foo instance and will therefore get the concrete implementation’s default value when executing.
(new Foo()).Bar() – would use the value of ‘1000’.
And in the case below we cast the Foo instance to an IFoo and it will then use the interfaces default value when executing.
((IFoo) new Foo()).Bar() – would use the value of ‘1’.
Below are some examples of the different use cases.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Should_get_the_concrete_class_default_value()
{
Foo f1 = new Foo();
f1.Bar();
f1.ParamValue.ShouldBeEqualTo(1000);
}
[TestMethod]
public void Should_get_the_interface_default_value()
{
IFoo f = new Foo();
f.Bar();
f.ParamValue.ShouldBeEqualTo(1);
}
[TestMethod]
public void Should_get_the_interface_default_value_because_of_explicit_cast()
{
Foo f = new Foo();
((IFoo)f).Bar();
f.ParamValue.ShouldBeEqualTo(1);
}
[TestMethod]
public void Should_get_the_concrete_class_default_value_because_of_explicit_cast()
{
IFoo f = new Foo();
((Foo)f).Bar();
f.ParamValue.ShouldBeEqualTo(1000);
}
}
interface IFoo
{
int ParamValue { get; }
void Bar(int paramValue = 1);
}
class Foo : IFoo
{
public int ParamValue { get; private set; }
public void Bar(int paramValue = 1000)
{
ParamValue = paramValue;
}
}
The next experiment – Extract Interface.
Next I tried removing the IFoo interface that I’d created manually, because I wanted to exercise the “Extract Interface…” functionality, just to see how it dealt with the these defaults.
Luckily, there were no surprises. The interface it created was exactly (less spacing) the same as I originally had.
Although it didn’t display the default constant value in the dialog during creation, there was a hint that the method signature had a default by placing [] around the int resulting in “Bar([int])”.

Side Tool Issue: Can’t say I like how it forced me to put the interface in a different file, I guess it’s enforcing “best practice” here, but I prefer to do this later in the dev cycle than immediately (kind of like how R# allows you to place in the file next to the original class). #ToolGettingInWay
Optional Parameter Issue: One issues I see with this solution was the dirty/icky copy/paste feeling I got when extracting the interface – the default was copied from the class to the interface.
Possible solutions to the “dirty/icky copy/paste feeling” the extract interface gives.
(in no particular order of preference)
- Place all defaults into a constant and reference the constant in both the interface and the concrete implementation(s).
- Don’t place the defaults in the concrete implementation (only in the interface). As you should probably not be depending on the concrete implementation to begin with, you wouldn’t need it there (and wouldn’t even call it). This would also help in the case that there are multiple concrete implementation and having to sift through the code looking for all instances to updated defaults for could be very error prone.
On the surface named parameters seem like a very simple feature to the C# language. But after delving into the feature a little, I can see there are many complicated scenarios you can get your self caught up into.
As with anything…Use with care!
Tags: .NET 4.0), Application Packaging, Virtualization
Posted by Jan Van Ryswyck on Jan 28, 2010 in
C & C++,
Dotnet,
Silver Light |
View Original Article
A typical way for invoking a non-public method of a class is by using reflection. This can come in handy in a number of cases. One typical scenario that comes to mind is when the designers of the .NET Framework or another 3rd party framework decided to bury a class or a method as internal while this could perfectly solve a problem (I just hate it when they do that).
Invoking private methods is not considered a best practice in general, but there are cases where you have no other option than to fall back on using reflection. The following code snippet shows how one would typically accomplish that.
public class Subject
{
private String DoSomething(String input)
{
return input;
}
}
// Calling code
var subject = new Subject();
var doSomething = typeof(Subject).GetMethod("DoSomething",
BindingFlags.Instance | BindingFlags.NonPublic);
var result = doSomething.Invoke(subject, new[] { "Hello Muppets" });
Console.WriteLine(result);
We all recognize this piece of code as we’ve done this at some point in one of our coding sessions. What I want to share here is a slightly nicer way to accomplish the same without all the usual reflection ugliness.
// Calling code that uses delegates
var subject = new Subject();
var doSomething = (Func<String, String>)
Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));
This code just creates a delegate that matches the signature of the non-public method that we want to call. To me, this approach looks far more elegant. Note that this only works for instance methods and not for static methods.
I hope that this can be of some use.
Tags: .NET 3.5, Application Packaging, Virtualization
In my previous post , i introduced a basic proxy that intercepts methods. But what is missing in the proxy is that it does not consider method arguments and can not handle return types. In this post, i will enhance the proxy to support exactly those.
First of all, i modified the IIntercept.Intercept() to accept IInvocaiton interface. The interface is pretty simple and it consists of an arguments array and a method that will be used to set the return value from interceptor.
- /// <summary>
- /// Contains Invocation details.
- /// </summary>
- public interface IInvocation
- {
- /// <summary>
- /// Gets the invocation arguments.
- /// </summary>
- object[] Arguments { get; }
- /// <summary>
- /// Sets the return value.
- /// </summary>
- /// <param name="value"></param>
- void SetReturn(object value);
- }
Internally, the interface is implemented with a class named MethodInovcation , where the arguments and return type is passed through the constructor. As, arguments will be passed dynamically during method call, I first declared a LocalBuilder that will actually take the arguments and wrap it around an array of objects which will be then passed to the constructor. Therefore, i created an extension method that will emit the necessary IL from method’s argument types.
- LocalBuilder args = ilGenerator.DeclareLocal(typeof(object[]));
-
- ilGenerator.Emit(OpCodes.Ldc_I4_S, parameterTypes.Length);
- ilGenerator.Emit(OpCodes.Newarr, typeof(object));
- ilGenerator.Emit(OpCodes.Stloc, args);
-
- if (parameterTypes.Length > 0)
- {
- ilGenerator.Emit(OpCodes.Ldloc, args);
-
- for (int index = 0; index < parameterTypes.Length; index++)
- {
- ilGenerator.Emit(OpCodes.Ldc_I4_S, index);
- ilGenerator.Emit(OpCodes.Ldarg, index + 1);
-
- Type parameterType = parameterTypes[index];
-
- if (parameterType.IsValueType || parameterType.IsGenericParameter)
- ilGenerator.Emit(OpCodes.Box, parameterType);
-
- ilGenerator.Emit(OpCodes.Stelem_Ref);
- ilGenerator.Emit(OpCodes.Ldloc, args);
- }
-
- ilGenerator.Emit(OpCodes.Stloc, args);
- }
The OpCodes.NewArray instruction declares an array from the target with the length pushed on the top of evaluation(EV) stack. The most interesting part in this code is how to take an argument and assign that to our array . OpCodes.Stelem_Ref actually assigns the value from the top of evaluation stack to the index that is mentioned through Opcodes.Ldc_I4_S where OpCodes.Larg [ 1 .. n ] pushes the argument to the top of EV stack.Outside the declaring of LocalBuilder through extension looks like:
- LocalBuilder locParameters = ilGenerator.DeclareParameters(paramTypes);
Here, we also need to declare a variable that will contain the instance of MethodInvocation
- LocalBuilder locMethodInvocation = ilGenerator.DeclareLocal(typeof (MethodInvocation));
Just before Intereptor.Intercept() is called (Let’s assume it from previous post), the following code is added.
- ilGenerator.Emit(OpCodes.Ldloc, locParameters);
- ilGenerator.Emit(OpCodes.Ldtoken, methodInfo.ReturnType);
- ilGenerator.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);
- ilGenerator.Emit(OpCodes.Newobj, typeof(MethodInvocation).GetConstructor( new []
- {
- typeof(object[]), typeof(Type)
- }));
- ilGenerator.Emit(OpCodes.Stloc, locMethodInvocation);
- ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
Another interesting part is how we dynamically pass the method’s return value from interceptor. OpCodes.Ldtoken loads the type’s token from which by calling GetTypeFromHandle the type is resolved in runtime and passed to the constructor.If you ever used an IL dissembler to look under the hood, you find it pretty common. Once, the extra lines are added to existing basic proxy , its time to check if things are doing just fine. To simplify, method will be called with an integer which will be returned by the interceptor.
- var proxy = new Proxy(typeof(TestClass));
- var test = (TestClass) proxy.Create(new BasicInterceptor());
-
- int result = test.TestCall(1);
-
- if (result != 1)
- throw new Exception("result should equal 1");
Thus, the existing basic interceptor will covert into following :
- public class BasicInterceptor : IInterceptor
- {
- public void Intercept(IInvocation invocation)
- {
- System.Console.WriteLine("Intercepted");
-
- invocation.SetReturn(invocation.Arguments[0]);
- }
- }
We are setting the return from the argument that is passed in. As previously the MethodInvocation is assigned to a local variable,after the interception the value is get and unboxed(value type/enum should be unboxed from object).
- if (methodInfo.ReturnType != typeof(void))
- {
- ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInvocation).GetMethod("get_ReturnValue"));
-
- if (methodInfo.ReturnType.IsValueType ||
- methodInfo.ReturnType.IsEnum)
- {
- ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
- ilGenerator.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
- }
- }
The snippet is placed just before OpCodes.Ret. The OpCodes.Callvirt calls the ReturnValue property from MehodInvocation where the value is set and pushes on the top of EV stack. OpCodes.Ret returns with whatever the value is on the top of EV stack. The top has to be empty for void calls therefore an extra check is added.
Also, for value types we just can’t put null on EV stack, we will definitely end up with an “JIT encountered and internal limitation” error. Therefore, return value in MethodInvocation should go through the following check which is equivalent to default(value) call.
- if (returnValue == null && returnType.IsValueType)
- {
- returnValue = Activator.CreateInstance(returnType);
- }
Finally, there are plenty of things that are missing in the proxy comparing to real ones but gives out a good example for playing with MSIL. The updated proxy can be downloaded from here .
Happy coding.

Tags: Application Packaging, MSIL, Virtualization
Posted by Brian Lagunas on Jan 22, 2010 in
C & C++,
Dotnet,
Silver Light |
View Original Article
If you attended the NETDUG user group meeting last night and would like to download the sample code for my Silverlight/WPF Multi-Targeting presentation, you can download it here.
Recap:
The Silverlight and WPF platforms are very similar, but they do not have binary compatibility; this means that an assembly compiled for one platform cannot execute on the other platform (Although, the story is a little different in Silverlight 4). You may want to target some or all of your application on WPF and Silverlight for a number of reasons.
Due to the fact that Silverlight and WPF are so closely related, the bulk of your application code can be shared between the two platforms. This encourages heavy use of pattern based development to isolate the logic from the presentation and maximize the separation between UI code and non-UI code.
Elements you can share:
- Presenters
- Controllers
- Models
- Services
- Unit tests
- Simple views, if the XAML used is supported by both Silverlight and WPF.
Elements that are harder to share:
- Complex views (XAML)
- Controls
- Styling
- Animation
Like always, if anyone has any questions feel free ask.
Tags: Application Packaging, multi-targeting, NETDUG, Silverlight, Virtualization, WPF
In this post i am going to show how you can write your own proxy for delegating calls. This just shows a way how you can handle it on your own but for complex interceptions its always wise to use alpha/beta/tested solutions. The post is more of an under the hood or aims to solve simple interception tasks where you might not need a full featured dynamic proxy or can be useful in building something that requires similar techniques that might save your day.
Let’s start by considering a simple class
- public class TestClass
- {
- public virtual void TestCall()
- {
- throw new Exception("Failed.");
- }
- }
Here, during the creation of proxy i will hook the method with an interceptor that will alternate the execution process from original code. Our interceptor looks like:
- public interface IInterceptor
- {
- void Intercept();
- }
Let’s create an implementation on it named BasicInterceptor where in the Intercept call it just prints a line.
- public class BasicInterceptor : IInterceptor
- {
- public void Intercept()
- {
- System.Console.WriteLine("Intercepted");
- }
- }
Once, we are done with our proxy the result code will look something like below:
- var proxy = new Proxy(typeof(TestClass));
- var test = (TestClass) proxy.Create(new BasicInterceptor());
-
- test.TestCall();
The above test.TestCall() call Instead of throwing an exception it will print our expected line. We can here see that I first created the proxy with the given type/class then during the instantiation i hooked that up with our interceptor. Hence, on my first move I created a class deriving from the specified type and expanded its constructor(s) to take IInterceptor implementation as parameter.
Accordingly, I first created a TypeBuilder instance from System.Refleciton.Emit which is pretty much common in all kind and that looks like:
- AssemblyName assemblyName = new AssemblyName("BasicProxy");
- AssemblyBuilder createdAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
- // define module
- this.moduleBuilder = createdAssembly.DefineDynamicModule(assemblyName.Name);
That is followed by:
- this.typeBuilder =
- this.moduleBuilder.DefineType(target.FullName, TypeAttributes.Class | TypeAttributes.Public, target);
In the proxy , I defined a field named “interceptor” that will be assigned with passed-in user-defined implementation.
- this.fldInterceptor = this.typeBuilder.DefineField("interceptor", typeof (IInterceptor), FieldAttributes.Private);
Now, for each constructor let’s expand it to have IInterceptor as first argument, call the corresponding base and set it to our defined field.
- Type[] parameters = new Type[1];
-
- ParameterInfo[] parameterInfos = constructor.GetParameters();
- parameters = new Type[parameterInfos.Length + 1];
-
- parameters[0] = typeof(IInterceptor);
-
-
- for (int index = 1; index < parameterInfos.Length; index++)
- {
- parameters[index] = parameterInfos[index].ParameterType;
- }
-
- ConstructorBuilder constructorBuilder =
- typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameters);
- ILGenerator generator = constructorBuilder.GetILGenerator();
-
-
-
- generator.Emit(OpCodes.Ldarg_0);
-
- for (int index = 1; index < parameters.Length; index++)
- {
- generator.Emit(OpCodes.Ldarg, index + 1);
- }
-
- generator.Emit(OpCodes.Call, constructor);
-
- generator.Emit(OpCodes.Ldarg_0);
- generator.Emit(OpCodes.Ldarg_1);
- generator.Emit(OpCodes.Stfld, fldInterceptor);
- generator.Emit(OpCodes.Ret);
Tip 1 : OpCodes.Ldarg_0 is like “this” context, which is not needed for static calls. If your are calling a field of the class or referring method arguments, always start with LdArgs_0 or you might end up with “JIT encountered an internal limitation” error.
Tip 2: In MSIL every method must terminate with OpCodes.Ret regardless its void or not. The difference between void and non-void calls is that the top of evaluation stack is not empty.
Now, as we set it up , we need to hook the interceptor in each method that is marked as virtual. First, let’s create the target method attribute :
- const MethodAttributes targetMethodAttributes =
- MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
Next, for each method that is not final hook the IInterceptor.Intercept() call.
- if (methodInfo.IsVirtual)
- {
- Type[] paramTypes = GetParameterTypes(methodInfo.GetParameters());
-
- MethodBuilder methodBuilder =
- typeBuilder.DefineMethod(methodInfo.Name,targetMethodAttributes, methodInfo.ReturnType, paramTypes);
-
- ILGenerator ilGenerator = methodBuilder.GetILGenerator();
-
- ilGenerator.Emit(OpCodes.Ldarg_0);
- ilGenerator.Emit(OpCodes.Ldfld, fldInterceptor);
- ilGenerator.Emit(OpCodes.Callvirt, typeof(IInterceptor).GetMethod("Intercept"));
-
- ilGenerator.Emit(OpCodes.Ret);
- }
Again, before loading the interceptor field on to the evaluation stack , I used Ldarg_0 or “this” equivalent . If you notice, you will see that I have used OpCodes.Callvirt instead of OpCodes.Call. This will actually call the base method rather the implemented. This difference is important if you need to distinguish between base and implemented calls. Unless otherwise, it is better to go with OpCodes.Callvirt that will do the work for you if “base” is something not in your consideration.
Finally, you need to create the type and the instance that will be initiated by Proxy.Create()
- Type proxy = this.typeBuilder.CreateType();
- return Activator.CreateInstance(proxy, args);
That’s it, we ended up with a simple proxy. In the next post i will enhance it with parameters consideration and show how to handle return value from proxy. The example proxy can be downloaded from here.
Happy new year !!

Tags: Application Packaging, MSIL, Virtualization
Posted by Davide on Dec 13, 2009 in
C & C++,
Silver Light |
View Original Article
Note – this is a multi part post:
Today I had the opportunity to take a look at the code written in the previous posts and insert some new stuff in order to modify the project and make new experiments about:
-
using a different ViewModel class for the design-time and run-time;
-
-
retrieve the data using an async call to a WCF service and passing back the results to the VM via MEF.
1 – Using different VM classes
To accomplish this task I’ve defined a new interface named IMainPageViewModel defining these members:
/// MainPage ViewModel interface
public interface IMainPageViewModel : IViewModelBase
{
string aViewModelProperty { get; set; }
DataItems dataItems { get; set; }
ICommand addDataItemCommand { get; }
}
This new interface is then implemented by two classes named ViewModels.DesignMode.MainPageViewModel and ViewModels.MainPageViewModel:
/// ViewModel for the "MainPageView" used in design-mode
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
public MainPageViewModel()
{
//Initialize the properties with test data if design mode
aViewModelProperty = "Value - Design Mode";
//Initialize the "dataItems" property
dataItems = new DataItems();
dataItems.Add(new DataItem() { Description = "Sample Data Item 1 - Design Mode" });
dataItems.Add(new DataItem() { Description = "Sample Data Item 2 - Design Mode" });
}
public string aViewModelProperty { get; set; }
public DataItems dataItems { get; set; }
public ICommand addDataItemCommand { get; set; }
}
/// ViewModel class for the "MainPageView" using MEF
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MainPageViewModel))]
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
public MainPageViewModel() { }
[Import("aViewModelPropertyTextProvider")]
public string aViewModelProperty { get; set; }
[Import(typeof(WcfDataItems))]
public DataItems dataItems { get; set; }
[Import(typeof(ICommand))]
public PartCreator<ICommand> addDataItemCommandCreator { get; set; }
private ICommand _addDataItemCommand;
public ICommand addDataItemCommand
{
get {
if (_addDataItemCommand==null)
_addDataItemCommand = addDataItemCommandCreator.CreatePart().ExportedValue;
return _addDataItemCommand;
}
}
}
The first one is associated with the View at design-time using an attached property which permits to bind an instance only at design time using this xaml (usually you should use <d:DesignProperties.DataContext>, here we are experimenting, of course):
<UserControl x:Class="SL4_MVVM_MEF.Views.MainPageView"
........
xmlns:designer="clr-namespace:SL4_MVVM_MEF.Designer"
xmlns:providersDM="clr-namespace:SL4_MVVM_MEF.Providers.DesignMode"
>
<!-- Design time DataContext -->
<designer:Page.DesignDataContext>
<providersDM:MainPageViewModelProvider/>
</designer:Page.DesignDataContext>
........
DesignTimeDataContext attached dependency property:
/// DesignDataContext Attached Dependency Property
public static readonly DependencyProperty DesignDataContextProperty =
DependencyProperty.RegisterAttached("DesignDataContext", typeof(object), typeof(Page),
new PropertyMetadata((object)null,
new PropertyChangedCallback(OnDesignDataContextChanged)));
/// Gets the DesignDataContext property.
public static object GetDesignDataContext(DependencyObject d)
{
return (object)d.GetValue(DesignDataContextProperty);
}
/// Sets the DesignDataContext property.
public static void SetDesignDataContext(DependencyObject d, object value)
{
d.SetValue(DesignDataContextProperty, value);
}
/// Handles the DesignDataContext property changes
private static void OnDesignDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
//Get the ViewModel instance only in design mode
if ((Application.Current == null) || (Application.Current.GetType() == typeof(Application)))
element.DataContext = e.NewValue;
}
And this is the design-time mode in Blend using the new attached property:

2 – MEF and implicit styles
The new implict styles feature available in Silverlight 4 beta is used to initialize the DataContext of the MainPageView type in a declarative way in App.xaml:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/ xaml/presentation"
xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
x:Class= "SL4_MVVM_MEF.App"
xmlns:views= "clr-namespace:SL4_MVVM_MEF.Views"
xmlns:providers= "clr-namespace:SL4_MVVM_MEF.Providers">
<Application.Resources>
<!-- Run-time DataContext composed using MEF -->
<Style TargetType="views:MainPageView">
<Setter Property="DataContext">
<Setter.Value>
<providers:MainPageViewModelMEFProvider/>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
In this case I’ve modified the MainPageViewModelMEFProvider class and inserted a new IViewModelProvider interface in order to obtain the instance of the ViewModel initialized by MEF:
/// Interface for the ViewModelProvider
public interface IViewModelProvider
{
object GetViewModel { get; }
}
/// Get the ViewModel instance using MEF
public class MainPageViewModelMEFProvider : IViewModelProvider
{
public MainPageViewModelMEFProvider() { }
[Import(typeof(MainPageViewModel))]
public IViewModelBase ViewModel { get; set; }
/// Get the Instance of the ViewModel using MEF
public object GetViewModel
{
get
{
PartInitializer.SatisfyImports(this);
return ViewModel;
}
}
}
3 – retrieve the data using an async call to a WCF service
I’ve added to the solution a simple WCF service which returns a collection of DataItems:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataItemService : IDataItemService
{
[OperationContract]
public List<DataItemFromService> GetDataItems()
{
// Add your operation implementation here
return new List<DataItemFromService>()
{
new DataItemFromService() {Description="DataItem from service 1"},
new DataItemFromService() {Description="DataItem from service 2"},
new DataItemFromService() {Description="DataItem from service 3"}
};
}
}
interface IDataItemService
{
List<DataItemFromService> GetDataItems();
}
public class DataItemFromService
{
public string Description { get; set; }
}
Since the project uses MEF composition and [Import] /[Export] attributes to initialize all the members of the VM class, I’ve used the same approach for the dataItems collection, retrieving data from an async call to the WCF service using a WcfDataItems class:
/// A sample collection of DataItems from WCF
[Export(typeof(WcfDataItems))]
public class WcfDataItems : DataItems
{
public WcfDataItems()
{
//Initialize the collection
DataItemWcfService.DataItemServiceClient svc = new DataItemWcfService.DataItemServiceClient();
svc.GetDataItemsCompleted += (s1, e1) =>
{
if (e1.Result != null)
e1.Result.ToList().ForEach(d =>
{
//Retrieve a new DataItem
DataItem di = DataItemCreator.CreatePart().ExportedValue;
di.Description = d.Description;
this.Add(di);
});
isLoading = false;
};
svc.GetDataItemsAsync();
isLoading = true;
}
[Import(typeof(DataItem))]
public PartCreator<DataItem> DataItemCreator { get; set; }
}
The code is available for download here.
Happy Silverlighting!
Tags: .NET Programming, Application Packaging, Patterns, Programming, ria, Rich Internet Applications, Silver Light, Silverlight 4, Virtualization
Posted by mtaulty on Dec 9, 2009 in
C & C++,
Silver Light |
View Original Article
The other day I had a talk to give which included a little around Windows 7 shell programming in .NET 4.0 Beta 2 and I hadn’t really looked at it so I took a few mins out to take a look at how you can program the Taskbar in Windows 7 from WPF in Visual Studio 2010 Beta 2. I was really looking for a short, snappy screencast to take me through it and I didn’t find one ( which doesn’t necessarily mean that they don’t exist but I did search around a little ) so I made a couple that I’ve embedded here. One is around jumplists; Windows 7 - Programming Taskbar jumplists with Visual Studio 2010 . and the other is around getting thumbnail previews of application windows on the Taskbar; Windows 7 - Programming Taskbar previews with Visual Studio 2010 . You’ll need Visual Studio 2010 Beta 2 to follow along with these; Download Visual Studio 2010 Beta 2 Also, I mention that there is more complete Windows 7 functionality in the Windows API Code-Pack so take a look at that too; Download Windows API Code-Pack and, as always...(
read more)

Tags: .NET, .NET Framework 4.0, Application Packaging, Virtualization, Windows 7, WPF
Yesterday , i was reading Clean Code by Uncle Bob. While i was doing so , i came across a line that really stuck my thought patterns and i would like to share it with my readers as well.
The line looks something like, provided that there is a shape factory that will be implemented by concrete classes.
“What should you name them? IShapeFactory and
ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in
today’s legacy wads, is a distraction at best and too much information at worst”
This is true, in a sense today even our popular refactoring tools [there are not much, so you can easily figure out] when typed, precedes the interface with “I” word. And if we look though all the open source foundries, we will see this here and there with no exception. Even honestly, i encode interfaces with “I” word, but technically it would be much better if we have a structure like
Shapes.Abstractions
| ShapeFactory
CSharpShapeFactory
After, reading that i came to realization that we should abandon this “I” encoding for interfaces that is going on decades to devs after devs. There should be a “General coding guidelines” which should include it and FxCorp should mark it as invalid during code analysis.
Now, did i say something wrong , enlighten me, why we still need to encode our inferface, when our modern compiler are smarter enough to do it for us. I guess we are way too ahead from the days of integer based type encodings , aren't we ?


Tags: Agile, Application Packaging, AspNetMvc, Virtualization