Tuesday, June 20, 2017

How to initialize instances asyncronously

Here is another problem I've been thinking about quite a while, before found a solution I like.
async/await keywords revolutionized the writing of asynchronous code in C#. It is as simple as marking a method with async keyword and using await in it to wait for asynchronous operations to complete in non-blocking manner.This gets trickier with async initialization methods. Think about a class, instances of which need to be initialized once only, before those can be used. In a non-async scenario one example would be to call the initialization method from the constructor, as follows:

public class SomeDirectory
{
  private Object state;

  public SomeDirectory()
  {
    this.Initialize();
  }

  // This method expects the state to be initialized before execution
  public void DoSomething()
  {
    // some logic
  }

  private void Initialize()
  {
    this.state = // state retrieval logic
  }
}

This gets complicated, when the initialization method becomes asynchronous. As constructors are non-async methods, the following transformation can lead to a situation, where instances of the SomeDirectory class aren't yet initialized after constructor, which can lead to some unexpected side-effects later, when the DoSomething method is called. The below sample code emphasizes the situation:


public class SomeDirectory
{
  private Object state;

  public SomeDirectory()
  {
    this.InitializeAsync();
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
   // some logic
  }

  private async Task InitializeAsync()
  {
    this.state = // state retrieval logic
  }
}

A simple solution to this would be to force the constructor to wait for the initialization to complete:


  public SomeDirectory()
  {
    this.InitializeAsync().GetAwaiter().GetResult();
  }


This, however, is not a good technique, as it will introduce delay in the caller thread, which can harm in many situations (like in server code, where the actual DoSomethingAsync api is not being called immediately).

The third approach is calling initialization on every public API. Of course with a simple "run-only-once" optimization in it. Something like this:


public class SomeDirectory
{
  private readonly Object stateLock = new Object();
  private Object state;

  public SomeDirectory()
  {
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
    await this.InitializeAsync();

   // some logic
  }
}

The problem with this approach is that it will slow down the very first call to DoSomethingAsync() method. Sometimes - it's something you don't want to have.
So here comes the final approach, which I'm using nowdays:


public class SomeDirectory
{
  private Object state;
  private readonly Task initializationTask;

  public SomeDirectory()
  {
    this.initializationTask = this.InitializeAsync();
  }

  // This method expects the state to be initialized before execution
  public async Task DoSomethingAsync()
  {
    await this.initializationTask;

   // some logic
  }

  private async Task InitializeAsync()
  {
    this.state = // state retrieval logic
  }
}

This approach will allow the execution of the initialization start as soon as the object is constructed. Yet, it won't loose the track of its execution.

Hope this will help some of you.

Friday, July 22, 2016

Unknown disposables: Disposing of non-disposable interface instances

In coding, it's a good practice to use factory methods (or some other creational design pattern) to abstract away creation of class instances. In most of the cases, the "creator" would return not the actual type being created, but the abstraction - the interface.
To emphasize the problem, let's consider the below example:

For simplicity, let's assume that we're dealing with a factory method, and the interface the factory method returns is called "IContract". Note, that IContract does not implement IDisposable. There are two different implementations of IContract - Impl and DisposableImpl. So here comes the interesting part, the DisposableImpl implementation does implement IDisposable.

So now, if one uses the factory method "Create()" to instantiate IContract, it may get a disposable instance back, and won't ever even know about it:

public class ContractFactory
{
    public IContract Create()
    {
        return new DisposableImpl();
    }
}

Obviously, the responsibility of disposing of the disposable instance is on the caller. A lot of people won't even notice the problem and just use the IContract and never worry about freeing up resources as early as possible. Yes, GC will eventually take care of the unnecessary resources, but that'll happen later than the actual variable becomes unnecessary - during finalization.

So one pattern a client can use is the following:

{
    IContract contract = null;
    try {
        contract = new ContractFactory().Create();
    // all the usage of the contract instance happens here
    }
    finally
    {
        IDisposable disposableContract = contract as IDisposable;
        if (disposableContract != null)
        {
            disposableContract.Dispose();
        }
    }
}


This will ensure safety in case of both disposable and non-disposable implementations.
Another way to go, would be to have a wrapper class, encapsulating the disposal logic and being a disposable itself, as follows:

public sealed class DisposableInterface<T> : IDisposable where T : class
{
    private readonly T interfaceInstance;

    public T Instance
    {
        get { return this.interfaceInstance; }
    }

    public DisposableInterface(T instance)
    {
        if (instance == null)
        {
            throw new ArgumentNullException("instance");
        }
       
        this.interfaceInstance = instance;
    }

    // A better implementation would be the usage of the Dispose pattern here.
    // Not doing that here to keep the sample simple.
    public void Dispose()
    {
        IDisposable disposableInstance = this.Instance as IDisposable;
        if (disposableInstance != null)
        {
            disposableInstance.Dispose();
        }
    }
}

Now, the caller could use the IContract as follows:
{
    using (DisposableInterface<IContract> contract = new DisposableInterface<IContract>(new ContractFactory().Create()))
    {
        IContract instance = contract.Instance;
        // all the interaction now happens with the "instance" reference
    }
}

As you can see, the second example is cleaner and nicer.
Now, as you're familiar with the problem, doesn't it raise a natural question: "should this become a pattern and be used all over the place with factory methods, as one can't know whether the actual implementation the factory methods returns will be disposable or not?"....
Think about this and leave any comments you may have.

Wednesday, June 17, 2015

"RunAs /NetOnly" functionality from C# code

Only recently I've learnt about the "/netonly" flag availability for "runas" command. I was really happy to find it, but the issue came later.
It turns out that the runas.exe command can't be automated, as it accepts passwords only through a prompt. So there is no way to pass in credentials without the prompt.

That made me seek for a custom solution for the problem. What it turned out is that the .Net Process API doesn't expose any functionality to control the process creation the way, which "/netonly" flag would results in.

Long story short, I came up with the following solution:
The CreateProcessWithLogonW Win32 API, which is being called internally by runas.exe, has a number of parameters indicating how exactly the process should be created. One of these parameters is "dwLogonFlags". The set of values it can take has one called "LOGON_NETCREDENTIALS_ONLY". From MSDN documentation for that value: "Log on, but use the specified credentials on the network only. The new process uses the same token as the caller, but the system creates a new logon session within LSA, and the process uses the specified credentials as the default credentials.". This is exactly what I need. After few hours of unsuccessful search for a C# code sample, which would create a process with this flag, I ended up creating my own.
The sample code is available for download at: http://1drv.ms/1LeqKnD

Hope you find this useful !

Thursday, April 9, 2015

The Compatibility Pattern: Designing adaptive classes

Any non-deprecated system, soon or late, faces challenges. Some of these challenges are quite common. The two following items represent just a fraction of those:
  • existing file storage doesn't satisfy current/coming space requirements
  • the data model need to be modified/extended to comply with new requirements

Today I’m going to describe a design pattern, which can be applied in a variety of situations (including the two above) and eliminate the pain of code re-write.

So, for the sake of simplicity let’s concentrate on a single scenario. Let’s assume we have an existing system – which is operational. Let’s also assume that “EntityA” is an entity in the data model of the system, and the records of that entity are processed by some business logic: “LogicA”.  So far the system used to operate just fine. Now – new requirements come in – which introduce changes to “EntityA” and the “LogicA” as well. Specifically, new “EntityA” records should be treated differently than the “old/current” records. For the sake of simplicity, let’s limit the changes in “EntityA” by just one new field “Field2”. So here what “EntityA” will look like:

image

where “Field1” is an existing field on the entity. Note, that I intentionally don’t mention the types here as its irrelevant in this context.

Also, let’s assume that “LogicA” is already encapsulated in a class with the same name, as follows:

image

Now, back to the new requirements, which affect “LogicA”. The simplest way to handle the change would be to modify the “LogicA.ProcessData” method. However that won’t be maintainable. Think about any future changes – affecting the same logic. After several such changes it’ll be really a mess and it won’t be easy to figure out how to change something  to impact only specific version of entities. So the simplest and design-wise proper solution would be to introduce new LogicA_New handler for the new entities and put the decision logic of instantiating the proper logic in some factory class. The following diagram depicts that case:

image

Note, that the abstraction of the handling logic into separate classes is an implementation of the Strategy design pattern.

This model allows future expansion of the system by just defining a new strategy/logic and updating the factory method, to return the proper handler type. Handling logic deprecation is quite straight forward as well, and can be handled in the reverse order: the factory method is updated to remove the obsolete case and the appropriate logic handler is removed.

Hope this will save you some time in the future.

Wednesday, April 1, 2015

The interview process

Looking back - there were many times I’ve went through an interview process for different software development positions in different companies. To be more precise – there were around 20 interviews I’ve went through. Frankly saying, it doesn’t matter what kind of company you’re interviewing for – 60% of the technical questions will be very similar (of course, there are rare exceptions to this rule). And if you’ve gone through at least 5 interview processes, you probably know what to look for - how to prepare for those questions.

Why ? Because most of those questions you’ll be asked will be just formality and well known mathematical problems. It’s just a matter of filling in a checkbox whether you’ve answered a question or not – and the chances you’d be ever dealing with that kind of problem during your day to day work – are almost 0! To answer these kind of questions you’d need to just have walked over any similar problem in the past. Most of those share very similar solutions.

These 60% are the bad part of the interview process and I call – THE INTERVIEW TAX. Because you have to learn those anyway even if you won’t be dealing with anything close to those questions.

Now, let’s talk about the other 40%. Those divide into three categories:

  • Thinking questions
  • Practice questions
  • Design questions

1. Thinking questions

These may easily be unsolvable mathematical problems as well. And the interviewer is asking you the question and also ask to think loudly. This is important as what he/she wants to observe – is how you think. Or – do you think at all. I know it’s funny, but I’ve seen people just having no ideas on how to solve a problem.

On the other hand, the problem can be really simple as well – very trivial – but the discussion around it will be like building a knowledge graph: you say something, you get another question on what you said, you answer again, and again get a new question – which slowly takes you away from the original topic. These discussions can take hours (luckily the interviewer will have a schedule).

2. Practice questions

The questions here are simple coding questions in your preferred programming language (unless the company has strict requirements about the coding language). In most of the cases – even a pseudo-code will be fine. These questions are aimed to verify your coding skills – like properly handling validation, corner cases. In the end you most probably will be given also a task to write unit-tests for your code. The interviewer may have noticed a mistake in the code, and sometimes want you to catch it – so be careful to do so. If you’ll write a code and the tests you’ll write won’t handle it – that’ll be reflected negatively for you.

3. Design questions

This is my preferred topic. Unfortunately these are quite rare questions during the interview process you get asked. I believe those are the most valuable ones as those will be giving answers on how well you’ll be doing your work – if you’ll be hired.

Anyway – here you may be given some real-world problems – and you’d have to solve it – by describing a system from a high level. The system can be very small or very big – depending on the responsibilities you’re being considered for. But even on the smallest systems (a simple example is an elevator or an alarm clock) some important skills can be seen.

I hope this writing will be a good overview for one who is looking forward for an interview and also for those who host interviews – to improve their existing processes, if they fall in the 60% category.

Saturday, January 10, 2015

C# 6.0: The great changes

It's now more than 10 years I'm writing code in C# and I enjoy every part of it. It gets better with every version, and there is no exception in the coming version: C# 6.0.
Everybody who had ever dealt with MVVM pattern, will be well familiar with the INotifyPropertyChange interface. The tedious part of the implementation were the constants (I used to have constants always) you had to define per each publicly exposed property - to store the name of the property.
I recently had a post about how to retrieve the property names dynamically using reflection (here), but still it's not everyone would consider a good option to go with. C# 6.0 mitigates this pain with a new keyword called "nameof".
To get the name of a property you'd simply write: nameof(PropName), and this would return "PropName". Really cool !

And now the other thing I am happy about. Remember the String.Format("Name: {0}", record.Name)  way of doing things ? There were many issues I've seen where updating the format one forgets to add additional parameter, or adds one, but forgets to add the '{X}' placeholder for it - which would cause a runtime exception. C# 6.0 changes the mechanism completely - as now instead of the placeholders you'll just refer to the values within the format string. That's much more readable and safe:
String.Format("Name: \{record.Name}")

And there is much more...

Tuesday, December 23, 2014

WCF: Identifing late exceptions in the pipeline

Hi.
Recently I’ve run into  a strange WCF service issue. The logs in the service method were indicating a successful completion of the call, but the call was still failing and the clients were getting exceptions.
 The exception message was: “An error occurred while receiving the HTTP response to <serviceEndpoint>. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down).“.
The service API which was called had a return type (not void), and the type was serializable. So the only explanation I could come up with was that something wrong goes with serialization. THAT WAS IT!
Luckily it’s possible to simulate the same serialization what WCF does behind the scene, and verify the assumptions. So I did it: created a test method within the unit-test project, called the API being called by the client to get properly built result object, and then tried to serialize it:
[TestMethod]
public void GetDataUsingDataContract_SerializesResults()
{  Service1 serviceInstance = new Service1();
  CompositeType argument = new CompositeType();
  CompositeType result = serviceInstance.GetDataUsingDataContract(argument);

  using (MemoryStream stream = new MemoryStream())
  {
 
   DataContractSerializer serializer = new DataContractSerializer(typeof(CompositeType));
    serializer.WriteObject(stream, result);
  }
}
Note: you’ll need to add a reference to System.Runtime.Serialization.dll.
In my case the “serializer.WriteObject(stream, result);” call threw with the detailed exception.
 
You can download the full sample project: http://1drv.ms/1sJljCd
 
Hope this helps.

Saturday, September 6, 2014

Windows Phone 8: The Map control

Recently I've been hitting an issue with integrating the Map control from the Windows Phone Toolkit into the UI. The problem was related to centering map to the desired location. I was using MVVM pattern for the app, so I had a proper public property in the data context, which I was trying to set as a binding source for the Center property of the Map control.

As I was just interested in centering map based on the property value, and not vice-versa, I've had explicitly specified the Mode property for the binding to be "One Way". And that was the problem.
It turns out, that for the Center property to work properly, you have to have the binding mode set to "Two Way".

So the final property and the XAML should be similar to the following to work:

The following property is the one defined in the data context:
public GeoCoordinate MapCenterLocation
{
 
get
  {
   
return this.mapCenterLocation;
  }
 
set
  {
 
   if (value != this.mapCenterLocation)
    {
 
     this.NotifyPropertyChanging(MapCenterLocationPropertyName);
      this.mapCenterLocation = value;
      this.NotifyPropertyChanged(MapCenterLocationPropertyName);
    }
  }
}


and the appropriate XAML for the map control should be:
<maps:Map x:Name="map"
  HorizontalAlignment="Stretch"
  VerticalAlignment="Stretch"
   Center="{Binding Path=MapCenterLocation, Mode=TwoWay}" />

As mentioned above - the "Mode=TwoWay" is critical for the Center property binding to work. Otherwise, the map will never be centered like the binding is not there.
Interestingly, you don't even get an error/warning for that.

Thursday, April 10, 2014

Dynamic Reflection in C#

Hi,

More and more I started to feel the need for dynamic reflection - reflection working not based on subject names (properties, methods, fields ,...) but delegates.
So got time to submit and idea on Microsoft Connect about it. The following sample shows what the idea is about:
internal class Sample
{
 public int PropA { get; set; }
 public void SomeMethod()
 {
  PropertyInfo info = GetPropertyInfo(() => this.PropA);
  // Some other code, using the "info" variable
 }

 public static PropertyInfo GetPropertyInfo(Func<object> property)
 {
  // This is the method I'm asking about.
 }
}
If you like it, please go and vote for it at: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/5755035-ability-to-get-propertyinfo-dynamically-passing-th


Update:
It turns out what I've asked in this post is possible using Expression trees. The following is the working example on how to achieve it:
    public static class PropertyExtensions
    {
        public static PropertyInfo GetPropertyInfo<TSource, TProperty>(this TSource instance, Expression<Func<TSource, TProperty>> propExtractor)
        {
            MemberExpression mexp = propExtractor.Body as MemberExpression;
            if (mexp == null)
            {
                throw new ArgumentException("Invalid");
            }
            PropertyInfo result = mexp.Member as PropertyInfo;
            if (result == null)
            {
                throw new ArgumentException("Invalid expression");
            }
            return result;
        }
    } 

Tuesday, March 11, 2014

Breaking the debugger session like an exception was thrown

Today I cam across a situation, which made me think about an new feature in Visual Studio Debugger.
But first about the scenario: I've been debugging a component test, and wanted to stop the debugger. But the same time - I couldn't do that, as that won't take the execution through the normal cleanup flow, defined in a finally block.
Then I thought about the feature I've started with, and here is the link to it: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/5624050-stopping-debug-session-to-go-through-the-defined

So please read it and vote for it !

Thursday, February 20, 2014

How I've fixed the periodic crashing IE problem

Hi there,

Today I've finally managed to fix the crashing IE problem, under Windows 8.1. So decided to share my experience, hoping for some of you out there - this post will be in help.
But first, let me give you a bit of history.

Frankly saying, I'm a Microsoft fan. Yes, I do work in Microsoft as a software developer.
So you guessed already, that I do use Windows - I love it ! I have had a chance to play with other OS-s as well, so please - no comments about "you haven't seen others".
So, my machine was running Windows 7 for a while already. And one day - Microsoft announces the availability of Windows 8 Preview. Of course - I do install it (on a VM for now). I guess it took some time for me to get used to it, and eventually, I liked it as well. Then - the release, and, as expected, I'm upgrading my main OS to it immediately.
Let me tell you the truth - that was the best OS upgrade experience I've ever went through. No issues, no hassles - and everything works: everything except the most used product - the Internet Explorer, which keeps crashing periodically - about 50 times a day.
Well, I now realize, that my laziness was keeping me away from trying to look into the actual problem, and fix it. So I was just tolerating that, and using it again and again. By the way, the non-desktop version of IE was ok, no crashes, no issues. And I started using that one more and more.
And finally, the final crash made me so angry, that I've forgot about my laziness, and decided to dig deeper.
First thing was to open the Windows Event Log (Windows Logs \ Application), and look for most recent errors: luckily the only errors were from IE (those I've been hitting). And the error message was very similar to:

Faulting application name: IEXPLORE.EXE, version: 11.0.9600.16518, time stamp: 0x52f347b2
Faulting module name: <module name>, version: <module version>, time stamp: 0x513d9755
Exception code: 0xc0000005
Fault offset: 0x00046ce7
Faulting process id: 0x4280
Faulting application start time: 0x01cf2df55b897962
Faulting application path: C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE
Faulting module path: <the path to the failing module>
Report Id: 9aa55680-99e8-11e3-bf29-c48508058295
Faulting package full name:
Faulting package-relative application ID:


Looking to the "Faulting module path" I guess will give you a clear picture - of what is really failing. In my case that was a file download application. I've then just uninstalled that application, and it's already 4 hours (I would have about 15 crashes already) - no issues.
Hopefully you'll be able to handle this now.

Sorry for non development related post.

Regards,
Artak

Thursday, October 17, 2013

Unit Testing DateTime.Now or DateTime.UtcNow

TDD is a great methodology, and if you follow it properly and get fanatic about it, then you eventually look for time to refactor all your code to be properly designed - hence - testable.
Eventually, you'll come up to a code where you've used DateTime.Now or DateTime.UtcNow properties, and start to think, should you really need to test this minor bit? The answer will be "Absolutely YES". But then, does it worth it to refactor the code for this simple thing?
If you're lazy enough and would be happy to solve the problem with some minor risk, then the following technique will be for you.
Let's say you want to test the following code - the Save() method:

internal class SampleState
{
    public DateTime LastSaved {get; set;}

    public void Save()
    {
          this.LastSaved = DateTime.UtcNow;
    }
}

The proper way would be to mock out the date/time provider and refer to it in the code. Alternatively this simple technique will be helpful:

[TestMethod]
public void Save_SetsLastSavedTime()
{
    // Setup
    SampleState sut = new SampleState();
    DateTime beforeCall = DateTime.UtcNow;

    // Act
    sut.Save();

    DateTime afterCall = DateTime.UtcNow;

    // Validate
    Assert.IsTrue(sut.LastSaved >= beforeCall && sut.LastSaved <= afterCall);   
}

The technique insures, that the time saved is within the test interval between the call started and ended. As mentioned before - this is not an explicit verification, but still - it gives high confidence that the proper time is being set.

Hope this will be useful !

Wednesday, October 10, 2012

The Dispose() method and the inheritance

Today I am going to write about the IDisposable interface – it’s Dispose() method, and how this should be really implemented in derived classes. The simplest implementation of Dispose() method will be just introduction of the following code to the class, and that’s all:
public class A : IDisposable
{    public void Dispose()
    {        // Disposal logic here 
    }
}
 
and this seems to be fine, but it is not.

Let’s assume for now that everything is fine, and we ship a library with the above code in it. Somebody, who is using the library, can easily use it in the following way:
public class B : A
{    public new void Dispose()
    {        //Class B specific dispose logic in here
        //And the following call is essential here

        base.Dispose();
    }
}

This seems to be fine as well, unless someone else, or even the owner of class B will use it in the following way:
using (A item = new B())
{    // some logic here
}

In this case, when exiting from the using block, the Dispose() method of type A will be called, which is sitting in the method table in memory as a separate record, and has nothing related to the Dispose() method of type B. And this will become a possible reason for a memory leak – any unmanaged resources introduced in class B will not be cleaned up !

One solution, of course will be to cast item to type B and call it’s Dispose() method explicitly, but that’s just complicating things, because this will need to be done in a finally block.

So let’s now see what I meant saying “it is not” in the beginning of the article, when was defining class A.

The thing is the the implementer of a public type must take the responsibility of problems like the one described by implementing types the way, so the users will not need to worry about the usage.

And the solution is actually simple – in every case, when introducing a type which implements the IDisposable interface, the Dispose() method must be marked either virtual (and the derived classes should override that method), or whole the class must be marked as sealed.

So by defining class A as sealed we will explicitly restrict its usage the way it was described – the incorrect usage. Now let’s see what will change, if we’ll mark the Dispose() method in class A as virtual and in class B override it.

Remember, this will force a single method record for a derived type to appear in the method table, so no matter how you’ll reference an instance of type B (either through type A, or any other type in the hierarchy) the Dispose method will call the Dispose method of type B, which, assumable (if implemented correct – as in the example above) will call the parent type’s Dispose() method and this will go by chain until the top of the hierarchy, making sure that any resource in whole the hierarchy got disposed.

Good luck with development !

Thursday, August 2, 2012

Synchronization: Working with synchronized resources

Today I'm going to write again about the synchronization, but will mainly concentrate on the way of helping to avoid some code duplication, and will save some time.

In one of my previous posts I've described several ways of synchronizing access to the resource, and what we’ve pointed out there as a general (of course with exceptions) practice each synchronized resource in needs to have an associated object, used for synchronizing access to that resource only, and for nothing else.

Thinking about that I came up with the following class definition which I found very handy:

public class ConcurrentResource<T>
{ 
  private readonly Object syncRoot = new Object(); 
  public readonly T Resource; 
  
  public ConcurrentResource(T argResource) 
  {
    if (argResource == null) 
    { 
      throw new ArgumentNullException("argResource"); 
    }
    
    this.Resource = argResource; 
  }
}



The ConcurrentResource type will encapsulate the object which to the access is going to be synchronized, and will also define internally a read-only property called syncRoot, which will be used for synchronizing the access.

Using that type I found it really handy but let me describe a bit more the use of it and what methods we can add to it to make it handier to work with.

So let's imagine we want to do some action with locking that resource. The following method will be really handy here, because it will encapsulate the locking mechanism in it as you can see:

public void HandleActionInSyncronizedContext(Action argAction)
{
  if(argAction == null)
  {
    throw new ArgumentNullException("argAction");
  }
 
  lock(this.syncRoot)
  {
    argAction();
  }
}



So the method internally will handle the locking mechanism and the caller will not need to use it directly in the code. One advantage of the abstraction, is that it will be very handy when we will need to switch from lock{…} to Monitor.Enter(…) call with timeout in one place, and get it working everywhere. There are bunch of interesting methods we can add to that type, and here are few of those:

public void WaitForPulse()
{
  Monitor.Wait(this.Resource);
}
 
public void Pulse()
{
  this.HandleActionInSyncronizedContext(()=>
  {
    Monitor.PulseAll(this.Resource);
  });
}
 



As a complete example of usage of the ConcurrentResource( of T) type you can take a look to the sources of ConsoleHoster project in here.

Sunday, July 22, 2012

Delegates and Events

Today I’d like to write about the events, but because I cannot talk about events without delegates, I’ll cover those as well in this post.
To make the article easier to understand (for new developers at least) let me describe a more real-world example so we’ll be able to model things from it. One such example can be the fire brigades' work – how they react to fires, how they being notified about fires and so on.
So thinking about it I assume that every fire brigade works for some kind of center, which control’s its work. And every such center has several brigades under its control. So let’s model that center as FireAlarmingCenter class described below:
public class FireAlarmingCenter
{
}

As we said earlier the FireAlarmingCenter will be one who notifies about fire alerts to the fire brigades. Before we will be able to add that notification capability to the FireAlarmingCenter class, we need to define what the notification will look like. and here where the delegates come in. To specify the details about the specifics of the notification we need to describe those through a delegate, which will define a signature of a method it can reference to, or a method, which can be used as a handler for an event of that delegate type.

public delegate void FireAlarmEventHandler(FireAlarmingCenter argCenter, AlarmDetails argDetails);

Now let’s add the event definition to the FireAlarmingCenter type as follows:

public event FireAlarmEventHandler FireAlarm;

Great, now we have the FireAlarmingCenter type, so let's see how this event is going to be consumed.
As we have said already, the consumers of FireAlarm event will be the fire brigades, which we can model like this:

public class FireBrigade
{
    public FireBrigade(FireAlarmingCenter argCenter)
    {
        if (argCenter == null)
            throw new ArgumentNullException("argCenter");

        this.Center = argCenter;
    }

    public FireAlarmingCenter Center
    {
        get;
        private set;
    }
} 

Now we’ve created the base plumbing so the FireBrigade will have the reference to the FireAlarmingCenter it’s “working for”. But there is still a hole there – the FIreBrigade doesn’t somehow “listen” to the FireAlarm event of its center. To do so, we just need to aappend the following line to the FireBrigade class constructor:

this.Center.FireAlarm += new FireAlarmEventHandler(this.HandleFireAlarm);

Although the C# 4.0 language let’s the developers to skip the delegate type after += operation, when registering for events and specify only the method name, which is going to work as handler for that event, I like that style, so its really visible from code what type exactly the event is, so to the handler method signature is. So that line will assume that we’ve defined the “HandleFireAlarm” method already in the FireBrigade class, which will contain logic about what to do in case of a fire.
Now let's see how the FireAlarmingCenter will notify the FireBrigade-s about a fire. I’m not going to write or guess what the conditions are on when to notify it, but am really going to concentrate on how it will be fired. The most simple way to do that is as follows:
  
private void OnFireAlarm(AlarmDetails argDetails)
{
    if (this.FireAlarm != null)
    {
        this.FireAlarm(this, argDetails);
    }
}

Very nice and simple, it’s really not what we want. So let’s go and see what is happening behind those lines ?
So the first line in the method checks whether there are any listeners registered for the FireAlarm event or not. Next, if there are listeners to the FireAlarm event, the most important thing is going to happen – the event is going to be called. To answer the question – “what means an event is called?”, I’ll need to go back a bit to describe what the delegate is.
So the delegate is a reference of a method, but not only – it is actually a list of references to methods, which all are matching the signature of the delegate. Actually, the definition of the delegate we’ve created is being translated by the compiler to a class definition with the name of that delegate and deriving from an abstract class called “MulticastDelegate”:
 
public class FireAlarmEventHandler : MulticastDelegate
{
}

So now we can approach to an event as a field of a specified delegate type in a class it’s defined in. So when in the FireBrigade class’s constructor the += operation on the FireAlarm event is being called, it actually adds a new method reference (which is specified on the right from the += operator) to the delegate invocation list.
Now, when the event (in this case the FireAlarm) is being called, the following happens:An iterator is being created which iterates over all the registered methods to that delegate instance, and each element of that iterator (in this case a method reference) the method is being called with parameters passed in to the event call. But this seems to contain a problem.Imagine a situation when during the event listeneres execution (iterating over the list of handler methods) a new FireBrigade will be constructed for that FireAlarmingCenter – the invocation list will be modified so an exception will be thrown here.But don’t worry – there is a very handy way of handling this and I really like it. If we’ll modify the code like this:

private void OnFireAlarm(AlarmDetails argDetails)
{
    FireAlarmEventHandler tmpEvent = this.FireAlarm;
    if (tmpEvent != null)
    {
        tmpEvent(this, argDetails);
    }
}

on the first line in the method the invokation list of the delegate will be copied and the next operations will be working on the copied list including the invocation itself) so adding or removing any new handlers to the FireAlarm event won’t affect the invocation any more. This technique is usually referenced as “Event Invoke Pattern”.
Visual Studio has a very nice snippet for this: “invoke”. Just type invoke in VS.Net and hit Tab twice (Tab+Tab) and you’ll get the code automatically appear in your source.

So I think that’s all for this post. Good luck with your development.

Sunday, July 15, 2012

The ConsoleHoster app

Hi.

The recent 4-5 months I was working on a very interesting project which will most probably be a help for other developers. Feeling quite good about it I finally decided to make it open source.
So here is the link where it's published: http://consolehoster.codeplex.com/
Hope you'll like it, and please leave your feedback there and join me in developing it, if you're intersted.
In my future posts I'll try to cover it in more details.

Regards,
Artak

Sunday, July 8, 2012

Regex: Identifying paths

Hi again and thank you for visiting my blog.

It's already three months I'm working on a project which again, as many other projects I'm working/worked on, started from just an idea.
So one of the challenges I met in this project was to come up with a regular expression, which will identify whether the given part of the string is a path, part of it, or relative one.
Remember (or if you don't know try) the TAB support in windows command window - you can type in a relative or full path, then type some prefix and on each sequentiall hit of TAB button, the file/folder names, which are in the specified path and start with the typed prefix, will be placed like auto-completition feature one after another.
So I finally came up with the following regular expressoin:
"((((^\w:|\s\w:)|\.\.?)(\/|\\))?(([\w.]+( [\w.]+)?)(\/|\\))*)|((((^\w:|\s\w:)|\.\.?)(\/|\\))?(([\w.]+([\w.]+)?)(\/|\\))*))([\w\.]*)\t"
Because it's quite complex, the processing was really taking long. First I tried to compile that regular expression into a separate assembly and then use the compiled one, but unfortunately it affected the performance harder, than earlier. Eventually I understood that I don't need all the groups defined in the pattern, so I removed those (marked those not to be counted as groups using (?:...)), and it increased the performance really good. So here what I ended up with:

"(?:(?:(?:(^\w:|\s\w:)|\.\.?)(?:\/|\\))?(?:(?:[\w.]+(?: [\w.]+)?)(?:\/|\\))*)|(?:(?:(?:(^\w:|\s\w:)|\.\.?)(?:\/|\\))?(?:(?:[\w.]+(?:[\w.]+)?)(?:\/|\\))*))([\w\.]*)\t"Althought the compiled query execution time need to be shorter than the non compiled one, I haven't went into details why it was like that, but the fact is fact - that's true. I'm pretty sure that for shorter regular expressions that will work faster, but no in this case.

Hope the regex will be helpful.

Enjoy .Net Development !!!

Monday, April 9, 2012

Syncronization: deadlocks and how to identify those

These days synchronization become very actual problem for any developer - nowdays its really hard to even imagine a single threaded application. Of course with this, some headache arises with deadlocks. Usually developers use lock(...) { } statement to synchronize access to some code block, and that is one possible reason of a deadlock. Don't get me wrong - I don't say that if you use lock statement, then you have a deadlock, but what I say, is that if you have a deadlock - then its definitely happening on one of the lock statements you've used in your code. So what to do to avoid those ? Or actually, which will be more correct to say, how to identify the lock statement where the thread blocks causing a deadlock forever ?
Fortunately, as almost always, there is a very handy option under the hand - The Monitor class. You probably know, that the lock (obj){...} statements translates to the following code:
try
{
    Monitor.Enter(obj);
    // ...
}
finally
{
    Montior.Exit(obj);
}
To make this code "deadlock-proof", you need to replace the Monitor.Enter method call as follows:
try
{
    if(!Monitor.TryEnter(obj, TimeSpan.FromSeconds(2))
    {
        // Log deadlock reason in here
        throw new Exception("Unable to take exclusive lock on the given object");
    }
    // ...
}
finally
{
    Montior.Exit(obj);
}

Here we are passing a TimeStamp parameter to the TryEnter method, specifying the amount of time to wait for the lock. So if during the specified time period it is impossible to take lock over the specified object, then the method will return false, and we'll be able to log something, which will tell us the place in code where the actual deadlock is happening. Of course it's not so convenient to use whole this construct in code, so this can be extracted to an extension method like the following:

public static void SyncronizeCallByLocking(this Action argAction, object argLock)
{
  // Argument validation in here
  if (!Monitor.TryEnter(argLock, TimeSpan.FromSeconds(2000)))
  {
    // Log exception in here, if required
    throw new ApplicationException("Unable to lock the object");
  }
 
  try
  {
    argAction();
  }
  finally
  {
    Monitor.Exit(argLock);
  }
}

After this it's really easy to wrap the code block, which needs to be synchronized like this:
new Action(()=>
  {
    // Code which needs to be syncronized
  }).SyncronizeCallByLocking(objectToLock);

By using this technique you will definitely not waste many hours of struggling by trying to find the deadlock reasons in your application, and guessing where those can arise from. Of course, if you want after fixing all the issues you're free to convert back to using the lock statement instead of what was described, but I won't bother about it, because you don't know what changes may come later, and how those may affect your application.
Good luck with your development.