Tag Archive for CodeSnippets

Tales from the Unmanaged Side – System.String –> char* (pt. 2)

A while ago, I posted an entry about marshalling a managed System.String into an unmanaged C string, specifically a plain char*. The solution I suggested, back in 2007, involved calling Marshal::StringToHGlobalAuto method to allocate memory and copy the string data into it, and then cast the HGlobal pointer into a char*.

It seems that in Visual Studio 2008 a new way of doing it was added, as part of the new Marshalling Library. This library provides a whole set of conversions between System.String and popular unmanaged string representations, like char*, wchar_t*, BSTR, CStringT and others I am even less familiar with.

The smarter string representations, like std::string, have their own destructors so I can carelessly let them drop out of scope without worrying about leaks. The more primitive ones, like char*, need to be explicitly released, so that’s why the Marshalling Library contains a new (managed) class called marshal_context which gives me exactly this explicit release.

Let’s compare my old code with the new:

   1:  const char* unmanagedString = NULL;
   2:  try
   3:  {
   4:      String^ managedString = gcnew String("managed string");
   5:      // Note the double cast.
   6:      unmanagedString = (char*)(void*)Marshal::StringToHGlobalAnsi(managedString);
   7:  }
   8:  finally
   9:  {
  10:      // Don't forget to release. Note the ugly casts again.
  11:      Marshal::FreeHGlobal((IntPtr)(void*)unmanagedString);
  12:  }

And the new:

   1:  marshal_context^ context = gcnew marshal_context();
   2:  String^ managedString = gcnew String("managed string");
   3:  const char* unmanagedString = context->marshal_as<const char*>( managedString );
 

Much shorter, I’m sure you’ll agree. And neater – no need for all the icky, icky casting between different pointer types. And most importantly, I don’t have to explicitly release the char* – the marshal_context class keeps a reference to all the strings that were marshalled through it, and when it goes out of scope its destructor makes sure to release them all. Very efficient, all in all.

Static Constructor throws the same exception again and again

Here’s a little gotcha I ran into today – if you have code in a class’s static constructor that throws an exception, we will get a TypeInitializationException with the original exception as the InnerException – so far, nothing new.

However, if we keep on calling methods on that object, we’ll keep receiving TypeInitializationExceptions. If it cannot be initialized, it cannot be called. Every time we try, we’ll receive the exact same exception. However, the static ctor will not be called again. What appears to happen is that the CLR caches the TypeInitializationException object itself, InnerException included, and rethrows it whenever the type is called.

What are the ramifications? Well, we received an OutOfMemoryException in our static ctor, but the outer exception was caught and tried again. So we got an OutOfMemoryException again, even though the memory problem was behind us, which sent us down the wrong track of looking for persistent memory problems. Theoretically, it could also be a leak – the inner exception holding some sort of reference that is never released, but that’s an edge case.

Here’s some code to illustrate the problem. The output clearly shows that while we wait a second between calls, the inner exception contains the time of the original exception, not any subsequent calls. Debugging also shows that the static ctor is called only once.

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:   
   6:          for (int i = 0; i < 5; i++)
   7:          {
   8:              try
   9:              {
  10:                  Thread.Sleep(1000);
  11:                  StaticClass.Method();
  12:   
  13:              }
  14:              catch (Exception ex)
  15:              {
  16:                  Console.WriteLine(ex.InnerException.Message);
  17:              }
  18:          }
  19:   
  20:          Console.ReadLine();
  21:      }
  22:  }
  23:   
  24:  static class StaticClass
  25:  {
  26:      static StaticClass()
  27:      {
  28:          throw new Exception("Exception thrown at " + DateTime.Now.ToString());
  29:      }
  30:   
  31:      public static void Method()
  32:      { }
  33:   
  34:  }

Upgrading all projects to .NET 3.5

A simple macro to change the Target Framework for a project from .NET 2.0 to .NET 3.5, hacked together in a few minutes. This will fail for C++/CLI projects, and possibly VB.NET projects (haven’t checked). Works fine for regular C# projects, as well as web projects:

 

For Each proj As Project In DTE.Solution.Projects
   Try
       proj.Properties.Item("TargetFramework").Value = 196613
       Debug.Print("Upgraded {0} to 3.5", proj.Name)
   Catch ex As Exception
       Debug.Print("Failed to upgrade {0} to 3.5", proj.Name)
   End Try

Next proj

Why 196613, you ask? Well, when I see such a number my first instinct is to feed it into calc.exe and switch it to hexadecimal. And I was right: 196613 in decimal converts to 0x00030005 – You can see the framework version hiding in there. Major version in the high word, minor in the low word. The previous TargetFramework number was 131072 – 0x00020000, or 2.0.

 

(Nitpickers might point out that I could simply set it to &30005 rather than messing with the obscure decimal number. They would be correct – but I got to this number through the debugger, so that’s how it will stay)

System.Diagnostics.EventLogEntry and the non-equal Equals.

Just a quick heads-up in case you’re stumped with this problem, or just passing by:

The System.Diagnostics.EventLogEntry class implements the Equals method to check if two entries are identical, even if they’re not the same instance. However, contrary to best practices, it does NOT overload the operator==, so these two bits of code will behave differently:

EventLog myEventLog = new EventLog("Application");
EventLogEntry entry1 = myEventLog.Entries[0];
EventLogEntry entry2 = myEventLog.Entries[0];

bool correct = entry1.Equals(entry2);
bool incorrect = entry1 == entry2;

After running this code, correct will be true while incorrect will be false.

Good to know, if you’re reading event logs in your code.

Displaying live log file contents

I’m writing some benchmarking code, which involves a Console application calling a COM+ hosted process and measuring performance. I want to constantly display results on my active console, but since some of my code is running out-of-process, I can’t really write directly to the console from all parts of the system. Not to mention the fact that I want it logged to a file as well.

So I cobbled together a quick Log class that does two things – it writes to a shared log file, keeping no locks so several processes can access it (I do serialize access to the WriteLine method itself, though). I don’t mind the overhead of opening/closing the file every time, since this isn’t production code.

The second method is the interesting one – it monitors the log file and returns every new line that is appended to it. If no lines are available, it will block until one is reached. The fun part was using the yield return keyword, which I’ve been looking for an excuse to use for quiet a while now.

Note that there are many places this code can go wrong or should be improved. There is no way to stop it running, only when the application is stopped. I bring this as the basic idea, and it can be cleaned up and improved later:

   1: public static IEnumerable<string> ReadNextLineOrBlock()
   2:         {
   3:             // Open the file without locking it.
   4:             using (FileStream logFile = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
   5:             using (StreamReader reader = new StreamReader(logFile))
   6:             {
   7:                 while (true)
   8:                 {
   9:                     // Read the next line.
  10:                     string line = reader.ReadLine();
  11:                     if (!string.IsNullOrEmpty(line))
  12:                     {
  13:                         yield return line;
  14:                     }
  15:                     else
  16:                     {
  17:                         Thread.Sleep(100);
  18:                     }
  19:                 }
  20:             }
  21:         }

This method can now be called from a worker thread:

 

   1: private static void StartListenerThread()
   2:         {
   3:             Thread t = new Thread(delegate()
   4:             {
   5:                 while (true)
   6:                 {
   7:                     foreach (string line in Log.ReadNextLineOrBlock())
   8:                     {
   9:                         // I added some formatting, too.
  10:                         if (line.Contains("Total"))
  11:                             Console.ForegroundColor = ConsoleColor.Green;
  12:                         
  13:                         Console.WriteLine(line);
  14:  
  15:                         Console.ForegroundColor = ConsoleColor.White;
  16:                     }
  17:                 }
  18:             });
  19:  
  20:             t.Start();
  21:         }

Dynamically creating a Sharepoint Web-Service proxy instance

In my current code, I find myself accessing many Sharepoint web services. In one run of code I can access 5-6 different web services on dozens of different sites, not necessarily even on the same server. Given that I find myself writing a lot of boilerplate code looking like this:

using (SiteData siteDataWS = new SiteData())
{
   siteDataWS.Credentials = CredentialsCache.DefaultNetworkCredentials;
   siteDataWS.Url = currentSite.ToString() + “/_vti_bin/SiteData.asmx”;

   // Do something with the WS.
}

Seeing as this is quite wearisome, I’ve decided to go an genericize it. Given also that the name of the ASMX file for all Sharepoint services is the same as the name of the class to be instantiated, it gets even shorter:

1:  public static WSType CreateWebService (Uri siteUrl) where WSType : SoapHttpClientProtocol, new()
2: {
3:    WSType webService = new WSType();
4:    webService.Credentials = CredentialCache.DefaultNetworkCredentials;

5:    string webServiceName = typeof(WSType).Name;
6:    webService.Url = string.Format(“{0}/_vti_bin/{1}.asmx”, siteUrl, webServiceName);

7:    return webService;
8: }

Line 1: Define a generic method that receives the type of Web Service and returns an instance of it. Note the generic constraints – the type must be a Web Service Proxy (SoapHttpClientProtocol) and must be instantiable. The last one is necessary for line 3 to compile.

Line 5: Get the name of the type – for our example above it would be “SiteData” – and build the URL based on the site URL and the web service name.

Now I can transform the above snippet to this:

using (SiteData siteDataWS = WebServiceHelper.CreateWebService(currentSite))
{
   // Do something with the WS.
}

Drastic change? No, not really. But it keeps things clean.

Allowing timeout on long-running operations – possible bug

A while ago, I wrote about a simple pattern to allow us to put a timeout limitation on a long running operations. Simply put, it allows us to replace this:

public MyObject GetData()
{
   try
   {
      MyObject data = BigComponent.LongRunningOperation();
      return data;
   }
   catch (Exception ex)
   {
      // Log and rethrow.
      throw;
   }
}

with this:

public MyObject GetData()
{
   try
   {
      MyObject data;
      Thread t = new Thread(
                           delegate()
                           {
                              data = BigComponent.LongRunningOperation();
                           });
      t.Start();
      bool success = t.Join(timeoutForOperation);
      if (success)
      {
         reutrn data;
      }
      else
      {
         throw new TimeoutException();
      }
  
      return data;
   }
   catch (Exception ex)
   {
      // Log and rethrow.
      throw;
   }
}

This pattern, while simple at first, introduced a bug into my design that in retrospect should be glaringly obvious. The bug is that although my component previously caught exceptions in LongRunningOperation, this method is now called in a different thread and not handled by my try/catch. This is hard to see when using anonymous delegates, since you get the feeling that it’s still a part of the parent method.

In .NET 2.0, the default behavior for an unhandled exception in a thread is to abort the whole process. In my case, it was an out-of-process COM+ service doing some heavy data crunching for us, and the result was a pop-up(!) on the server complaining that the COM Surrogate crashed. Took me a while to figure out what I did wrong.

One way of solving this is to simply wrap the code i nside the delegate with try/catch and swallow the exception. But that way I lose the information about the inner exception, which I want to propagate upwards. What I ended up doing is somewhat uglier, and involves passing the exception backwards the way I did with the data:

MyObject data;
Exception exceptionInProcess;
Thread t = new Thread(
                     delegate()
                     {
                        try
                        {
                           data = BigComponent.LongRunningOperation();
                        }
                        catch (Exception ex)
                        {
                           exceptionInProcess = ex;
                        });

if (exceptionInProcess != null)
{
   throw exceptionInProcess;
}

Retrieving all properties for a Sharepoint list

When we call the GetListItems or GetListItemChanges methods in Sharepoint’s Lists Web Service, we pass an XmlNode parameter specifying which fields we want to return, in this format:


  

Now, if we leave this field as null, we get a certain set of properties back – Name, Last Modified and so forth. Basic, commonly used properties. However, if we want to return ALL properties, and we don’t want to explicitly state them, we need to pass an XmlNode with an empty-but-valid ViewFields XML:

XmlDocument doc = new XmlDocument();
XmlNode viewFields = doc.CreateElement(“ViewFields”);
XmlNode results = wsLists.GetListItemChanges(myListGuid, viewFields, since, null);

Now I get a whole handful of properties to read to my heart’s delight.

All info via Karthikeyan‘s blog.

Granting User Rights in C#

As a follow-up to my previous post about changing a Windows Service’s user account – there was one think I forgot.

In order for a user to run a service, that user must be granted the “Run as Service” right by the operating system. Usually it’s not a problem – the Services MMC snap-in automatically adds that right to a user we choose, and the ServiceProcessInstaller that we get when creating services in .NET also contains code to grant that right. The problem is when we’re doing it ourselves through our code – the Change() method on the Win32_Service WMI object doesn’t grant that right, and the only other WMI classes that seemed relevant, the RSoP classes, seem to be read-only classes that give us auditing and reports on what user rights are granted, but don’t let us manage them.

In other words, it’s back to P/Invoking. This time – the LsaOpenPolicy, LsaAddAccountRights and LsaClose methods.

Luckily for me, the work was already done. Much furious googling led me to a two year old forum post by MVP Willy Denoyette, with his managed wrapper class around these Win32 methods. It was written for .NET 1.1, probably, and uses some P/Invoke calls for things that have since been incorporated into .NET 2.0, like getting account SIDs. Never mind. It works fine, and that’s all I need.

Technically, I could build a list of constants for the specific logon rights, but for now this is the only one I need:

private static void GrantLogonAsServiceRight(string username)
{
   using (LsaWrapper lsa = new LsaWrapper())
   {
      lsa.AddPrivileges(username, “SeServiceLogonRight”);
   }
}

Setting Windows Service Account – C# and WMI

I’ve been busting my brains for over two hours trying to accomplish a relatively simple task – changing the username and password of a currently running Windows Service. Should be trivial enough, but the managed ServiceController class doesn’t give me that ability, so I had to resort to more esoteric solutions.

Assuming I wish to avoid direct registry manipulation – an easy enough choice to make – I can either P/Invoke the ChangeServiceConfig method (from advapi32.dll) or use System.Management and call the Win32_Service WMI class. I decided to use as little interop as possible and headed down the WMI path.

Now, Win32_Service doesn’t have a property for the user password, which makes sense for security reasons. What I can do is invoke the Change method on it, passing it the username and password. Unfortunately, Change accepts 11 different parameters that can be changed, most of which I wish to leave untouched.

I tried using MgmtClassGen.exe to generate a strongly-typed wrapper around Win32_Service, but the Change method is created for me needed work – it asked for an ErrorControl parameter as a Byte, for instance, but the ErrorControl property was strongly typed as a String – I had to start tweaking the parameters myself, receiving strange exceptions and potentially modifying properties I didn’t want to.

 Most code samples I could find refer to VBscript, which can simply not pass the parameters it doesn’t want, but C# isn’t as flexible. Ultimately, though, I decided to simulate this approach by simply passing null for any parameters I want untouched. This requires me to work without the MgmtClassGen class, and invoke the Change method untyped, like this. I can’t say it’s code I’m especially proud of, but it gets the work done.

string objPath = string.Format(“Win32_Service.Name='{0}'”, serviceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
   object[] wmiParams = new object[11];
   wmiParams[6] = username;
   wmiParams[7] = password;
   service.InvokeMethod(“Change”, wmiParams);
}