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)
            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}}" />

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 :)

Tuesday, October 4, 2011

Dialogs in MVVM (Silverlight)

Several days ago I was facing a problem, when was trying to open/show a dialog from in my MVVM application.
The actual problem is that I want that dialog also to be bound to a ViewModel instance - controlling it.
There are many approaches to handle this. I will present one of them - which I am satisfied with.
So, let's start. What I want is to have a DialogViewModel instance in my main ViewModel object, which is the DataContext of the current page, and which from from I'm going to open the dialog.
When thinking of MVVM itself you think that is much be something like setting a property and a dialog must show up - THAT IS CORRECT ! And that is what I'm going to achieve.
So just to give a small example of code, how the structure should be:

public class PageViewModel
    private DialogViewModel dialogVM = new DialogViewModel();

    public DialogViewModel DialogVM
            return this.dialogVM;

public class DialogViewModel : INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private bool show = false;

    private void NotifyPropertyChange(string argPropertyName)
        PropertyChangedEventHandler tmpEH = this.PropertyChanged;
        if(tmpEH != null)
            tmpEH(this, new PropertyChangeEventArgs(argPropertyName));

    // Here comes a lot of logic like dialog commands, ... which I will not include in this article

    public bool Show
            if(value !=
       = value;

This is quiete enough for the ViewModel layer. So this is really what I've described enough. You will now ask - how should this boolean change (althought it supposed to be such thing) affect the dialog to appear - keep reading.
The simple approach (which won't work with ChildWindow derieved dialogs) is to add a dialog definition into the XAML and bind its Visibility property to the DialogVM.Show property, using a BoolToVisibilityConverter (am sure you'll be able to write something like this yourself). But when you'll try to do this, the dialog will behabe strange - it will really be not what you wanted - and you'll notice a lot of issues with it. Maybe in further versions of Silverlight this way of showing dialogs also will be possible - but not yet.
So, the second approach, I'll keep with, is to create a helper class, derieved from Control class. This will be the actual bridge between the DialogVM and the dialog we're going to show.
Here what the helper control will look like:

public class DialogHelper : Control

But an empty class is not going to be any helpfull for us. And here the core of the solution is: we're going to add a DependencyProperty to this control - to enable it to be bound to anything, bind it with the DialogVM.Show property and finally handle the change of that dependency property.

public class DialogHelper : Control
    private static readonly DependencyProperty ShowProperty = DependencyProperty.Register("Show", typeof(bool), typeof(DialogHelper), new PropertyMetadata(false, new PropertyChangedCallback(OnShowChanged)));

    private static void OnShowChanged(DependencyObject argSender, DependencyPropertyChangedEventArgs argEA)
        ConfirmationDialogHelper tmpSender = argSender as ConfirmationDialogHelper;
            DialogToShow tmpDialog = new DialogToShow();
            //The following line makes sure that the dialog also will work based on MVVM
            tmpDialog.DataContext = (this.DataContext as PageViewModel).DialogVM;

So, finally, here is the way you should handle it in MVVM - ENJOY !!!

Please sorry for any code typos, cause I was typing it right into the blog editor - with no IntelliSence support.

Thursday, July 28, 2011

Silverlight - WCF: NotFound Exception

Hi all.

Today I'll try to cover a problem, which many Silverlight developers are facing, trying to make WCF service calls. So the problem is that there are a lot of cases, when the client will get "NotFound" error, and here are the possible reasons for that.
(Make a note, that I will assume that the service is actually running, and you're calling to correct endpoint).
1. The amount of data being transfered is more than the limits - the service and clients are configured for. Remember, even if you haven't manually configured those values, there are some defaults. So this can be a cause for such an exception. Here is a good link as a start point for this case.
2. When a method returs something, which contains, or itself is an Enum type, and you've overriden the default values of that enum, by giving different values to its members, and there is no value with 0, then you'll have the same. This is because during serialization, if you won't assign any value to those members, which are type of the Enum, they will get default value (they are value type), which is 0 for Enums, and the Serializer will try to serialize the 0 to any of the marked values, which don't contain 0, so you'll end up by a Serialization Exception on service side, which won't be handled on client and will come back as a NotFound error.

Good luck with your development.

Thursday, July 7, 2011

Memory Leaks in Silverlight Toolkit

Hi all.
In this post I'll try to share my previous experience about memory leaks I've faced in one of projects I've working on.
The problem was in DateTimPicker control of the Silverlight Toolkit, and also in Accordion. Seems those were not being garbage collected and causing all the stuff related to them even with event handlers to stay there in memory.
So here are few simple tips to follow to avoid such things: Always be sure that you've unregistered any event handlers from the above mentioned controls, because those will make the objects, which in those handlers defined to also stay in memory.
If the controls are defined in a XAML file, just remember to remove it from its parent container. All this is easily handled by a simple interface implemented on a control level (you can call it IReleasable for example), and just call the Release method (defined in this interface) from the Page's unload point. And in this method do this "detach" from the leaking control. Why the unload is not a proper place- because for a control it may fire many times - as the Load event.

Good luck with Silverlight development.

Friday, March 18, 2011

Silverlight: MEF and other approaches

Hi all.

Today I'd like to concentrate to the discussion about the MEF: a relatively new framework for dynamically loading Silverlight content.
It was amazing from the first point of view, and we have decided to use it. The process started.
Of course it's easy: use some simple attributes, mark the exportable types you want in your .xap packages with those attributes and that's it - you'll have them whenever you'll need them, and everything will be ok.
Yes, all this is right, BUT ...
There is a big BUT about this MEF: when you application will come a bit bigger - and it will come to this stage, because you are already using MEF, so that was your intention to avoid loading such a big application, you'll find out that instead of downloading each library/assembly only once from the server, you'll download it as many times, as you have it in each downloadable .XAP.
This became a big problem, when my app with all those xaps grown to ~14Mb. What to do?
Of course there is always a better way to go. And here one, which I have implemented and is satisfied with:
The .Net Framework is such a good thing :) I have created a simple attribute, which was aimed to mark the assembly references for the assembly it's applied to. And the second part, is that I've created a small asynchronous Assembly Loader, which is using this information from the described attribute, and downloads all those dependencies, when you ask it to download an assembly. If this assembly is already downloaded, you'll just get that instance, otherwise it will download it, it's references, and when everything is ready to be used, it fires this amzaing "AssemblyLoaded" event, which to I was able to react. So finally, avoiding this dll duplication (another .dll hell) I've reduced the size of the app from 13.6Mb to 3.8Mb. And one more thing - it works excellent and much faster.

Monday, February 28, 2011

Context menu in Silverlight

Hi all.

Few months ago I was trying to find a standard way to implement a context menu, but could find no solution which I liked. So finally decided to write something from scratch.
I will not go down into the details here, just will give the idea here.
So first of all I thought, that the menu can contain several kind of items:
1. Items, which are system(application) wide, and you will have them in your entire application, anywhere you'd click. The "About" menu item appears under this case.
2. Items, which are based on the control type, which on the user clicks the right mouse button: these can be buttons, textboxes, anything derieved from Control. Into this point I have added the Cut, Copy, Paste items for textboxes.
3. Items, bound to exact controls - concrete instances. In this case, only when you click on the specified instances, the items should appear there in the menu.

The implementation is quite simple, so I will not include any code here. But if you'll need just write me, and I will be happy to help.

So, this is all.

Sunday, February 13, 2011

The interview I failed

It was in march 2008- in early march. I was in an interview process for Microsoft Ireland. Also, the same time, I was looking for a local job in Yerevan for the case I fail. But seems I wasn't ready for a failure. Anyway - the last stage of the interview to Microsoft passed. I was now expecting the results. The day after was the day I had to complete the task I've been given as part of the interview process for a position in CQG (Yerevan). I was not ablt to work on the task as good. So the next day - and the last tet-a-tet interview started.
Question from the interviewer:
-What is a thread?
-(I was silent. Had nothing in my mind to tell them. Was absolutely empty minded and was just trying to say something but ... I was not able to.)
-What is a process ?
-(Again the same)
-How would you make the program you've sent, to run better for multicore processors?

Started reviewing the code I sent them:
-Why you wrote this part in this way?
-I really don't know, cause it is much better to write it in [telling which exactly] way.
-Strange, you know the correct answer, but you have written in not the best way here.

Here was the influence of the Microsoft on me. I was expecting the results... and was packing all my things to relocate.

This was my only interview in Armenia, which I failed. And that was so silly.

This is all I'd like to share in this post. And the lesson learnt was: always, when going to an interview, leave aside any kind of excitement - concentrate, and win.

Friday, February 11, 2011

Windows Phone 7 development

Hi all.

Few months ago Microsoft has announced about its new mobile platform: Windows Phone 7. And here the pursuit started. Thousands of developers started looking into it to develop something new.
The same way I did. Decided to start from scratch a month ago - to develop a simple Tetris game. First I've investigated the market - there were several such games, but all had very small playground, which was not user friendly (by me). So the core of my idea was to make the playground as much, as the phone screen is.
Microsoft did really good job by creating a lot of restrictions for the apps, which you are going to expose on the marketplace. There is a big doc of guideance you have to follow.
After few days of development, when I had the game skeleton ready, I've started investigating the way to publish it. First I had to register withing the AppHub( this costs 99$). After the registration (which is not available for any country) I had to wait two weeks to be validated. One of those validation points being handled by GeoTrust (a partner company responsible for registrant validation), and this was the longest part to wait for.
Registration is done, and the only step left is to wait until Microsoft verifies your application. This stage took them only a day. And finally, my app is on the marketplace. This is the start, and it was really easy. So I will continue my app development for WP7 - for a great mobile platform.