I started playing with the .NET Framework 4.0 composition namespace (also known as MEF) and I want to share the most simple example I could write. The program prints out the providerName field, but the actual value is provided by the ExternalProvider class. The CompositionContainer class is able to wire the ExternalProvider.Name property and the Program.providerName field using the Export and Import attributes.
Add the System.ComponentModel.Composition.dll assembly to your project’s references.
Really simple, I think.
- using System;
- using System.ComponentModel.Composition;
- using System.ComponentModel.Composition.Hosting;
- using System.Reflection;
- class ExternalProvider {
- [Export("ProviderName")]
- public string Name {
- get {
- return "Spider";
- }
- }
- }
- class Program {
- static void Main() {
- new Program().Run();
- }
- [Import("ProviderName")]
- string providerName;
- void Run() {
- new CompositionContainer(new AssemblyCatalog(Assembly.GetExecutingAssembly())).ComposeParts(this);
- Console.WriteLine(this.providerName);
- }
- }
If you need to run MS Test command line utility as a 64-bit process you need to do 2 things:
Disclaimer: Be aware that this is not supported and it is under you own risk.
1. Backup the MSTest.exe file first and then remove the 32-bit flag by running the CorFlags.exe utility as:
CorFlags.exe MSTest.exe /32BIT- /Force
2. Run your test with /noisolation switch to run tests within the MSTest.exe process and avoid using 32-bit only VSTestHost.exe
MSTest.exe /testcontainer:<your assembly> /resultsfile:results.trx /noisolation
And optionally, if MSTest.exe fails because the 32-bit flag was modified, you may want to skip the strong name verification:
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\StrongName\Verification\MSTest,b03f5f7f11d50a3a /f
Do a web request using System.Net classes, HttpWebRequest or WebClient. For example:
new WebClient().DownloadFile("http://tinyurl.com/d5yy8a", @"C:\Temp\file.xml");
Or:
HttpWebRequest.Create("http://tinyurl.com/d5yy8a").GetResponse();
If the first request takes more than 4 seconds and you think is too much time for your application, then the following information may interest you.
The reason the first request takes more time is because it tries, by default, to detect the proxy setting in a weird way. The framework uses an embedded JavaScript code for doing the detection, but the first time it does it’s job, it spends more time “dynamically compiling” the JavaScipt code than executing the actual proxy detection logic.
One way to skip this detection is by setting the proxy settings yourself, either by code or by using a configuration file like this:
<configuration>
<system.net>
<defaultProxy>
<proxy
proxyaddress="http://ContosoProxy:80"
autoDetect="False" />
</defaultProxy>
</system.net>
</configuration>
If that solution doesn’t suits you, another way is do the proxy detection yourself (well, with the help of WinHttp.dll). It happens that there is a library in Windows XP, 2003, Vista, 7, called WinHttp.dll that exposes useful methods for proxy detection and in order to use it we just need some P/Invoke code and P/Invoke is by far faster than compiling the embedded JavaScript.
WinHttpGetProxyForUrl can be used for detecting the proxy for an URL and the function WinHttpGetIEProxyConfigForCurrentUser is useful if you want to read the proxy configuration from Internet Explorer. In this example I won’t do the IE proxy configuration reading just to keep it simple.
WinHttpGetProxyForUrl return a list of proxies to use. That list may look like a list of IP address separated by colons. In the example below I split that list and pre-append the http:// suffix if needed so it can became a valid URL. This example just picks the first proxy address and uses it. You can later on add logic to try multiple proxies if the request fails, just remember that once you use a HttpWebRequest object, you cannot re-use it, you need to create a new one and also keep the tracking of the all the timeout so you don’t end waiting 1 hour before timeout. If you use WebClient, you can override the method GetWebResponse and set the proxy there, just don’t eat the WebException exceptions that have a Status equals WebExceptionStatus.ProtocolError since that is actually a valid response.
Using normal System.Net proxy detection I get the output:
MS:7537
MS:41
MS:39
…
Using WinHttp.dll I get:
MS:410
MS:11
MS:11
…
Here you have:
http://code.msdn.microsoft.com/WinHttp
In my previous post I explained how to collect ETW events from URL Rewrite (or any other IIS provider) and then display those structured events in the Event Viewer. Now I want to show you how to collect ETW events using C#.
The .NET Framework 3.5 provides a new namespace System.Diagnostics.Eventing.Reader where you can find useful classes for publishing ETW events, but doesn’t provide a mechanism for consuming, so I had to write a class EventTraceWatcher for simplify things.
I want to use this class for tracking, in real time, all the URL Rewrite Events.
Setup Event Trace Session
The first thing to do is to setup the session, open “Reliability and Performance Monitor”, go to Event Trace Sessions and add a new Data Collector Set named “Rewrite”; my previous post has more detailed steps, once you create the collector set, go to its properties and add the provider “IIS: WWW Server” and the Keyword 0x400 (Rewrite) and set the Level to 5. Here is how it should be:
Use stream mode “Real Time”
By default the Data Collector Set will write the collected events in the file system. Change it from File to “Real Time”. Your .NET Application will be listening those real time events. Open the data collector properties and in the Trace Session tab change this setting.
Make sure to start the Rewrite Collector once you are finish with this settings.
EventTraceWatcher class
The EventTraceWatcher class is very trivial to use, you need to provide the name of the Data Collector Set to it’s constructor (“Rewrite” in our example), hook the event “EventArrived” in your code and then just set the property Enabled to true to start the asynchronous processing of the ETW Events.
using System;
using Microsoft.Iis.Samples.Eventing;
class Program {
static void Main() {
try {
new Program().Run();
}
catch (Exception ex) {
Console.Error.WriteLine(ex);
}
}
private void Run() {
Guid RewriteProviderId = new Guid("0469abfa-1bb2-466a-b645-e3e15a02f38b");
using (EventTraceWatcher watcher = new EventTraceWatcher("Rewrite")) {
watcher.EventArrived += delegate(object sender, EventArrivedEventArgs e) {
if (e.EventException != null) {
// Handle the exception
Console.Error.WriteLine(e.EventException);
Environment.Exit(-1);
}
// Process only URL Rewrite events
if (e.ProviderId != RewriteProviderId) {
return;
}
// Dump the event name (e.g. URL_REWRITE_START, ABORT_REQUEST_ACTION, etc).
Console.WriteLine("Event Name: " + e.EventName);
// Dump properties (e.g. RewriteURL, Pattern, etc).
foreach (var p in e.Properties) {
Console.WriteLine("\t" + p.Key + " -- " + p.Value);
}
Console.WriteLine();
};
// Start listening
watcher.Enabled = true;
// Listen events until user press <Enter>
Console.WriteLine("Press <Enter> to exit");
Console.ReadLine();
}
}
}
With this code you can write tools to help you to filter in real time information from IIS. Download the EventTraceWatcher class from:
http://code.msdn.microsoft.com/EventTraceWatcher
IIS Failed Request Tracing is a powerful way to troubleshoot Web Requests, it provides an easy way to track each execution step for one specific request. URL Rewrite Module provides several events that can be tracked using Failed Request Tracing, here is an article that explains how: http://learn.iis.net/page.aspx/467/using-failed-request-tracing-to-trace-rewrite-rules/
IIS Modules have the ability to publish ETW Events almost for free and URL Rewrite was not the exception and implemented this feature. There are many ways to listening for ETW Event, but one way that I found really easy is using the Event Viewer and the Reliability and Performance tools in Windows 2008 (and Vista).
I’m running Windows 2008, so let me show you how to listen the URL Rewrite ETW events using the Server Manager tool.
- Be sure IIS Failed Request Tracing is enabled by following the article above.
- Open Server Manager and navigate to Server Manager / Diagnostics / Reliability and Performance / Data Collector Sets / Event Trace Sessions
- In the Action Pane select More Actions > New > Data Collector Set
- Choose a Name and click Next
- In the “Which event trace providers would you like to enable?” step, click Add (wait some seconds) and choose “IIS: WWW Server”:
- Choose the property “Keywords(Any)” and click Edit. For URL Rewrite events, you need to choose Manual and type the value 0x400. You can optionally mix this value with any other flag available like IISSecurity or IISModule (0x200); if you select Automatic and the flag, you will see in the Manual text box the flag value. Click OK to close the Property dialog.
- Now choose the property “Level” and click Edit, this time select Manual and type the number 5. Click OK and the Finish.
- A new Event Trace Session has been created. You can click the Start button any time to start listening and recording all the URL Rewrite events.
- By default, all the recorded data will be stored in the directory %LOCALAPPDATA%, to change this, select the session “URL Rewrite” and choose Properties from the contextual menu. There is a Directory and File tabs change your settings.
Let’s do a break. At this point you had configured Windows to start listening URL Rewrite events; those events will be recorded in a ETL file that can be processed by many tools like Log Parser and TraceRpt.exe. To display those event in the Event Viewer you need:
- In the Server Manager tool, navigate to Server Manager / Diagnostics / Event Viewer / Application And Services Logs
- Click the action Open Saved Log and choose the ETL file, if you didn't’ change the default settings, it should be at “%LOCALAPPDATA%\URL Rewrite.etl”. Click OK to close the “Open Saved Log” dialog.
- Select the URL Rewrite log from the Saved Logs folder:
- Now you will realized that the Event Viewer only has one part of the information available, the ETL file, it still needs to match that data to some other metadata stored in the WMI repository store in order to show you the formatted data.
- Select the “URL Rewrite” log and click the action “Save Events As” and safe the log as “URL Rewrite Events.evtx” (note the new extension).
- Once saved, open the new file using, again, the action “Open Saved Log”
- Now you click any Event in the list. The General tab won’t show anything relevant, but the Details will:
I will have some conclusions later, I have to leave now. Hope you find it somehow useful.
The GoLive release of URL Rewrite Module is now available and has a lot of improvement thanks to the IIS Community feedback (and tons of internal brainstorm meetings!). A new feature is the ability to create Rewrite Rules by using Rewrite Templates, Rewrite Templates are UI extensions that help to simplify the creation of rules.
URL Rewrite Module includes 3 templates and more interesting, it allows you to add your own Rewrite Template.
Take a look to the following walkthrough if you haven’t play with Rewrite Templates:
http://learn.iis.net/page.aspx/497/user-friendly-url---rule-template/
I want to show you how easy is to write your own Rewrite Template extension, here is how this demo should look like:

As you know, iis.net has already some good articles that explain how to create an IIS Manager UI Module, so allow me to reuse the following article:
http://learn.iis.net/page.aspx/269/how-to-create-a-simple-iis-manager-module/
Follow the article above and once you are done with it, please do the following changes.
- Add the assembly Microsoft.Web.Management.Rewrite.Client.dll to your C# project. If you can’t find the assembly reference in the GAC, download it from here.
- Replace the code in DemoModule.cs by the following code that registers your extension in the URL Rewrite UI Module:
using System;
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Iis.Rewrite.RewriteTemplates;
using Microsoft.Web.Management.Server;
namespace ExtensibilityDemo
{
internal sealed class DemoModule : Module
{
protected override void Initialize(IServiceProvider serviceProvider, ModuleInfo moduleInfo)
{
base.Initialize(serviceProvider, moduleInfo);
IExtensibilityManager extensibilityManager = (IExtensibilityManager)
GetService(typeof(IExtensibilityManager));
extensibilityManager.RegisterExtension(typeof(RewriteTemplateFeature),
new DemoRewriteTemplateFeature(this));
}
}
}
- Add a new file named DemoRewriteTemplateFeature.cs and copy and paste following code:
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Iis.Rewrite.RewriteTemplates;
using System.Windows.Forms;
namespace ExtensibilityDemo
{
internal sealed class DemoRewriteTemplateFeature : RewriteTemplateFeature
{
private const string FeatureTitle = "Rewrite Extensibility Demo";
private const string FeatureDescription = "Demonstrates the UI Extensibility.";
public DemoRewriteTemplateFeature(Module module)
: base(module, FeatureTitle, FeatureDescription, null, null)
{
}
public override void Run()
{
Form form = new Form();
form.Text = "URL Rewrite Extensibility Demo";
form.StartPosition = FormStartPosition.CenterParent;
form.ShowDialog();
}
}
}
Colorized by: CarlosAg.CodeColorizer
Download the demo from here:
To install it, you will need to GAC the assembly RewriteExtensibilityDemo.dll and register the module in administration.config by adding the following entry under the moduleProviders section:
<add name="RewriteExtensibilityDemo"
type="ExtensibilityDemo.DemoModuleProvider, RewriteExtensibilityDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8975c3932a2fc4ae" />
Last week we shipped the first preview of URL Rewrite Module for IIS 7.0. If you are not familiar with URL Rewriting engines, please check out the walkthroughs:
http://learn.iis.net/page.aspx/460/using-url-rewrite-module/.
If you are you familiar with mod_rewrite, I’m pleased to let you know that we have a mod_rewrite rule importer feature to help you to leverage your rule-crafting knowledge:
http://learn.iis.net/page.aspx/470/importing-apache-modrewrite-rules/
URL Rewrite Module ships two matching engines, one for Regular Expressions (Perl 5 compatible/ECMAScript) and a simple one for wildcard matching. You can choose the engine you feel more comfortable with, I just want to give you some facts (some of them are silly but they are just a reminder):
1. Regex matching is more powerful, but expensive in terms of execution time.
2. Wildcard matching is cheaper than Regex and easy to understand.
3. Both engines are case-insensitive by default.
4. Case-sensitive matching has much better performance than case-insensitive.
5. Wildcard matching assumes “exact match”. For an expression like “blog”, it would match “blog” and only “blog”.
6. Regex matching assumes “partial match”. In this case, “blog” will match “blogger”, “demo/blog”. If you want an exact match you need to change the match expression to “^blog$”.
7. In Regex, “.” is reserved, it means “any character”, so “default.aspx$” will match “defaultXaspx” too. Escape it to “default\.aspx$’. Wildcards doesn’t have this behavior, the only reserved character is ‘*’.
8. To create a capture in Regex, use parenthesis.
9. Each ‘*’ in a wildcard expression creates a capture. For example, an expression like “*.*” would match “logo.jpg” and it will create 2 captures, “logo” and “jpg” (without the dot).
10. You can reference a capture by index. The index is 1-based, so in the previous example 1 means “logo” and 2 means “jpg”.
11. The index 0 means “the entire input”. In the previous example 0 means “logo.jpg”.
12. The syntax for back-reference a capture is {type:index} where type can be R for “Rule Back References” and “ C for “Condition Back References”. The index must be and integer equals or greater than zero.
Please give all the feedback you want, this is a technical preview so your feedback can definitely make a difference for the next release.
Install it from:
Microsoft URL Rewrite Module for IIS 7.0 CTP1 (x86)
Microsoft URL Rewrite Module for IIS 7.0 CTP1 (x64)
URL Rewrite Forum:
http://forums.iis.net/1152.aspx
I hadn't posted since two years ago; a lot of things happen in such a time and now I'm part of the IIS team. I'm not sure about what to talk about, so I will start with random stuff.
I found debugging very task oriented, there are a bunch of ways to get an answer to the same question; let's say that someone gave you a machine ready to be debugged in kernel mode and you want to do .tlist -v to list all the processes and the additional information such as PID, Session, Command Line. If you are using a remote machine to access the target machine in kernel mode, .tlist will give you the process in the remote machine; to get the processes in the target machine and dump process information such as the Command Line arguments follow the next steps:
1. List the processes.
kd> !process 0 0
**** NT ACTIVE PROCESS DUMP ****
PROCESS 8447b790 SessionId: none Cid: 0004 Peb: 00000000 ParentCid: 0000
DirBase: 00122000 ObjectTable: 830002d8 HandleCount: 580.
Image: System
... (some other processes)
PROCESS 867b7d90 SessionId: 0 Cid: 07a4 Peb: 7ffdf000 ParentCid: 0a00
DirBase: 7ea6b560 ObjectTable: 83170470 HandleCount: 60.
Image: appcmd.exe
2. Look for your process and copy the DirBase property, in this example I will use appcmd.exe (7ea6b560), and switch to the process' context:
kd> .context 7ea6b560
3. Dump the process information, that information includes the command-line
kd> !peb
PEB at 7ffdf000
InheritedAddressSpace: No
ReadImageFileExecOptions: No
BeingDebugged: No
.... (more information)
ImageFile: 'D:\Windows\System32\inetsrv\appcmd.exe'
CommandLine: 'D:\Windows\System32\inetsrv\appcmd.exe clear config -section:system.web
Server/cgi'
Hi there!, I'm a development consultant at MS Mexico. I'd been bloging at http://danielvl.blogspot.com and now it's time to move to this new home :)
I'm going to share whatever I have learned from the CLR, design and some Servers (e.g. BizTalk). Currently, I am working in a earlier implementation of WS-RM and there has been a lot of fun :), I'm going to share some C#/C++ code and tools that hope you migh found useful!