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 Rick Strahl on Feb 18, 2010 in
C#,
Dotnet,
Silver Light |
View Original Article
I’ve run into the problem a few times now: How to pre-authenticate .NET WebRequest calls doing an HTTP call to the server – essentially send authentication credentials on the very first request instead of waiting for a server challenge first? At first glance this sound like it should be easy: The .NET WebRequest object has a PreAuthenticate property which sounds like it should force authentication credentials to be sent on the first request. Looking at the MSDN example certainly looks like it does:
http://msdn.microsoft.com/en-us/library/system.net.webrequest.preauthenticate.aspx
Unfortunately the MSDN sample is wrong. As is the text of the Help topic which incorrectly leads you to believe that PreAuthenticate… wait for it - pre-authenticates. But it doesn’t allow you to set credentials that are sent on the first request.
What this property actually does is quite different. It doesn’t send credentials on the first request but rather caches the credentials ONCE you have already authenticated once. Http Authentication is based on a challenge response mechanism typically where the client sends a request and the server responds with a 401 header requesting authentication.
So the client sends a request like this:
GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1
Host: rasnote
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en,de;q=0.7,en-us;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
and the server responds with:
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
WWW-Authenticate: basic realm=rasnote"
X-AspNet-Version: 2.0.50727
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
WWW-Authenticate: Basic realm="rasnote"
X-Powered-By: ASP.NET
Date: Tue, 27 Oct 2009 00:58:20 GMT
Content-Length: 5163
plus the actual error message body.
The client then is responsible for re-sending the current request with the authentication token information provided (in this case Basic Auth):
GET /wconnect/admin/wc.wc?_maintain~ShowStatus HTTP/1.1
Host: rasnote
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en,de;q=0.7,en-us;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: TimeTrakker=2HJ1998WH06696; WebLogCommentUser=Rick Strahl|http://www.west-wind.com/|rstrahl@west-wind.com; WebStoreUser=b8bd0ed9
Authorization: Basic cgsf12aDpkc2ZhZG1zMA==
Once the authorization info is sent the server responds with the actual page result.
Now if you use WebRequest (or WebClient) the default behavior is to re-authenticate on every request that requires authorization. This means if you look in Fiddler or some other HTTP client Proxy that captures requests you’ll see that each request re-authenticates: Here are two requests fired back to back:
and you can see the 401 challenge, the 200 response for both requests.
If you watch this same conversation between a browser and a server you’ll notice that the first 401 is also there but the subsequent 401 requests are not present.
WebRequest.PreAuthenticate
And this is precisely what the WebRequest.PreAuthenticate property does: It’s a caching mechanism that caches the connection credentials for a given domain in the active process and resends it on subsequent requests. It does not send credentials on the first request but it will cache credentials on subsequent requests after authentication has succeeded:
string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential("rick", "secret", "rasnote");
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
WebResponse resp = req.GetResponse();
resp.Close();
req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential("rstrahl", "secret", "rasnote");
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
resp = req.GetResponse();
which results in the desired sequence:
where only the first request doesn’t send credentials.
This is quite useful as it saves quite a few round trips to the server – bascially it saves one auth request request for every authenticated request you make. In most scenarios I think you’d want to send these credentials this way but one downside to this is that there’s no way to log out the client. Since the client always sends the credentials once authenticated only an explicit operation ON THE SERVER can undo the credentials by forcing another login explicitly (ie. re-challenging with a forced 401 request).
Forcing Basic Authentication Credentials on the first Request
On a few occasions I’ve needed to send credentials on a first request – mainly to some oddball third party Web Services (why you’d want to use Basic Auth on a Web Service is beyond me – don’t ask but it’s not uncommon in my experience). This is true of certain services that are using Basic Authentication (especially some Apache based Web Services) and REQUIRE that the authentication is sent right from the first request. No challenge first. Ugly but there it is.
Now the following works only with Basic Authentication because it’s pretty straight forward to create the Basic Authorization ‘token’ in code since it’s just an unencrypted encoding of the user name and password into base64. As you might guess this is totally unsecure and should only be used when using HTTPS/SSL connections (i’m not in this example so I can capture the Fiddler trace and my local machine doesn’t have a cert installed, but for production apps ALWAYS use SSL with basic auth).
The idea is that you simply add the required Authorization header to the request on your own along with the authorization string that encodes the username and password:
string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "rick";
string pwd = "secret";
string domain = "www.west-wind.com";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Headers.Add("Authorization", auth);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
WebResponse resp = req.GetResponse();
resp.Close();
This works and causes the request to immediately send auth information to the server. However, this only works with Basic Auth because you can actually create the authentication credentials easily on the client because it’s essentially clear text. The same doesn’t work for Windows or Digest authentication since you can’t easily create the authentication token on the client and send it to the server.
Another issue with this approach is that PreAuthenticate has no effect when you manually force the authentication. As far as Web Request is concerned it never sent the authentication information so it’s not actually caching the value any longer. If you run 3 requests in a row like this:
string url = "http://rasnote/wconnect/admin/wc.wc?_maintain~ShowStatus";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "ricks";
string pwd = "secret";
string domain = "www.west-wind.com";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.Headers.Add("Authorization", auth);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
WebResponse resp = req.GetResponse();
resp.Close();
req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential(user, pwd, domain);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
resp = req.GetResponse();
resp.Close();
req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential(user, pwd, domain);
req.UserAgent = ": Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 4.0.20506)";
resp = req.GetResponse();
you’ll find the trace looking like this:

where the first request (the one we explicitly add the header to) authenticates, the second challenges, and any subsequent ones then use the PreAuthenticate credential caching. In effect you’ll end up with one extra 401 request in this scenario, which is still better than 401 challenges on each request.
Getting Access to WebRequest in Classic .NET Web Service Clients
If you’re running a classic .NET Web Service client (non-WCF) one issue with the above is how do you get access to the WebRequest to actually add the custom headers to do the custom Authentication described above? One easy way is to implement a partial class that allows you add headers with something like this:
public partial class TaxService
{
protected NameValueCollection Headers = new NameValueCollection();
public void AddHttpHeader(string key, string value)
{
this.Headers.Add(key,value);
}
public void ClearHttpHeaders()
{
this.Headers.Clear();
}
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri);
request.Headers.Add(this.Headers);
return request;
}
}
where TaxService is the name of the .NET generated proxy class. In code you can then call AddHttpHeader() anywhere to add additional headers which are sent as part of the GetWebRequest override. Nice and simple once you know where to hook it.
For WCF there’s a bit more work involved by creating a message extension as described here: http://weblogs.asp.net/avnerk/archive/2006/04/26/Adding-custom-headers-to-every-WCF-call-_2D00_-a-solution.aspx.
FWIW, I think that HTTP header manipulation should be readily available on any HTTP based Web Service client DIRECTLY without having to subclass or implement a special interface hook. But alas a little extra work is required in .NET to make this happen
Not a Common Problem, but when it happens…
This has been one of those issues that is really rare, but it’s bitten me on several occasions when dealing with oddball Web services – a couple of times in my own work interacting with various Web Services and a few times on customer projects that required interaction with credentials-first services. Since the servers determine the protocol, we don’t have a choice but to follow the protocol. Lovely following standards that implementers decide to ignore, isn’t it? :-}
© Rick Strahl, West Wind Technologies, 2005-2010

Tags: .NET, Application Packaging, Virtualization, Web Services
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 Bryant Likes on Jan 18, 2010 in
C#,
Dotnet,
Silver Light |
View Original Article
One of the cool features of SharePoint 2010 (currently in beta) is that you can set
it up on a Windows 7 machine. This means that as a SharePoint developer you no longer
have to run a Server OS.
To get started I downloaded
the SharePoint 2010 Foundations beta from here. You will also need
Visual Studio 2010 which you can download from here.
To setup SharePoint 2010 on Windows 7 you need to follow
this guide which explains how to configure the setup process to run on Windows 7 (it
is only one change to an xml file).
Make sure you install all the prerequisites which I won’t list here (they are
listed in the guide). It will still install even if you don’t, but you will get errors
when you try to configure SharePoint (voice of experience here).
Once you have everything installed and have completed the configuration tool, your
site should come up in the browser! Now you can start working with Silverlight and
SharePoint.
Tip: Install the
SQL
Service Manager
so that you can turn SQL Server off when you’re not doing
SharePoint development.
A some great resources for getting started with Silverlight and SharePoint 2010 are
the PDC sessions which you can watch for free:
For this example we will primarily be utilizing the information in the first session
by Paul Stubbs. With SharePoint 2010, Silverlight can live just about anywhere in
the user interface, but this example will be geared toward how simple it is to publish
a Silverlight application to a SharePoint site and use it in a web part.
Fire up Visual Studio 2010 and create a new Silverlight Application:
At the prompt asking you if you want to create a web application to host the Silverlight
application uncheck the checkbox. We don’t need to host Silverlight in a separate
web app since SharePoint will be the host.
In the Silverlight Application, edit the MainPage.xaml to have the following Xaml:
<
Grid
x
:
Name
="LayoutRoot"
Background
="PowderBlue">
<
TextBlock
Text
="Silverlight
In SharePoint"
TextWrapping
="Wrap"
FontSize
="56"
FontWeight
="Bold"
/> </
Grid
>
Now let’s add the SharePoint part of the project. Before we add the SharePoint project
though we need to be running Visual Studio as the Administrator. Save your work and
close the solution. Then right click the Visual Studio 2010 shortcut and select Run
As Administrator. Back in the solution, right click the solution and select Add ->
New Project. Select SharePoint –> 2010 as the project type and select an Empty
SharePoint Project:
If you aren’t running as an Administrator then Visual Studio will tell you that
the project requires elevated permissions in order to run.
The SharePoint customization Wizard dialog will pop up asking if you want to deploy
as a sandboxed solution or a farm solution. Leave the sandboxed solution checked and
click ok. Next, right click on the SharePoint project in the Solution Explorer and
select Add -> New Item. Add a new Module to the project as shown below:
Now right click the new Module and select Properties. In the Properties window click
in the Project Output References and then click the ellipse button (…). In the Project
Output References dialog click the Add button. Expand the deployment location property
on the new reference then change the Project Name to the Silverlight project name
and the Deployment Type to ElementFile. You should end up with something that looks
like this:
Next expand the module we created in the SharePoint project and delete the Sample.txt
file. Then open the Elements.xml file. Edit the file to include the xap file that
will be generated from our Silverlight application:
<?
xml
version
="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Module Name="SilverlightModule">
<File Path="SilverlightModule\SilverlightInSharePoint.xap" Url="_catalogs/masterpage/SilverlightInSharePoint.xap" />
</Module>
</Elements>
At this point your application is ready to be deployed. Right click the SharePoint
project and select Set as Startup Project and hit F5. Visual Studio will build and
deploy your project to your local SharePoint site and then open it in the browser.
However, at this point our Silverlight application isn’t active in any of the pages.
Let’s add the Silverlight application as a web part in the default page.
On the SharePoint site click the edit icon then the insert tab, select Web Part, and
choose the Silverlight Web Part in the Media and Content category:
Click Add and in the Silverlight Web Part dialog enter the value from the Url field
in the Elements.xml file but add a leading slash. So for our example
we would enter:
/_catalogs/masterpage/SilverlightInSharePoint.xap
The web part will give you a message that it could not download the xap file. You
can ignore this message and just click the save icon. You will get the Silverlight
application on the web page, but it will look messed up:
The problem is the default size for the Silverlight Web Part is 400x300 but our text
is bigger than 300. So we need to set the size to be 400x400. Click the drop down
arrow on the top right of the web part and select Edit Web Part. In the web part properties
dialog set the height of the web part to 400 and set the chrome type to None. Click
Ok and you should get a better looking page:
Congratulations! You’ve now gotten started with Silverlight 3 and SharePoint 2010.
Silverlight development with SharePoint 2010 is much improved in this new version.
Happy SharePointing!
Tags: Application Packaging, SharePoint, Silverlight, Virtualization
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
Dropdown menus (a.k.a. flyout or DHTML menus) are fine as long as such menus are implemented in an accessible way, which to a large extent means making them keyboard friendly.
Unfortunately, most dropdown menus which we come across in the wild are not keyboard friendly. A couple of common examples:
* No real links: Sub-level links cannot be revealed without using a mouse, and top-level items are not linked to sub-pages. Not revealing the sub-menus for non-mouse users may be ok if the top-level items are actual links to pages that contain the sub-level links in a normal, visible sub-menu. That way the dropdown menus do not prevent people from navigating the site and can be seen as an enhancement for users who like them.
* Tabbing black hole: Sub-level links are not displayed on focus but exist in the tab order, which makes them technically accessible but also creates a “tabbing black hole” for non-mouse users. Since there is no visual feedback unless you use a mouse they are extremely difficult to use.
Next time you implement a dropdown menu, please make sure to avoid these problems.
Tags: .NET, C & C++, coding tips, CSS, dhtml, dropdowns, HTML, Java, Menu
While ASP.NET GridView control supports data export to Excel, Silverlight DataGrid control does not. To implement the data export, you need to retrieve data from the DataGrid and write the data to an Excel XML file (Office Open XML File Format).
1. Use Microsoft Excel application to create a new Excel spreadsheet with the format that you want for the data export. Enter a couple of dummy data and Save As XML spreadsheet. This is your Excel template.
2. Copy all the source of the above Excel template to where you will develop the data export function such as in the ExportToExcelButton_Click event. The following are partial source.

3. Use Silverlight SaveFileDialog control to create a StreamWriter instance. Call WriteLine method of the instance in each line of the copied Excel template source.

4. Running the code now, you should be able to export data to an Excel XML file, which is identical to the one you created originally in the step 1. You can use this to verify that your base code is working.
5. Replace data-driven lines with dynamic data.

6. Retrieve data from ItemsSource of the DataGrid and replace the dummy data lines with the retrieved data. (Assume entity class of Customer with single property of Name).

Tags: .NET, ASP.NET 3.5, C & C++, Office, Silverlight 3.0
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
Posted by Finasteride. on Nov 11, 2009 in
C#,
Dotnet |
View Original Article
Finasteride. Finasteride versus beta-sitsterol.
