Blog Home  Home Feed your aggregator (RSS 2.0)  
Eric Malamisura's Blog - .NET
Geek Ramblings
 
 Thursday, April 24, 2008

So I have been working on a project where we are taking the existing data access code which is in pretty bad shape and we are trying to redesign and redo most of it using LINQ to SQL.  So after some research and reading from Scott Gu, LINQ in Action, and MSDN White Paper about how to use LINQ to SQL I noticed most of the examples they provide are overly immature.  They play like everything is great, and just drop it all in your code behind, or have a single layer of responsibility and it will all just work like magic!!  This sounded to good to be true, and after my experience it really is too good to be true!

 

So in this series of articles I am going to go through all of the things that we encountered.  The first thing you will run into with LINQ to SQL is that the DataContext is stateful and this is particularly concerning if you are planning to use it in a stateless environment like ASP.NET.  You can download the source code to the Northwind sample project that follows the design that is being discussed in this series here.

 

Below is a list of the issues we encountered while using LINQ to SQL and how we dealt with these issues.

  • DataContext Lifetime Management (Part 1)
  • Entity Persistence (Part 2)
  • Data Concurrency (Part 3)
  • N-Tier Design (Part 4)

DataContext Lifetime Management

So how do you manage the lifecycle of the DataContext?  There is a pretty good article (LINQ to SQL DataContext Lifetime Management) about this on Rick Strahl's blog and I won't cover what he already has in his article, I would recommend going to go read it and take from what you want.  I borrowed multiple concepts from his article and adapted them to my needs.

 

The solution we chose was keep the HttpContext around per a HTTP request, this was achieved by writing an HttpModule and creating an instance of this DataContext and storing in the HttpContext.Current.Items collection.  Now using this method you will have access to the same DataContext per a page request essentially, so you can do all of your work against a single DataContext and then submit it.

 

Below is the code that was used for storing the DataContext in a web application:

 

   10 public class WebContextStorage : IContextStorage

   11     {

   12         public WebContextStorage()

   13         {

   14 

   15         }

   16 

   17         #region IContextStorage Members

   18 

   19         public T GetItemContext<T>(string key)

   20         {

   21             Dictionary<string, object> storage = GetDictionaryFromStorage();

   22             return (storage == null) ? default(T) : (storage.ContainsKey(key) ? (T)storage[key] : default(T));

   23         }

   24 

   25         public void SetItemContext<T>(string key, T item)

   26         {

   27             Dictionary<string, object> storage = GetDictionaryFromStorage();

   28 

   29             if (storage == null)

   30             {

   31                 storage = new Dictionary<string, object>();

   32                 HttpContext.Current.Items.Add("storage", storage);

   33             }

   34 

   35             storage[key] = item;

   36         }

   37 

   38         private static Dictionary<string, object> GetDictionaryFromStorage()

   39         {

   40            return (Dictionary<string, object>)HttpContext.Current.Items["storage"];

   41         }

   42 

   43         #endregion

   44     }

 

There are other issues you need to deal with however, in our case we have Windows Services that need to be able to access our data to run various jobs, etc.  But no HttpContext exists in a WindowsService, so if you read Rick Strahl's blog you will already realize the solution to this is to use ThreadLocalStorage, we took a similar approach and used a Dictionary decorated with the [ThreadStatic] attribute, which was easier and we might be loosing some of the benefits of using ThreadLocalStorage but for now this is working just fine for us.

 

Below is the code that was used to store the DataContext in a non-web application:

 

    9 public class ThreadContextStorage : IContextStorage

   10     {

   11         [ThreadStatic]

   12         private static readonly Dictionary<string, object> _storage = new Dictionary<string, object>();

   13 

   14         public ThreadContextStorage()

   15         {

   16 

   17         }

   18 

   19         #region IContextStorage Members

   20 

   21         public T GetItemContext<T>(string key)

   22         {

   23             return (_storage.ContainsKey(key) ? (T)_storage[key] : default(T));

   24         }

   25 

   26         public void SetItemContext<T>(string key, T item)

   27         {

   28             _storage[key] = item;

   29         }

   30 

   31         #endregion

   32     }

 

So first off, we have two DataContext Lifetime Management strategies above, so we built a DataContextManager that follows the Strategy Design Pattern.  Now I don't like to get hung up on strict design pattern techniques, I always take the concept and adapt it to what works best for my situation, but I do want to point it out as a concept we used.  So we ended up writing something called the DataContextManager, the name is not really important but what it does is so below is the code:

 

   13  public class DataContextManager

   14     {

   15         private readonly IContextStorage _contextStorage;

   16 

   17         public DataContextManager(IContextStorage contextStorage)

   18         {

   19             if (contextStorage == null)

   20             {

   21                 throw new ArgumentNullException("contextStorage");

   22             }

   23 

   24             _contextStorage = contextStorage;

   25         }

   26 

   27         public T GetDataContext<T>() where T : DataContext, new()

   28         {

   29             T dataContext = _contextStorage.GetItemContext<T>(typeof(T).FullName);

   30             if (dataContext == null)

   31             {

   32                 dataContext = new T();

   33                 dataContext.Log = new DebuggerWriter();

   34                 _contextStorage.SetItemContext<T>(typeof(T).FullName, dataContext);

   35             }

   36 

   37             return dataContext;

   38         }

   39 

   40         public void Submit<T>() where T : DataContext

   41         {

   42             T dataContext = _contextStorage.GetItemContext<T>(typeof(T).FullName);

   43 

   44             if (dataContext != null)

   45             {

   46                 dataContext.SubmitChanges();

   47             }

   48         }

   49     }

 

So as you can see it is very simple, you could also add a new GetDataContextManager to pass in a connection string if needed but in our case we figured no one should need this ability since we have all of our connection strings in the configuration file we can just configured those using the LINQ to SQL designer.  If this becomes an issue we may add this ability.

 

The DataContextManager instance is stored in a ServiceLookup class we have that follows the popular design pattern by Martin Fowler called the Registry.  Essentially all it does is stores instances of all the service objects you will be using throughout your application, in our case this is built in a module on the Init so it is built once per AppDomain creation and remains static throughout.  If you remember from the lifecycle process of ASP.NET, first time a user visits the application it loads the AppDomain, when the HttpApplication is created it loads the HttpModules, and HttpHandlers, you can read about this in great detail in one of Rick Strahl's articles.

 

Below is where we define our implementation of the ServiceLookup class:

 

    8 public static class ServiceLocator

    9     {

   10         private static readonly Dictionary<string, object> _map = new Dictionary<string, object>();

   11 

   12         public static void Load<T>(T service)

   13         {

   14             Load(typeof(T).FullName, service);

   15         }

   16 

   17         public static void Load<T>(string key, T service)

   18         {

   19             _map.Add(key, service);

   20         }

   21 

   22         public static T Get<T>()

   23         {

   24             return Get<T>(typeof(T).FullName);

   25         }

   26 

   27         public static T Get<T>(string key)

   28         {

   29             return (T)_map[key];

   30         }

   31     }

 

As discussed above we want all of the objects in our ServiceLocator to be static, and maintain their lifetime throughout the lifetime of the AppDomain, this way we do not have reconstruct them multiple times.  To do this we use a HttpModule as seen below:

 

   16 public class ServiceBuilderModule : IHttpModule

   17     {

   18         public void Init(HttpApplication context)

   19         {

   20             ServiceBuilder.BuildServiceDependencies();

   21         }

   22 

   23         public void Dispose() { }

   24     }

 

The ServiceBuilder is a helper static class that simply does all the work so we can keep all of the code out of the module itself:

 

   12 public static class ServiceBuilder

   13     {

   14         public static void BuildServiceDependencies()

   15         {

   16             DataContextManager dataContextManager = new DataContextManager(new WebContextStorage());

   17             ServiceLocator.Load<DataContextManager>(dataContextManager);

   18             ServiceLocator.Load<CustomerDao>(new CustomerDao(dataContextManager));

   19         }

   20     }

 

We will cover in a later topic how the CustomerDao is used, etc. But for now the DataContextManager is what to really pay attention to since it constructs/retrieves your DataContext.  Next in order to get the DataContext all you have to do is request it from the ServiceLocator for example:

   24 public AdventureWorksLiteDataContext DataContext

   25         {

   26             get

   27             {

   28                 return _dataContextManager.GetDataContext<AdventureWorksLiteDataContext>();

   29             }

   30         }

 

So that is all for Part 1 in this series, next we will cover EntityPersistence and how we solved the problem of maintaining the state of a LINQ Entity across page posts.  If you have any questions do not hesitate to email me or preferably to comment below!

Thursday, April 24, 2008 6:04:08 PM (GMT Standard Time, UTC+00:00)  #    Comments [2]    |   | 
 Wednesday, March 12, 2008

This is nothing new but I created a bookmark for this a while back and was going through my .NET bookmarks (200+ of them) and came across this one.  This is actually pretty cool and I forgot all about it.  It lets you query a live database using LINQ, the implication of course that you are better at writing code than writing SQL queries, and most developers are much better at writing code than SQL queries.  Plus not all SQL is simple, so this will let you write those complex queries in a manner of seconds.

http://www.linqpad.net/

Oh did I forget to mention it has a killer interface?

Wednesday, March 12, 2008 2:20:48 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]    |   | 
 Sunday, February 03, 2008

So I have been exploring DI Frameworks lately (Dependency Injection), and there are a couple of solutions.  While I kind of like the metadata approach vs. the XML Configuration one there really isn't anything available yet.  You have ObjectBuilder, but its only a DI Framework, it doesn't include a DI Container so you are left to build your own container, which includes setting up all of your strategies, context, etc.  The CodePlex guys are apparently working on an ObjectBuilder v2 which they are trying to get vetted by the P&P team at Microsoft.

So the choices are:
Spring.NET
StructureMap
Castle Windsor Container

I have been evaluating these mostly because of a hobby project I am working on called VistaTune, I would like to use a DI Framework and the current changeset that is checked in is using Spring.NET but I am not happy with Spring.NET for a couple of reasons.  First there is no real way to control your dependency injection dynamically, its all configuration based.  Secondly there is no way to inject an instance into your container, for example during unit testing I would like to inject a mock to override the real instance that is mapped in the configuration.  Thirdly there is no DSL (Domain Specific Language), and appears to be no DSL planned for the future release.

Note: After posting this Jeremy D. Miller the developer of StructureMap updated me, the current version of StructureMap v2.0 already has DSL but the next version is being extended with even more.  See the comments section below, also visit his blog here for more information.

For those reasons, I am leaning towards using StuctureMap, which in current release has no DSL but next release will which is already in testing so its pretty much done.  It supports container injection, and it allows you to reset your injection so you can revert back to the original container before injection which is really cool.  It also supports interception, among other things that are out of the scope of my assessment.

So which DI Framework?  It is a difficult question to answer, and I really think it will be interesting to see what comes about from the current top runners at the moment.  I expect to see big things from Microsoft on ObjectBuilder, especially since they just released their PIAB (Policy Injection Application Block) which is their solution to an AOP (Aspect Oriented Programming) Framework.  I would personally rather see PIAB stay isolated by itself, I prefer small isolated Frameworks rather than huge bloated ones that you only want to use for a single thing. 

Sunday, February 03, 2008 8:14:29 AM (GMT Standard Time, UTC+00:00)  #    Comments [1]    |   | 
 Sunday, January 20, 2008

Ok, so the previous post I discussed a service locator implementation based on the Martin Fowler registry example.  After some thought and discussion with a couple of friends I decided the previous implementation was a bit too strict for it's own good.  So I have come with a way that still gives you generic goodness, it does however suffer from boxing/unboxing which may give you a slight performance penalty vs. my previous implementation but the penalty should be minimal if noticeable at all.

The new service locator implementation:

  public interface IService { }
    public class ServiceLocator
    {
        private static ServiceLocator _instance;
        private ServiceLocator() { }

        private static Dictionary<string, object> _map = new Dictionary<string, object>();

        public static ServiceLocator Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ServiceLocator();
                }
                return _instance;
            }
        }

        public void Load<T>(T service) where T: IService
        {
            Load(typeof(T).FullName, service);
        }

        public void Load<T>(string key, T service) where T : IService
        {
            _map.Add(key, service);
        }

        public T Get<T>() where T : IService
        {
            return Get<T>(typeof(T).FullName);
        }

        public T Get<T>(string key) where T : IService
        {
            return (T)_map[key];
        }
    }

To use this the syntax is slightly different than before, this time everything is method based.  I still constrain the methods to the IService type, for some reason  it just gives me a warm and fuzzy feeling when I use the constraint. It is obviously up to you whether or not you want to use it, you could delete the marker interface and the constraints completely and it will work just fine.

To Get: MyService wmiService = ServiceLocator.Instance.Get<MyService>();
To Load: ServiceLocator.Instance.Load<WMIService>(new WMIService());

So both versions work, both versions are acceptable solutions but this one is more flexible than the last version.  In particular this version allows a greater degree of flexibility around unit testing and mocking frameworks.

Sunday, January 20, 2008 7:12:03 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
 Wednesday, January 16, 2008

So I came across the need for a service locator but I didn't want to use a framework since my needs were relatively lightweight, and mostly based around testing.  So looking at Martin Fowlers examples of Service Locators I adopted them and came up with a .NET way of doing it using Generics.  It is of course flexible, the method I am offering obviously has a couple of constraints that I have put in place on purpose for my scenario.  One of them being I wanted only one instance of a service set in the service locator at any given time, so you could very easily adapt it to suit your own needs. 

Also the interface specified is a marker interface used to specify a constraint on the generic, the idea was that all services would be marked with this interface.

 public interface IService { }

    public class ServiceLocator<T> where T : IService
    {
        private static Dictionary<string, T> _map = new Dictionary<string, T>();
        private ServiceLocator() { }

        public static void Load(T service)
        {
           _map.Add(typeof(T).FullName, service);
        }

        public static T Get()
        {
            return _map[typeof(T).FullName];
        }
    }

An example of a service would be like follows:

public class MyService : IService
{
    //Whatever Methods
}
Then on application startup you would obviously load all of your services into the service locator:
MyService myService = new MyService(...);
//...do whatever you need to setup the service

ServiceLocator<MyService>.Load(myService);

So later on anywhere in your code you simply do a

MyService myService = ServiceLocator<MyService>.Get();

It's pretty simple but just in case...As you can see I chose to use the FullName of the type as the key in map, you could always choose to do it the way Martin Fowler did where you simply expose the instance of each service type directly but for me I kind of liked this method.

 

Wednesday, January 16, 2008 5:15:04 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
 Sunday, December 30, 2007

Been working on a new application called VistaTune, it is open on CodePlex so you should go check it out but basically its an application that will enable you to tune Vista as well as setup profiles to use for certain "modes" such as gaming, developing, etc.  In any case during my development I noticed that the ServiceController class of .NET is lacking in that it does not allow you to change the Startup Mode of a service.  Personally I find this kind of odd since it lets you do everything else, so I went ahead and wrote an Extension Method for this class.

The below code is the cleanest and quickest implementation I could come up with, note that editing the registry to change the behavior of a service is considered evil and is very problematic so I would not recommend that route.

        public static void ChangeStartMode(this ServiceController sc, ServiceStartMode mode)
        {
            ManagementPath managementPath = new ManagementPath()
            {
                Server = System.Environment.MachineName,
                NamespacePath = ManagementPath.DefaultPath.NamespacePath,
                RelativePath = String.Format("Win32_Service.Name='{0}'", sc.ServiceName)
            };

            //Method: ChangeStartMode, Parameters: Mode (string), Return Value: int (0 success)
            new ManagementObject(managementPath).InvokeMethod("ChangeStartMode", new object[] { mode.ToString() });
        }

I hope this helps anyone that is having this problem, I did not find very good solutions to this problem when I was searching for it.  Also most of the code samples I found were very dirty, created lots of objects that were not necessary, etc.

Sunday, December 30, 2007 5:15:05 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
 Saturday, July 14, 2007

Was messing with the ListView control in WPF as usual and could not for the life of me figure out how to get the Image source attribute (Image is a separate control type) to show the image of a bitmap that I pulled from an icon from the system.  Basically what I was doing was I was using SHGetFileInfo to retrieve the icon of a particular file, I have two columns in my ListView.  The first column holds a <Image> element the second column holds a <TextBlock> element which displays the path.  I wanted the first column to display the system icon of the second column, so I retrieved this value through the windows API SHGetFileInfo (unmanaged) and got back an Icon which I then convert to a Bitmap.  I wrote a helper utility that does all of this, it also caches the images for common file extensions to prevent excessive system fetching. 

But setting the source in XAML to the property of type Bitmap does nothing, it turns out you have to set the source to the path of the image.  Well my question was, how do you specify the path of an image that you have in memory?  Also then how do you specify the path to XAML?  Well it turns out you can write something called a Converter that will convert the value of anything you want before the binding actually takes place.  Using the following XAML syntax to setup the binding, there are two steps, first you setup the local resource, second you specify the converter to use.

Resource:

   1:  <Window.Resources>
   2:      <custom:ImageConverter x:Key="imageConverter" />
   3:  </Window.Resources>
 

Binding Syntax:

<Image Source="{Binding Path=Image, Converter={StaticResource imageConverter}}" ... >

Next you must write the converter, since the convert I am using is read only the ConvertBack method does nothing.  There does not appear to be a read-only version of this interface so this is the best I could think of, in any case it works.  There is another interface called IMultiValueConverter, from what I gather it converts an array of objects handed to it.

The convert I wrote that takes a Bitmap and returns the source path:

   1:  [ValueConversion(typeof(Bitmap), typeof(string))]
   2:      public class ImageConverter : IValueConverter
   3:      {
   4:          public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   5:          {
   6:              return Imaging.CreateBitmapSourceFromHBitmap(((Bitmap)value).GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
   7:                  BitmapSizeOptions.FromEmptyOptions());
   8:          }
   9:   
  10:          public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  11:          {
  12:              return null;
  13:          }
 

It returns a BitmapSource which it turns out is one of the types that you can bind to with the Image Source attribute in XAML, so this works.  So first off you do not want to use this for Resource files, you should use the built in WPF support such as setting the path to its package location:

"pack://application:,,/Resources/file.ico"

Which will work as long as you don't set the location of the resource to "Embedded Resource" since that is not supported.  If you need to store vector based graphics you can use the Resource Management support of WPF but if you can't for valid reasons than the above option seems to be your only one.

 

Saturday, July 14, 2007 7:48:59 PM (GMT Standard Time, UTC+00:00)  #    Comments [1]    |   | 
 Saturday, July 07, 2007

In a previous post I mentioned I couldn't figure out how to get a column to stretch the width of the control when it was expanded.  Well I stumbled onto a binding feature that is very very cool, its called RelativeSource and it lets you bind to properties on the control itself using the Self attribute, or the one I care about is child controls.

So in all its glory, the code that I use to set to an arbitrary number, is now set to a number that auto increments when the controls width is changed which you can verify by placing it in a text block.

   1:  Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}, AncestorLevel=1}, Path=ActualWidth}"

So yes it is verbose, and yes at first glance its confusing but it makes sense when you understand what its doing.  It's just going one level down to its container, and then I am getting the ActualWidth of that container.  Why not width?  Well I don't set the width on that control so the width will be null actually, in WPF width does not give you the Width of the control.  Instead it gives you the width that you have set it to if ever, and ActualWidth gives you the current active width of the control.

Today has been a HUGE WPF day for me, I have spent the entire day working with it and its exciting.  I hope to share all my findings with everyone that needs it.  It is very difficult to find information on how to do a lot of the stuff I am posting about, most of it has taken me hours upon hours of trial and error to get it working.

Saturday, July 07, 2007 3:35:14 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    |   | 

In WPF the beloved and well known InvokeRequired method has disappeared from the framework.  Replacing it is the Dispatcher, and it's methods CheckAccess and VerifyAccess pretty much are the replacement for InvokeRequired.

So if you have done any new WPF work you will quickly think, what the hell am I talking about.  Because if you type Dispatcher and wait for intellisense you don't see these methods, well that's because they are explicitly hidden from intellisense.  One can assume they did this intentionally to prevent developers from overusing these methods, since every WPF object will periodically call these methods on their own it's not necessary for you to check manually.  Unless you are developing your own WPF object, at least that's my best guess.

They have actually marked the Dispatcher.CheckAccess and Dispatcher.VerifyAccess with the [EditorBrowsable(EditorBrowsableState.Never)] (thanks Karsten Januszewski)attribute so you can see that they are intentionally hiding this from view.  I hope more light is shed on this topic as it's quit confusing.  Also there is a hack circulating for a way to check if the executing thread needs to be marshalled or not by doing a comparison against the UI thread.  To me that code really makes me feel dirty just by looking at it.

So how do you use the Dispatcher?  Well there are numerous different ways, I prefer to use an anonymous delegate:

   1:   Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate
   2:  {
   3:    //Update UI 
   4:  });

You don't have to use the ThreadStart delegate, the reason I use it is simply because it takes no parameters.  You can also obviously point it at a method, or itself which if you do that you will need to use CheckAccess in that instance.  There is a very valid performance reasons controls don't check to see if they are on the correct thread every single time.  If you do it the second way you incur that overhead, so out of curiosity I ran a benchmark comparing the two styles.

In the first benchmark I used the method above, and got the following results (in milliseconds):

1st Run

2nd Run

3rd Run

4th Run

5th Run

6th Run

Average

10368ms

9483ms

9750ms

9531ms

9559ms

9511ms

9700ms

10644ms

9873ms 9845ms 10009ms 9830ms 9876ms 10012ms
 
I find it interesting, the additional check using CheckAccess incurred about 300ms of additional processing time in a loop execution of 100,000 iterations. Using the below algorithm for keeping the CPU busy, remember this was a UI test so I needed an event to fire on he UI side from a separate thread and get marshalled to the UI thread.  None of that code changed between the benchmarks, the ONLY code I changed was the UI thread, and how it handled the marshalling.
 
 
 
The difference seems negligible and not worth really any effort to avoid, however if you are working with millions, or billions of records that require the UI to updated for each item (why?) then you might want to take this optimization into account.  Unlikely as the situation really is it's interesting... 


Algorithm used for benchmark (simulates a real world data event, think of the DataGrid):

   1:  ArrayList al = new ArrayList();
   2:  for (int i = 0; i < 100000; i++)
   3:  {
   4:    al.Add("Test");
   5:    if (NewItem != null)
   6:      NewItem(this, EventArgs.Empty);
   7:  }

Is this a 100% solid benchmark? Probably not, in fact someone else might be able to get differing results but it does show a difference which is really quit obvious.  You are calling an additional method so you would expect it to take slightly longer but it also illustrates why they don't call this on the WPF object for every single method call natively.

Saturday, July 07, 2007 1:07:53 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    |   | 
 Sunday, June 24, 2007
Been messing with WPF, usually when a new language comes out to get familiar with it I write a simple test applicaiton.  Normally this is a replica of Notepad, I usually write an exact replica of Notepad with every single feature duplicated.  This tends to get me quit familiar with the new technology, from there I can move on to more interesting things.  Well with WPF this has taken me far longer than any language I have done this in thusfar, it has so many unique things in it, that are completely foreign to me and most developers.

So one thing I noticed that was quit unusual was how the RichTextBox worked, it is much much more powerful to a point where it's nearly unbelievable to the point it can be extended, I expect to see alot of new programs with a very unique text support interface coming out with this thing.  But more to the point, loading a text file into a RichTextBox in WPF is less than straight forward.

Below is how you do it:

using (Stream stream = fileDialog.OpenFile())
{
    TextRange tr = new TextRange(rtMain.Document.ContentStart, rtMain.Document.ContentEnd);
    tr.Load(stream, DataFormats.Text);
}

Now my first impressions were what the hell?  How does it work?  So on further investigation it's quit unique, the ContentStart, and ContendEnd properties are actually something called TextPointer and are indeed references and not integer values as one would expect from previous versions.  While this is not apparent it is much more elegant and gives you much more flexability at adding text in any spot you wish without changing the caret position, etc.

So basically TextRange holds these two pointers, and when you load the file from a stream it takes the contents of the stream and dumps that in between those two pointers.  So there you go, now it makes sense!

Sunday, June 24, 2007 2:44:10 AM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
 Monday, May 21, 2007
A typical problem that is encountered using multiple threads and events is that when you fire your event, the subscriber to that event will be running from the thread that initiated the event.  The typical way of getting around this is to check InvokeRequired in the windows form and then use Invoke of that form to Invoke the event.  Wouldn't it be nice if you could marshall that event to the proper thread before the UI gets the event?  I mean you wouldn't have to deal with it, it would just work.

So you may wonder why didn't the .NET team just build this into WinForms?  Well I wondered that to, but I watched a Channel 9 video (can't remember which one) where basically they said they didn't do this because it would put a huge performance burden if every single event had to be thread safe.  So in order to achieve optimal performance it was up the developer to only make a form/component/etc thread safe only when it needed to be thread safe.  This way performance is optimal.

With that said you can use the below code snippets that a co-worker of mine pulled from the Microsoft CAB Framework, you can use it to marshal an event to the control where the synchronization context is located.  All WinForms have a SynchronizationContext, which is used by the FireMarshalledEvent method to marshal the event to the forms thread context.

Below is a very simplified example of how this would work, I would suggest you modify it to your needs before using it:

void FireMarshalledEvent(SynchronizationContext syncContext, Delegate eventDelegate, EventArgs eventArgs)
{
    if (eventDelegate != null)
    {
        if (syncContext != null)
        {
            syncContext.Send(
                delegate(object data)
                {
                    try
                    {
                        ((Delegate)data).DynamicInvoke(this, eventArgs);
                    }
                    catch (TargetInvocationException exp)
                    {
                        //Log Error
                    }
                    }, eventDelegate);
                }
        else
        {
            eventDelegate.DynamicInvoke(this, eventArgs);
        }
    }
}

public event EventHandler<EventArgs> MyEvent;

FireMarshalledEvent(SynchronizationContext.Current, MyEvent, new EventArgs());


Monday, May 21, 2007 2:20:17 PM (GMT Standard Time, UTC+00:00)  #    Comments [0]    | 
 Tuesday, May 08, 2007
So a couple of weeks ago I ran into a situation on a project I was working on where all projects in the solution were signed, we received a third party assembly from a vendor that was not.  We asked them to sign it but it was going to take nearly 2 weeks before we received that delivery.  In order for us to move forward I needed to have this assembly signed, but how do you sign an assembly without access to the source code?

Well a coworker of mine came up with a rather ingenious solution, and I am posting here so the knowledge can be shared.  I googled for a solution and found none so hopefully this will help people with this same situation.

So here are the commands:

ildasm /tokens /out=unsignedAssembly.il unsignedAssembly.dll
ilasm /dll /key=key.snk unsignedAssembly.il /out=signedAssembly.dll

As you can see whats happening here is you use the dissassembler to generate the MSIL code into the unsignedAssembly.il file, at which point you essentially have the code, or a form of it.  Next you use the assembler to reassemble the msil code into the binary assembly but this time you sign it using your key!

Its brilliant, it works great and I did not notice any drawbacks to doing it this way.

Tuesday, May 08, 2007 1:56:39 PM (GMT Standard Time, UTC+00:00)  #    Comments [2]    | 
 Wednesday, May 02, 200