Branislav Abadjimarinov's technical blog

Branislav Abadjimarinov's technical blog

  1. Design Patterns course at FMI, Sofia University for the summer semester 2012

    The Design Patterns course will be part of the summer semester's curriculum of FMI, Sofia University. I'm glad that I'm part of the team of this course for the second time. This year we will have an entry test with various computer science questions.

    We have a tough schedule ahead of us. The course will consist of 15 lectures. Along with the classic Gang Of Four Patterns we've added some new topics and interactive lectures.

    This is the full list of lectures:
     

    • OOP design & Singleton
    • Factory Method, Abstract Factory & Builder
    • Prototype & Flyweight
    • Adapter & Bridge
    • Composite & Decorator
    • Proxy & Facade
    • Code-patterns, anti-patterns and real world frameworks (.net, jdk) pattern examples
    • Lecture where we write project in front of the students.
    • MVC & MVP
    • Command & Mediator
    • Iterator, Strategy & Template Method
    • Observer & Visitor
    • State & Memento
    • Interpreter & Chain of Responsibility


    Along with the course I'm also part of a project to create a Design Patterns book in Bulgarian.

    Posted by Branislav Abadjimarinov on January 20 at 10:10 AM

  2. ActionScript 3 Number data type problem with long integer values

    Lately I've been doing some front-end flex programming and in a series of posts starting with this one I'll share my view of the Adobe's programming framework. First I'll start with ActionScript 3 - the programming language used in flex. It is an EcmaScript derived language. From what I've seen for a month or so programming there are two basic rules in the ActionScript world:

    1. The owls are not what they seem and
    2. There are a lot of owls

    Maybe it is a good choice in flash with its simple syntax and agility but when it comes to enterprise programming I've found that it fails too often to accomplish simple tasks. As a .net refugee I expect at least the basic language features to be working predictably.
    Consider a case in which you need a really big integer number to be passed to the UI of your flex application. Let's say that it is bigger than 32bits. There is a special data type Number in ActionScript to preserve 64bit values and it seems to do it well ... except when your integer number is bigger than 16 digits. In that case god knows what happens to your number.

        var reallyBigNumber:Number = Number(2885118563511697402);
    
        trace(reallyBigNumber); // traced value is 2885118563511697400
    
        var asString:String = reallyBigNumber.toPrecision(21);
    
        trace(asString); // traced value is 2885118563511697408.00
    


    Not only your number is "rounded" to a different value but when you call toPrecission function (which is expected to give you more precise representation of the number) you get a whole new third value. To bring even more confusion the Flash builder's watch shows that reallyBigNumber's value is 2885118563511697408 which is not what trace prints to the console. All the provided numbers are far from the max value of the Number data type. Go figure.
    Maybe the Number data type is perfect for flash animations where you have two trees and five owls flying around but when you build an enterprise framework you got to have strong foundations.

    [Edit 9/2/2011]

    For an year or so about 2 or 3 of my work collegues also hit the same issue in several different areas. Also, as Art commented on my previous post, this is not a bug but rather a tech limitation of actionscript 3 and hence flex limitation also.
    In a nutshell the actionscript Number data type is implemented by the IEEE-754 standard. The IEEE-754 is a standard for doble precission floating point numbers. So the equivalent of actionscript 3 Number  type is java and .net's double. This is the reason for loosing precission when transfering java long values to actionscript Number.
     

    Posted by Branislav Abadjimarinov on June 23 at 4:22 PM

  3. WeakReference and .net memory management

    WeakReference class is relatively unknown to the .net community. A weak reference in general is a reference to an object that doesn't stop the garbage collector from collecting an object. In its nature it is an agile reference to object - it can be useful to keep large objects in memory only if the application can afford it. If the application is pressed for memory it can collect the object which is weakly referenced.

    The WeakReference class is drop dead simple to use. When you want to crate a weak reference to an object you just create a WeakReference and pass the object as a constructor parameter like this:

    WeakReference weakRef = new WeakReference(referencedObjectInstance);

    You can use the IsAlive Boolean property to check if an object is collected. And you can get the object instance using the Target property. It is good practice to use those two in combination to check first if the object is still available and than access it.

    Another use of the WeakReference class is to check if objects are collected as expected. Let's say I have a simple Student class:

        public class Student
        {
            public string Name { get; set; }
        }

    And I want to create an array of students. The array will not be garbage collected if an object from it is still alive. In the case where only one object form an array is alive it will prevent all the others array objects from being garbage collected. Creating the WeakReference will allow us to track if the objects are really collected.

        class Program
        {
            static void Main()
            {
                Student[] firstGrade = new Student[2];
                
                firstGrade[0] = new Student { Name = "Usefull Bob"};
                firstGrade[1] = new Student { Name = "Average Joe"};

                WeakReference weakRef = new WeakReference(firstGrade[1]);

                GC.Collect();

                Console.WriteLine(weakRef.IsAlive ? "Alive!" : "Dead");

                // Uncomment to prevent all objects in the array from garbadge collection
                // Console.WriteLine(firstGrade[0].Name);
            }
        }

    There is also some differences if our application is running in Debug or Release mode. When the application is in Debug mode the garbage collector behavior is pretty much unpredictable as some objects are kept alive intentionally to support better debugging experience. If you want to get a real picture of the memory management in your app you have to do your profiling in Release mode. WeakReference class can also be used in Unit tests to verify if an object is garbage collected as expected.
     

    Posted by Branislav Abadjimarinov on May 20 at 1:50 AM

  4. I'm officially a Microsoft Certified Trainer

    I haven't posted for a while and as you can gues I've been busy with all kinds of tasks. As the title states, now I'm officially a Microsoft Certified Trainer (MCT). Today I received my confirmation email. Joining the MCT program has been in my list of goals for a long time and I'm glad that I finally accomplished it. Now with the official release Visual Studio 2010 and .net framework 4.0 I'm sure there will be a lot new things to learn. Related to these events I plan to change the structure of this blog and add more detailed posts and tutorials.

    Posted by Branislav Abadjimarinov on April 30 at 2:15 AM

  5. AJAX the easy way in ASP.NET Web Forms using genric handlers

    In this article we'll see a quick and elegant ajax call solution based on generic handlers in asp.net and jQuery. The goal is to populate a street list in a dropdown with ajax call based on a selected postal code in a dropdown. The usual way to do this in ASP.NET Web Forms will be to use the AjaxToolkit, MS Ajax library and web service. The problem with this approach is that it is coplex and prone to errors.
    To accomplish the task we will create a generic handler(.ashx file) in our asp.net project. The generic handler is a lightweight approach to deliver content to the user. It doesn't have the heavy page lifecycle. By default the generic handler has only one method - ProcessRequest and one readonly property - IsReusable. The handler inherits directly from IHttpHandler. The IsReusable property defines if one handler object can be pooled and shared on different requests. If you set it to true be sure that the ProcessRequest method is thread safe. Than we will implement the ProcessRequest methods as follows:

    using System;
    using System.Web;
    using System.Collections.Generic;
    using System.Runtime.Serialization.Json;

    public class GetStreetsByPostCode : IHttpHandler
    {
      public void ProcessRequest(HttpContext context)
      {
        List<string> streets = new List<string>();
        int postCode;
        string postCodeParameter = context.Request.QueryString["code"];
       
        if (!String.IsNullOrEmpty(postCodeParameter) &&
            int.TryParse(postCodeParameter, out postCode))
        {
          AddressService service = new AddressService();
          streets = service.GetAvailableStreetsByPostCode(postCode);
        }
       
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<string>));
        serializer.WriteObject(context.Response.OutputStream, streets);

        context.Response.ContentType = "application/json";
      }

      public bool IsReusable
      {
        get
        {
          return false;
        }
      }
    }

    As you see we are using DataContractJsonSerializer object to serialize data in JSON format. The JSON format is native data representation format for the JavaScript language. Also we set the content type http header to "application/json" which is the JSON document mime type. The AddressService is just a class used to get data. This is all we need from server side. For client side we will use jQuery library. Based on a selected post code we will populate a dropdown with available streets for this post code. The script bellow will make an ajax request to our generic handler, parse the JSON data and fill in the dropdown values.

    $(function() {
      $("#DropDownPost").change(function() {
        LoadAddress();
      });
    });
    function LoadAddress() {
      var selectedPostCode = $("#DropDownPostCode option:selected").text();
      if (selectedPostCode && selectedPostCode != "0") {
        $.post("/GetStreetsByPostCode.ashx?code=" + selectedPostCode,
             function(result) {
                 var streets = eval("(" + result + ")");
                 ClearStreetsDropDown();
                 PopulateStreetsDropDown(streets);});
      } else {
        ClearStreetsDropDown();
      }
    }
    function ClearStreetsDropDown() {
      $('#DropDownStreet option').each(function(i, option) { $(option).remove(); });
    }
    function PopulateStreetsDropDown(streets) {
        $('#DropDownStreet').append(
            $('<option selected="selected"></option>').val("").html("")
          );
        $.each(streets, function(val, text) {
          $('#DropDownStreet').append(
            $('<option></option>').val(text).html(text)
          );
        });
    }

    Posted by Branislav Abadjimarinov on March 26 at 12:15 AM

  6. Web Applications Development with .NET Framework and ASP.NET course in Technical University of Sofia

    From Monday, 15 February a new course on programming is starting in the Technical University of Sofia. The course is titled "Web Applications Development with .NET Framework and ASP.NET" and it will cover some of the basics of Microsoft .net platform and ASP.NET. The training provided will be very brief and it will require a lot of dedication by the people attending.  I'm taking part with a couple of lectures on ASP.NET and AJAX. The course is free and is supported by Telerik Academy. You can check the course official web site for more information.

    Posted by Branislav Abadjimarinov on February 11 at 1:43 AM

  7. How to speed up compilations in ASP.NET Web Site

    When working with ASP.NET most developers, including me, choose to use the Web Site model. One of the reasons for that is the smooth working process. If you make a change in your website you do not need to manually recompile - asp.net does that for you. But because of this change there is a slight delay before the site starts again. There are several tricks to decrease this time to minimum.

    1) Use the optimize compilation option. It was introduced with a hotfix for .net 3.5 sp1. You can find it here - http://support.microsoft.com/kb/961884.
     In general on change in App_Code, web.config or Global.asax file ASP.NET wipes the temporary files and generates new. This option allows ASP.NET to generate only the changed part of the files and leave the others. The only thing you have to do to enable this behavior is to put in your web.config :
    <compilation optimizeCompilations="true">
    The fix is for Windows XP,Windows Server 2003, Windows Vista and Windows Server 2008.
    If you're running Windows 7 or Windows Server 2008 R2 you already have this feature installed but you still need to enable it.

    The first trick will take care of the redundant file generation but files still will be copied. The Second one will speed the copy and access process.

    2) Keep your ASP.NET temporary files in the RAM. There are some programs that create a RAM disk - a hard disk partition that is persisted in the RAM. I personally use RAMDisk - it is free for hard disks bellow 4GB and you can download it from this address - http://memory.dataram.com/products-and-services/software/ramdisk/download-ramdisk. The UI of the software is pretty simple - you have to choose size of disk in MB and Format.

    RAMDisk

    The options for format are FAT16, FAT32 & Unformatted. You can use Also NTFS which I will recommend. You need to choose the Unformatted option. Then you Start the RAMDisk, go to Control Panel->Administrative Tools->Computer Management and in the left pane choose Storage->Disk Management. Right-click on the unallocated space and choose New Simple Volume. You'll be prompted to choose Letter for the volume - I usually choose R (for RAMDisk).

    ComputerManagement

    Now you should be able to see the new drive in Windows Explorer.

    WindowsExplorer

    The only thing you have to do next is to change the path for your temporary ASP.NET files in web config's compiler section.
    <compilation defaultLanguage="c#" debug="true" optimizeCompilations="true" tempDirectory="R:\ASP_NET_TempFiles\" >
    On the next website request you'll see that the files will be populated on your newly created RAM disk.

    The size of the disk depends on how big your project is. I usually use no more than 512MB - a good round number :-) .

    If you want to keep the data in the virtual disk even when you shut down your PC you can persist the drive to image file (.img) from RAMDisk.

    RAMDisk second tab

     

    P.S. Have in mind that there are technologies that does put your most used files in the RAM automatically (for example Microsoft Super Fetch) but you do not have controll what does and what doesn't get cached. So just try this method and see if there are any improvements in web application start time.

    Posted by Branislav Abadjimarinov on February 02 at 11:18 AM

  8. Application Architecture Guide 2.0

    In codeplex I found a very interesting book part of Microsoft Patterns and Practices. The book is Application Architecture Guide 2.0 - http://www.codeplex.com/AppArchGuide . It covers various topics from application architecture field in Microsoft and in general. The book is a must read for Microsoft application architects, developers and even IT. It will help you understand a lot of the terminology and the ideas behind the application design. The chapters are short, informative and very well written. The book is one of the few good readings I've found about Architectural design patterns. The lack of information in this area is one of the reasons for so much badly designed code in applications. I think also that it will be awesome if we can create a university course for Application Architecture based on this book and other resources.

    Posted by Branislav Abadjimarinov on January 25 at 8:36 AM

  9. Renew User in the same Request in asp.net while using forms authentication with cookies

    In ASP.NET forms authentication the usual authentication flow goes like this:

    • a user submits his credentials;
    • they are  validated against database, web.config or other data source;
    • an authentication cookie is issued and added to the current response (which is not sent yet);
    • the cookie is sent along with the response;
    • on the next request from that user the cookie is decrypted and the current Security Principal is initialised with the data;

    While this is good for most cases it has one flow - immediately after the authentication cookie is issued the current Security Principal for the request is outdated. You can check this with the following code:

    if(Membership.ValidateUser(userName, password))
    {
        FormsAuthentication.SetAuthCookie(userName, false);
        bool isAuthenticated = Request.IsAuthenticated; // isAuthenticated is false
    }

    This outcome is logical because of the authentication flow but some times it is confusing and can cause problems. A possible solution is to renew the information for the Current Security Principal for the request. This can be done with the following code:
    public void RenewCurrentUser()
    {
      System.Web.HttpCookie authCookie =
        System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
      if (authCookie != null)
      {
        FormsAuthenticationTicket authTicket = null;
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        if (authTicket != null && !authTicket.Expired)
        {
          FormsAuthenticationTicket newAuthTicket = authTicket;

          if (FormsAuthentication.SlidingExpiration)
          {
            newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
          }
          string userData = newAuthTicket.UserData;
          string[] roles = userData.Split(',');

          System.Web.HttpContext.Current.User =
            new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
        }
      }
    }

    You can check if the solution works like this:

    if(Membership.ValidateUser(userName, password))
    {
        FormsAuthentication.SetAuthCookie(userName, false);
        bool isAuthenticated = Request.IsAuthenticated; // isAuthenticated is false
        RenewCurrentUser();
        isAuthenticated = Request.IsAuthenticated; // isAuthenticated is true
    }
     

    Posted by Branislav Abadjimarinov on January 24 at 3:52 AM

  10. Attach already changed object to a data context in Entity Framework

    Entity Framework in its current version (.net 3.5 sp 1) has some problems with multi-tier application architecture. If you need to use different data context instances for getting an object and submitting the changes made to it you'll face some frustration. Typical scenario in n-tier applications is to use one data context for selecting data and another for submitting the changes made. The problem is that once you  attach an object to the new context you'll lose tracking of all changes made to the object.

    The solution is to explicitly call the SetModifiedProperty method  to notify the ObjectStateManager of the data context about the changes.  Also you should be aware that the property's state is set with reflection (when you need to specify a method or class name as string usually reflection is involved (-: )

                AdventureWorksLTEntities context = new AdventureWorksLTEntities();
                Product product = context.ProductSet.FirstOrDefault();
                if (product != null)
                {
                    product.ListPrice += 10; // product.EntityState is set to Modified
                }

                AdventureWorksLTEntities newContext = new AdventureWorksLTEntities();

                context.Detach(product); // product.EntityState is set to Detached
                newContext.Attach(product);  // product.EntityState is set to Unchanged

                ObjectStateEntry state = newContext.ObjectStateManager.GetObjectStateEntry(product);
                state.SetModifiedProperty("ListPrice"); // product.EntityState is set to Modified

                newContext.SaveChanges();


    P.S. Special thanks for this post to the ADO.NET team from Microinvest for introducing this problem to me.

    Posted by Branislav Abadjimarinov on December 12 at 12:38 AM

© Copyright 2017 Powered by AtomSite 1.3.0.0