Sunday, January 29, 2012

AppDomains - Why and How ?

Finally I've found time for this post, which I was planning last year already.
So, where you may need an AppDomain in your application, how you'll treat it and what are the benefits of using it? I'll try to answer to those question. Read further.
Let's start from the theory: An Application Domain represents an isolated environment in a managed .net application process. Saying roughly those are sub-process layers, where the code will execute. The important features of Applicaiton Domains I'd like to mention here are the following:
1. An applicaiton domain has its own - isolated from others, memory
2. Those can be loaded and unloaded dynamically. Unloading an applicaiton domain will unload all the assemblies loaded in that applicaiton domain (there are still some cases when this is not true, although non-practical cases).
Now let's try to find a usage. Imagine a scenario, where the applicaiton needs to load a component from non-trusted source. There are several issues with this, and the most important for me are Security and Reliability.
Security: you never know what the code in that component is doing behind the scenes.
Reliability: the component can be non-well designed, leaving holes for exceptions to arise.
Let's first concentrate on the case, if we are going to handle such scenario without application domains. Of course for interaction with that third-party component there will be a well-defined interface, and every call of a method of that interface (actually an instnace of 3-rd party component, which I will call Component X further) will be wrapped in a try-catch block. But what if the component does something else behind the scenes ? For example it can has a background thread which does some other processing. In this case, your handlers won't be able to handle exceptions coming from that background processed code, because those are not on the stack of a thread you've just called a method in. So what will happen ? I won't go into details here, but will say that an exception coming out from such backgroun thread (which is not properly caught in Component X, will finally take your process down, and you'll have no chance to react, cause have no handlers at all.
Don't blame me here, cause I'm not going into some special cases here, like WinForms, where you can handle all the exceptions on the Application level by registering to ThreadException event.
On the reliability side - you don't know what the code is doing from data-accessing perspective. So there are limited choices for you to react here - limit your own application permissions to not allow the Component X to do something wrong. But still, you will share the same address space in memory with that component.
Ok, now let's jump to the usage of application domains for this scenario, and see how those will solve the above mentioned problems.
First, in FCL (Framework Class Library) there is a type called AppDomain, which is handling management and interaction with application domains. So let me from now on call application domains just AppDomain for the sake of simplicity only.
Well, the proper design for the above scenario will be the following:
1. Create an AppDomain

AppDomain tmpDomain = AppDomain.CreateDomain("ComponentX Domain");

2. Register for the UnhandledException event of that AppDomain

tmpDomain.UnhandledException += new UnhandledExceptionEventHandler(OnComponentDomain_UnhandledException);

3. Add proper permissions to that AppDomain (this is called sandboxing - limiting permissions)
// Leaving code for this section, because this is out of scope from this article
4. Load the Component X assembly into that AppDomain

Assembly tmpComponentAssembly = tmpDomain.Load(AssemblyName.GetAssemblyName("./ComponentX.dll"));

5. Create Component X instance in that AppDomain.
6. Create a proxy in our AppDomain to interact with Component X instance in the new-created domain(because the memory of each AppDomain is isolated, the process of passing data between AppDomain-s involves serialization and deserialization of that data, and whole the process is refered as Marshalling).

Type tmpComponentType = GetComponentTypeFromAssembly(tmpComponentAssembly, typeof(IComponentContract).Name);
IComponentContract tmpComponentProxy = tmpDomain.CreateInstanceAndUnwrap(tmpComponentAssembly.FullName, tmpComponentType.FullName) as IComponentContract;

7. After finishing working with Component X unload AppDomain of Component X to free up memory. This will also unload the assembly loaded in that AppDomain.

// This call is missing in the example solution attached to this article.
tmpDomain.Unload();

Great, this solves the security problem and what about the reliability? The AppDomain type (in Net Framework 4.0) defines an event called UnhandledException. Unfortunately there is no way to handle that exception and continue the normal flow of the application, but the good thing here is that you get your "last-chance" to save state, or log the exception, and even schedule a task in OS to start a new instance of your application. There are several important aspects you should be aware of regarding this event: "This event can be handled in any Applicaiton Domain, although its not necessarily raised in the application domain, where the exception occured. An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated.
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains."
The quoted part I've taken from MSDN documentation cause it very well explains that event propogation. I still recommend you to read the MSDN page.
In the section above I've specified the exact version of Net Framework because in the earlier versions the behavior was slightly different. Here is another section from MSDN for earlier versions: "In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug."
I've also created a small solution with code representing the scenario described in this article. Click here to download the example codes.

Friday, January 27, 2012

Comparing IPAddress-es

Recently I was struggling with a LINQ expression, where I had a comparison of two ip addresses. Like used to - the comparison was done by the == operator, which was the cause of the headache.
NEVER USE == WITH IPAddress.
Seems IPAddress have no its own overrie for ==, and because it's a reference type that operator is just comparing two addresses(whether those point to the same location in memory or not). And I was getting false for equal ip address comparison.
You can just try to do the following:

bool areEqual = IPAddress.Parse("150.148.1.54") == IPAddress.Parse("150.148.1.54");
// the areEqual now is false

So the proper way to compare them is to use the Equals method, which IPAddress type has an override for:

bool areEqual = IPAddress.Parse("150.148.1.54").Equals(IPAddress.Parse("150.148.1.54"));
// and now the areEqual will be true


Good luck with your coding.

Monday, November 21, 2011

ASP.Net: Application Pools, Application Domains and/or processes

Hi all.

Today I just wanted to bring some light on the way ASP.Net handles requests. So let's start from scratch.

What is ASP.Net itself from OS perspective ?
ASP.Net is just a process called aspnet_wp.exe. How in that case it's stable against application crashes - read further.

In the last question we've mentioned something called Application.What is that ? Ok, Application is an atomic unit of the ASP.Net process - it's the type of the objects, which are responsible for processing client requests. But there is a good and important trick here, which ASP.Net process takes care of - the Application Domains. In fact, for each application (which is represented by a vritual directory in IIS) ASP.Net creates a separate AppDomain, and everything related to specific application happens in the boundaries of that domain. This makes one Application be resistant against others' crashes.
So for each request coming from the client, ASP.Net "creates" (I will cover this a bit later) a separate Application type instance (Application object) to handle that request. Why I've quoted the creates word, is because that's not the case and there is a nice optimization done under the hood: as soon as the application being started (AppDomain for that application being created), ASP.Net creates a pool of up to 100 instances of Application classes to not spend time on heavy object-creation operation on each request. So, finally, what we get, is that for each request a "random" existing Application instance processes that request.
This brings us to one important point: Never keep state in Application instance, or even if you need to take into account the fact that the instnace you've written some state to most probably will be chosen to process request from other clients as well.
All this is great, but seems we're missing something: where do the Application Pools stand in whole this architecture ? Ok, time to change your understanding about Application Pools, because those are just number of settings, which can be applied to different applications. Applicaiton Pools are just a conveniet way to group important settings alltogether and then be able to apply them to any application you'd like to.

I think this is all for this post.
Good luck in your development.

Wednesday, November 2, 2011

Better Work Environment: Bigger Screens


It's almost 5 years I used to work on two monitors, and now sometimes feel the need of the third one. Yes, it's very handy to work on several, but there is a drawback as well: you get used to it and its getting harder and harder to work on a single one at home.
Today, I had to spent some time on my WP7 game (which is in the Marketplace from february), and suddenly thought about moving from 22" Samsung (monitor) to 32" Samsung (TV). And you know what - that's amazing - clear picture, wide area to work and you can see every long line of your code (I'm not fan of splitting lines by enters).

Tuesday, November 1, 2011

Silverlight: Control visibility based on several properties' values

Hi there.

During last few months I've noticed that many people are struggling with problems like object visibility based on parameters.
And here I will try to make this more easy for some of them.
So, let's begin. First of all let me make a not about the IValueConverter interface, introduced in silverlight framework. That's really a very usefull contract, especially when you get used to converters. You now ask about converters ? Sure: A converter is there to help you to convert a value to match the expected result and vice-versa. That's a mechanism, which adopts the input to output, assuming that the output is fully depending on input.
So, how does it work ? Let's assume we have the following XAML:


    <TextBlock Text="Dummy text" Visibility="{Binding Path=DummyTextVisibility}" />

Most of the developers will go this way - trying to match the properties to the UI expectations. But this is NOT CORRECT ! Just think - You're trying to bend your logic to match the View ? Everywhere, in every study about UI development you read that separation is something everyone is trying to achieve (I mean presentation and logic separation). And here you try to adopt the logic based on presentation.
So which is correct ? The correct way to handle this is to not think about the presentation layer at all, when you're developing the business layer. And as soon as you think this way, you see, that it would be much natural to have something like this:

    <TextBlock Text="Dummy text" Visibility="{Binding Path=IsDummyTextVisible}" />


But wait... will this work ? Sure not, cause the Visibility property expecting something of type System.Windows.Visibility, and you've just passed in a bool.
Here the Converter comes in: it lets you to bind to anything logical, and then get what you want to get from it, so it will let us write the following, assuming that we have defined BoolToVisibilityConverter:

  <cnv:BoolToVisibilityConverter x:Key="boolToVisibility" />
   ...
   <TextBlock Text="Dummy text" Visibility="{Binding Path=IsDummyTextVisible,Converter={StaticResource boolToVisibility}}" />

We assume here also that the xmlns:cnv was imported in the root tag, and that the <cnb:BoolToVisibilityConverer ... was defined in the resources section.
And here is the code for the BoolToVisibilityConverter:

public class BoolToVisibilityConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            return (bool)value ? Visibility.Visible : Visibility.Collapsed;
        }
        catch (Exception ex)
        {
            return Visibility.Collapsed;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        /// some logic here if you're going to use this
    }
}

Great. Now we have everything in place except the thing, that in some cases you will need to make an object visible depending on two parameters - control is going to be visible if both those parameters are visible. Don't waste your time looking for some complex solutions, just wrap your control in a Panel control, and bind its visibility to the other parameter you'd like to:

<Grid Visibility="{Binding Path=SecondParameter, Converter={StaticResource boolToVisibility}}">
    <TextBlock Text="Dummy text" Visibility="{Binding Path=IsDummyTextVisible,Converter={StaticResource boolToVisibility}}" />
<Grid>

So, that's it. Enjoy :)

Thursday, October 20, 2011

Improving .Net Framework

I was thinking a lot of times about a way of forcing types to have some common constructor. Of course this can be achieved by abstract classes - but the derieved classes can hide it. So the way I was hoping it to be is through the interfaces - to be able to specify a signature of a contructor, the implementing types should have.
Am so happy that Microsoft has Connect :) So my idea is already there - go and vote for it here

Let's see what will they decide.

Tuesday, October 18, 2011

Remote Assistance within MVVM based applications

Even we - IT professionals, require a lot of web assistance during our daily life. One of the cases I was facing several days ago was a problem during the payment for an item in Amazon. As usual, the user calls to the support, describes the situation, gets a lot of clarifying questions, and being asked for about three times to repeat, just to ensure that he hasn't missed something.
This is a problem - a big problem both for the customer, who is facing a problem and the support guy, who is just unable to vividly see the situation happening on the customer machine. And the thing the Support man can dreams of in those cases - is a remote connection.
Of course in 99.9% of cases such a luxary will be impossible, and the reason is only the firewalls, the client - who doesn't even know what the remote desktop connection is, ... .
But all we are living in an eWorld - and most of the things we do are related to the internet - onlin shopping, emails, some new account registration, blogging, ... . So I thought that there must be a better way of support, and there is. Of course, it won't fit the requirements of all the users, but it can cover most of the cases. And in this blogpost I will try to bring the idea I do have which can change the way of support.
So let's imagine that the application, which we're adding the support for is designed using MVVM pattern. What does this mean ? This means, that whole the logic of the application is being handled by the ViewModel class instance (in simple case there can be only one class in ViewModel layer). And based on any change on that class the UI is being changed accordingly. So what if someone, who is using the same application, will be able to simulate the same changes in the same order on a ViewModel layer obects on his machine, as the user on his machine ? This will mean, that the UI on both machines will have the same state after every single change, which, in its place, means that both users will have the same view. All this is true, until there is some User-Specific logic in the appilcation, which can change the way the Application behaves depending the logged in user. Let's for now leave this open point for later discussion (in this post of course), and assume that there is a solution for this as well, and both users can log in by the same user.
So, if we will come up with some service, which transmitts any change from one application instance to another we will have a simple screen sharing between those two users. To acomplish this we need a centralized way of transfering the changes in one ViewModel to another.
Remember that a ViewModel class in Silverlight, implements the INotifyPropertyChanged interface, which in its place defines the PropertyChanged event. And any change which can cause the UI to update, being tranfered to the UI throught firing this event. So what we can do is by simply registering to the ViewModel class instance's PropertyChanged event, and pass any change of any property to a service (I will not go into the code, but will just concentrate on the logic here. Please write your comments to the post, and I will try to respond shortly). Transfering to the service all this data is no enough, because there must be some unique token, which by the data should be identified. And this token should be shared with the other party (The support guy in our case), so he will be able to attach his UI to that token as a listener on the service, so any change coming to the service should be transfered to the Support Application Instance (SAI later: the application instance which the support guy has onpened on his machine for remote assistance). This will now bring any UI change to the SAI.
So in this case we got something which is very like a screen sharing application - but the actual sharing. Of course this is a lot already, and the Support guy will know now how the user goes from one point from another in the UI, but let's not stop on this, and continue developing the idea.
Based on all this we can achieve the same from the other side, and bring any change that is being done on the SAI, to the Customer Application. This will mean already, that the application is being remotely controlled.
And that's all. Of course I haven't spent time describing minor things like the user must first allow the Support guy to remotely see his changes, and how he is going to get that unique token, ... and a lot more, but I tryed to explain whole the working solution I do see, which I hope, can bring a big change to the online application support.

All the best to all of you, and enjoy :)