.NET

Naming collision in ASMX web service

by Warlock on Jul.02, 2010, under .NET, C#, xml

I ran into an interesting problem today while working on an ASMX web service.

Everything compiled fine, but when I went to view the ASXM in the browser to manually invoke the methods to test it, the normal automatically generated info page didn’t come up. Trying to grab the WSDL also gave me a blank page.

I then attached the debugger to IIS to observe what was happening when I tried to view the ASMX info page. By breaking on exceptions, I was able to uncover the following error:

The XML element ‘XXX’ from namespace ‘http://tempuri.org/’ references a method and a type. Change the method’s message name using WebMethodAttribute or change the type’s root element using the XmlRootAttribute.

With a little more thinking, I was able uncover what I believe was going on.

I had defined a complex type to return as a response:

public class FooResponse {...}

[WebMethod]
public FooResponse Foo() {...}

Note that here the exact name pairing of Foo/Foo+Response is important. When I changed the method name as follows, the problem went away:

public class FooResponse {...}

[WebMethod]
public FooResponse Fooxxx() {...}

What I believe is happening is .NET is attempting to automatically wrap the response coming from the Foo method with an element named FooResponse. The use of that same name as the object you want to return creates ambiguity. By changing the name of my response object, or the name of my method I was able to avoid this collision.

I have also posted this information in response to a question on StackOverflow.

Leave a Comment more...

XSLT with Optional Extension Object

by Warlock on Dec.08, 2009, under .NET, C#, xml

Extension objects provide a convenient way to allow an XSL transform to interact with the outside world. They can also be used to offload computations that are difficult to express in XSL.

Recently, I ran into a scenario where I wanted to write an XSLT that would use an extension object to record some additional information about intermediate steps of the transform. The extension object was not required, however, and I wanted to leave it up to the user of the XSLT as to if they wanted to use the extension object.

The question then became how to conditionally execute calls to the extension object. Suppose you have the following extension object defined in C#:

public class FooExtensionObject
{
  private List<string> recordedValues = new List<string>();

  public void RecordValue(string val)
  {
    recordedValues.Add(val);
  }
}

Now suppose this extension object is used in the following XSLT:

<xsl:transform
        version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:foo="urn:FooExObj">
  <template match="/">
    ...
    <xsl:value-of select="foo:RecordValue(@bar)"/>
    ...
  </template>
</transform>

The extension object is supplied to the XSLT through the arguments:

XslTransform transform = new XslTransform();
transform.Load("SomeFile.xsl");

XsltArgumentList args = new XsltArgumentList();
FooExtensionObject aFoo = new FooExtensionObject();
args.AddExtensionObject("urn:FooExObj", aFoo);

XmlTextWriter myWriter = new XmlTextWriter("output.xml", null);

transform.Transform(xpathDoc, args, myWriter);

In the case where the extension object is not supplied, however, this XSLT will cause an error. To correct this issue, you can use the function-available function. Change the transform as follows:

...
<xsl:if test="function-available('foo:RecordValue')">
  <xsl:value-of select="foo:RecordValue(@bar)"/>
</xsl:if>
...

The conditional statement blocks out the use of the extension object when it does not exist. Unfortunately, you must do this where ever you wish to use the extension object.

Leave a Comment more...

XML Comments

by Warlock on Nov.24, 2009, under .NET, C#, Visual Studio

Today I was looking for a reference for the proper notation for the cref attribute of the <see cref="..."> C# XML comment tag, and after finding it, I thought I’d post it here for future reference.

The cref (code reference) tag is prefaced by a single character, then a colon, followed by the reference in question. The character defines what is being referenced, as defined by the table below.

Character Description
N Namespace
T Type (class, interface, struct, enum, delegate)
F Field (member variable, constant, etc)
P Property (including indexers and indexed properties)
M Method (including special methods like constructors – #ctor – operators, etc)
E Event
! Error string

The full reference for the prefixes is available here, with the full XML comment documentation available here. The Code Project also has an article on the topic.

1 Comment :, , , more...

Mapping Enums to custom strings in NHibernate

by Warlock on Jul.02, 2009, under .NET, Database

Many times when working with a legacy relation model and a newly developed C# object model that sits on top of the relational model, you may need to map enum values to/from arbitrary strings in the database using NHibernate.

For example, suppose you have a a work order object that three possible states: request, approved, denied. To represent this, you might use the following enum:

enum WorkRequestState
{
    Request,
    Approved,
    Denied
};

But let’s assume that the legacy relational model has represented these values as strings: REQ, APR, DEN. You can’t change the values for the relational model, and you certainly don’t want to use these values in your enum because they are not as readable as the values shown above.

By default, NHibernate will automatically convert you enum to a string value that matches the name of the enum values if the table field a string, or it will convert to the integer value for the enum options if the table field is an integer.

To do the above custom mapping we must implement a custom NHibernate type.

First, create a new class that inherits NHibernate.Type.EnumStringType. In your constructor, pass the type of the enum you are handling, and the maximum number of characters that the enum values will be to the base class constructor:

class WorkRequestStateEnumStringType : NHibernate.Type.EnumStringType
{
    public WorkRequestStateEnumStringType()
        : base( typeof(WorkRequestState), 3)
    {
    }
    ...
}

Next, override the GetValue(...) method to map the enum value to the equivalent string.

public override object GetValue(object enm)
{
	if( null == enm )
		return String.Empty;

	switch( (WorkRequestState)enm )
	{
		case WorkRequestState.Request	: return "REQ";
		case WorkRequestState.Approved	: return "APR";
		case WorkRequestState.Denied	: return "DEN";
		default : throw new ArgumentException("Invalid WorkRequestState.");
	}
}

Override the GetInstance(...) method to map a string value to the equivalent enum value:

public override object GetInstance(object code)
{
	code = code.ToUpper();

	if( "REQ".Equals(code) )
		return WorkRequestState.Request;
	else if( "APR".Equals(code) )
		return WorkRequestState.Approved;
	else if( "DEN".Equals(code) )
		return WorkRequestState.Denied;

	throw new ArgumentException(
		"Cannot convert code '" + code + "' to WorkRequestState.");
}

Finally, in the NHibernate mapping file, specify the property’s type as the derived EnumStringType class.

<class name="WorkRequest" table="work_request_table">
  <property
    name="Status"
    column="status_field"
    type="my.namespace. WorkRequestStateEnumStringType, MyAssembly" />
  ...
<class>

Note that when specifying this type, you must use the assembly-qualified name because the NHibernate code doing the mapping is in a separate assembly from the type you created.

This information has been derived from Jeremy Miller’s original post here.

3 Comments :, , , more...

WPF Regular Expression Test Utility

by Warlock on Jun.16, 2009, under .NET, Software Development Tools, WPF

When working on .NET applications, I frequently need to test regular expressions I’m using in my code. There are many good utilities out there to test regular expressions, but most are web-based and rely on Javascript for regular expression processing, which lacks support for .NET’s named captures.

In response, I built the a regex test utility in WPF that has the following features:

  • .NET syntax for regular expressions
  • Supports named capture groups
  • Gives real-time feedback (as you type) for the regular expression and the test input
Screenshot of regex tester.

Screenshot of regex tester.

The binary requires .NET 3.5 and is available here. The source can be found on GitHub here.

Also, for those of you working with .NET regular expressions, I’ve always found this site a great resource.

2 Comments :, more...

ASP.NET 1.1 pages/assemblies take a long time on first load

by Warlock on May.18, 2009, under .NET

The first time you load a page on an ASP.NET web site, or the first time you access a .NET web service, it may take significantly longer to load than subsequent accesses. There are several things that can cause this, including the framework compiling the aspx source pages, but there can be an even more significant delay if you are using Authenticode-signed assemblies and your server does not have access to the internet. In the case of web services, this delay may even be long enough to cause timeouts depending on the configuration of your client programs.

The problem is that as .NET loads Authenticode signed assemblies, it must check for updates on the certificate revocation list (CRL) to verify the signature on the assembly is valid. If Active Directory is not configured to have the authority for CRLs on the local network and the server in question does not have a connection to the internet, the request for the CRL will time out after approximately 15 seconds, and .NET will continue loading the assembly and consider it to be unsigned. This problem is discussed in several articles.

To verify this is what’s happening, you can use a packet sniffer on the server in question and look for the request for the CRL. Using Wireshark, I was able to observe the following behavior after I had stopped the World Wide Publishing service, started the trace, relaunched the World Wide Publishing service, and made a request:

Request for CRL

Request for CRL

The above screenshot shows that a request was made for http://crl.microsoft.com/pki/crl/products/CodeSignPCA2.crl (IP address 96.17.76.91).

Note that the request will not always be made. The CRL is always cached for the lifetime of a process, so if the IIS worker processes continue to run you will not get a request for the CRL. It’s possible that the CRL is cached for longer, though I haven’t been able to verify that this Microsoft Technet article describes many things about the Windows PKI, including CRL caching. I can replicate the above results when I first stop the World Wide Publishing service, clear the cached data from Internet Explorer, start the trace, start the World Wide Publishing, then make a request to the ASP.NET page/web service. For computers that are not connected to the internet and have not been for a long time, I would guess any caching for the CRL would expire, and every time an Authenticode signed assembly is loaded Windows would try to refresh the CRL. On Vista, you can explicitly refresh the CRL cache per this article.

Resolving this issue on .NET 2.0 post SP1 is straightforward. Setting the generatePublisherEvidence configuration option to false will skip the CRL check. This issue is discussed in Microsoft KB936707.

On .NET 1.1, things are not as straightforward. There isn’t a configuration setting to disable the authentication behavior. The only solution is to disable CRL checking for the entire machine. This can be accomplished through the following steps, originally described on this website.

  1. Open Internet Explorer
  2. Go to Tools —> Internet Options…
  3. Go to the Advanced tab
  4. Locate the Security section and uncheck the Check for publisher’s certificate revocation option.
    Disable Check for publisher's certificate revocation option.

    Disable Check for publisher's certificate revocation option.

CRL checking can also be disabled throughout the entire organization per this Microsoft Technet article.

Another option to address the symptoms as opposed to the underlying issue is to change the behavior of the IIS worker processes. As mentioned previously, the CRL is cached throughout the lifetime of a process, so by managing the lifecyle of the worker process, you can force this timeout to come during non-work hours.

In IIS manager, view properties for the app pool under which your ASP.NET application is running. Go to the Performance tab and disable the idle timeout of the worker processes.

Disable worker process idle timeout

Disable worker process idle timeout

Next, go back to the Recycling tab and set the processes to only recycle at a certain time of day (e.g. 2:00 a.m.).

Change app pool recycling to non-business hours

Change app pool recycling to non-business hours

The last step is to create a custom script that will make a request to your application shortly after the worker processes have been recycled. This will force the CRL check at a time when it doesn’t matter how long the first request takes as normal user activity won’t be interrupted.

Leave a Comment :, , , more...

Enabling Browser-Based Invocation of ASP.NET 1.1 Web Services

by Warlock on Apr.27, 2009, under .NET

When working with web services it can be helpful to manually invoke them via a browser for testing purposes. By default, .NET 1.1 is configured to let you do this from the machine on which you are running, but will not let you do it from other machines on the network.

ASP.NET without browser-based webservice invocation

ASP.NET without browser-based webservice invocation

ASP.NET with browser-based webservice invocation enabled

ASP.NET with browser-based webservice invocation enabled

To enable this feature from other computers on the network, edit the machine.config file located at C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG\machine.config. In this file, locate the section <webServices>. In the <protocols> sub-section, add the following entry: <add name="HttpPost"/>. This will result in the following configuration:


<webServices>
  <protocols>
   <add name="HttpSoap1.2"/>
   <add name="HttpSoap"/>
   <add name="HttpPost"/>
   <add name="HttpGet"/>
   <add name="HttpPostLocalhost" />
   <add name="Documentation"/>
  </protocols>
  <soapExtensionTypes>
  </soapExtensionTypes>
  <soapExtensionReflectorTypes>
  </soapExtensionReflectorTypes>
  <soapExtensionImporterTypes>
  </soapExtensionImporterTypes>
  <wsdlHelpGenerator href="DefaultWsdlHelpGenerator.aspx" />
  <serviceDescriptionFormatExtensionTypes>
  </serviceDescriptionFormatExtensionTypes>
</webServices>

As a side note, it’s the <add name="HttpPostLocalhost" /> option in the <protocols> section that enables invoking the web services locally. All of these configuration settings are documented here.

Leave a Comment more...

PowerShell Import-Csv Error

by Warlock on Apr.17, 2009, under .NET, Scripting

I ran across the following error while working with a PowerShell script I was developing:

Import-Csv : Cannot process argument because the value of argument "name" is invalid.
Change the value of the "name" argument and run the operation again.

It had me stumped for a while. The Impor-Csv command was failing, but the file name was good (I could cat the files contents to standard out).

Long story short, the error came from having trailing blank columns in my CSV. Import-Csv uses the first row in the CSV as names for the columns (unless you specify otherwise) and when you have blank columns (or at least multiple blank columns) it causes this error as it doesn’t have a valid name for them. The underlying culprit for the error was actually Microsoft Excel. I was exporting a spreadsheet to a CSV and the spreadsheet had previously had some trailing columns. I values to the columns, but apparently Excel decided they should still show up in the export. Fully deleting the columns so they didn’t show up in the CSV resolved the problem.

6 Comments :, more...

Retrieving the Logged-in User’s Email via AD

by Warlock on Apr.02, 2009, under .NET

I was writing a test utility yesterday and I wanted to get the email address for the user who is currently logged into the computer. The only way I could think of was to query Active Directory for it, so I ended up with the following code:

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

private string GetCurrentUserEmailAddress()
{
    string ldapPath = "";
    string filter = "";

       Domain d = Domain.GetCurrentDomain();

       foreach (string e in d.Name.Split('.'))
       {
           if (ldapPath.Length > 0)
               ldapPath += ",";

           ldapPath += "DC=" + e;
       }

       ldapPath = "LDAP://" + ldapPath;
       filter = "(&(objectClass=user)(SAMAccountName="
                     + System.Environment.UserName + "))";

       DirectoryEntry de = new DirectoryEntry(ldapPath);
       DirectorySearcher ds = new DirectorySearcher();
       ds.Filter = filter;

       SearchResult sr = ds.FindOne();

       if (null == sr)
           throw new Exception("Failed to get user for path '"
                    + ldapPath + "' and filter '" + filter + "'.");

       return sr.Properties["mail"][0].ToString();
}

The basic gist of it is as follows:

  1. Use the AD administrative classes to determine the active domain
  2. Convert the domain into a valid LDAP path to act as the root of the query
  3. Create a filter for the LDAP query using the login name of the user
  4. Run the query against AD and pull down the user’s email address

I’ve only tested the above code on a few computers but it seems to work.

1 Comment : more...

Customizing Your Powershell Prompt

by Warlock on Mar.30, 2009, under .NET, Scripting

Powershell is a great CLI for Windows and I appreciate it’s design more and more every time I use it. As I interactive with for more and more tasks, wanted to customize it a bit so that it looked prettier, and so I could visually distinguish what was going on more easily.

One thing I’ve always done in the *NIX world was add color to my prompt so that it would be easy for me to tell where each command/output sequence started and ended. To do this you need to edit (or create) the file <My Documents>\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

To determine how to render the prompt, Powershell calls a function, prompt. To change the appearance, just implement this function in your profile. Mine is as shown below:

Write-Host -nonewline "Welcome to PowerShell "
Write-Host -nonewline -foregroundcolor Magenta $env:Username
Write-Host "!"
Write-Host " "

function prompt {
            Write-Host -nonewline -foregroundcolor Magenta "PS "
            Write-Host -nonewline -foregroundcolor Green $(get-location)
            Write-Host -nonewline -foregroundcolor Magenta " >"
            " "
}

Note that the output uses the -foregroundcolor flag with Write-host to change the output color. Also note that built-in variables are used to determine context information, such as the current location.

This blog post worked a quick reference for me.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...