Decorator

March 23, 2010 Design Patterns 4 comments

I have a story about the doctor who had a very good and fast Mercedes. On the way to work he is often stuck in traffic congestion and this makes him mad and late making his patients suffer. He has a dream of his car becoming Ambulance so that all cars make the way. Only one issue with this: Ambulance should beep loud. Currently his car has no such loud horn. The doctor also doesn’t want to waive his warranty by changing internals of this car. Let’s decorate Mersedes so when you drive it beeps real loud. How can we accomplish this using a Decorator design pattern?

DECORATOR

So here we have Car class and Mersedes implementations:

The Decorator pattern is used to add some functionality to your objects. In our example we want to add beeping to the concrete implementation of Car, but also we can add other functionality. So in order to save contract of Car class and have base class for all features we create the CarDecorator class like below:

as you see it has decoratedCar wrapped, that is why patterns is also called Wrapper.
So in order to add some additional functionality we derive from Decorator class:

so it was slight extension – beeping :)

And usage looks very friendly – we cover Mersedes with Ambulance features, after that we can cover it with more abilities, in other words we can add features dynamically.

Output:

I’m Mercedes and I’m on my way…
…beep-beep-beep-…

I think you extected it. Now lets take a look at the UML diagram of this wisdom:

This pattern has some similarities to the Composite and Adapter patterns. Adapter could change the interface of behavior, but Decorator not (we are derived from Car). Composite works with lot of components, not like Decorator with only one.


4 comments


Resharper – navigating to .Net Framework code

March 23, 2010 Resharper No comments

As you know with Resharper when you press “Ctrl+B” you navigate to the declaration of thing you are currently located on. But when you press that on double for example? In Visual Studio you are able to navigate to the metadata view, but Resharper provides 3 options: Object Browser, MetadataView and actual .Net Framework code. If you have no appropriate mscorlib.pdb Resharper will download it like on the picture below:

So finally you are able to see this code:

namespace
System
{
    [ComVisible(true)]
    [Serializable]
    public
struct
Double
: IComparable,
IFormattable, IConvertible, IComparable<double>,
IEquatable<double>
    {
        public
const double
MinValue = 1.79769313486232E+308;
        public
const double
MaxValue = 1.79769313486232E+308;
        public
const double
Epsilon = 4.94065645841247E324;
        public
const double
NegativeInfinity = Infinity;
        public
const double
PositiveInfinity = Infinity;
        public
const double NaN
= NaN;
        //….

This is one of things why I love Resharper, no need to go for another tool like Reflector.


No comments


Simple example to see multithreading data sharing issues

March 23, 2010 .NET, Concurrency No comments

I heard a lot of the corruption that could be made by the multiple threads when they share same data. And understanding why that happen is not so hard, but I wanted some bright example of it, which will be able to quickly show what is going on.

So here is my example:

    public class Counter
    {
        public
int Count = 0;
        public
void UpdateCount()
        {
            for
(int i = 0; i < 10000; i++)
            {
                Count = Count + 1;
            }
        }
    }
    class Program
    {
        static
void Main(string[]
args)
        {
            var
counter = new Counter();
            var
threads = new Thread[500];
            for
(int i = 0; i < threads.Length;
++i)
            {
                threads[i] = new Thread(counter.UpdateCount);
                threads[i].Start();
            }
            foreach
(var thread in threads)
                thread.Join();
            Console.WriteLine(string.Format(
                @”If you are running this code on multiple processors machine you
probably will not get expected ThreadCount*Iterations={0}*{1}={2}, but
less number, which is currently equal to {3}”
,
                    threads.Length, 10000,
threads.Length * 10000, counter.Count));
        }
    }

As you see I’m using 500 threads. Why? First it is because this ensures that lot of them will be allocated on another processor and second is because the UpdateCount runs “Count = Count + 1” that is quite very trivial and requires about 3 atomic operations, so to increase possibility to run them in concurrent threads I increased their count.

Below is the output:

If you are running this code on multiple processors machine you probably will no
t get expected ThreadCount*Iterations=500*10000=5000000, but less number, which
is currently equal to 4994961
Press any key to continue . . .
As you see the actual number of the Count field is less than expected. We lost one each time when next happens at once:
Thread 1: Reads Count (1000)
Thread 2: Reads Count (1000)
Thread 1: Increases Count (1001)
Thread 2: Increases Count (1001)
Thread 1: Writes Count (1001)
Thread 2: Writes Count (1001) – he-he so it wrote back the same number, not 1002
You probably already know how to solve this with lock or Interlocked class or other stuff.
For example just change line Count = Count + 1; with line Interlocked.Increment(ref Count); or lock (this)Count = Count + 1; But I’m getting fun writing this.


No comments


Code Complete – Classes, Methods, Defence Programming

March 21, 2010 Book Reviews, Clean Code, Opinion No comments

Yesterday I’ve read 3 chapters of the “Code Complete“. First one of them was a “Classes” and second was “Methods”. I would say that I took almost nothing for myself from those pages, but the third one was “Defense Programming” and it was quite enjoyable to read.

Classes

Class should stand for one logical unit of understanding from real world or from your system. In other worlds it should be noun, that could do some appropriate operations. It is not just a set of data. Also class should have Single Responsibility – not doing things it should not do and not be cohesive to other classes. Class should not contain too much data and too many methods.
After that McConnel talks about the Composition and Inheritance.
Use inheritance when behavior contract is the same and data is the same to some extend, but only concrete behavior differs, but not expectations of it.
Use composition when behavior is 100% the same, but you still could distinguish what you have before and what you would like to have further.
This means that no need to have AccountLessPerson if the person does not have bank account, it definitely better to have Person with field BankAccount.
Liskov Substitution Principle says that once you have class B derived from class A, other classes should work with B by the contract which is the same as A declares, only enhancements to the behavior is allowed, no real change in it.

Methods

It was boring to read this chapter. i.e. methods should have appropriate names, they should not be longer than N lines of code and be readable, they should not take more than 7 parameters, they should not change params, they should not change global fields etc….
It had to be much better to read there more about how methods should interact with other system.

Defence Programming

This was the most interesting part for me. This all is about building the wall of protection to your system. And this is needed to serve two main purposes: first is stability of the system and the second is for insuring correct behavior.
Assert
Assertion is the way to defense your code from wrong input data, and even defensing yourself from giving wrong result. For example in the beginning of method GetOrdersForAccountNumber(int accountNumber) you could have Assert.That(accountNumber > 0, “since you will not be able to make order with wrong number”) and after you finished with all calculations you could have Assert.That(orders != null, “because don’t think that that is good idea to pass out null object…”).
Exception handling
Exceptions is the tool for working with unusual situations that occur in your application. Some languages still don’t have build-in exception handling, and I’m so lucky that I work with such language like C#. McConner says “Develop with language, not on language”, but the C# just leads to writing a good code. Exception handling is quite big theme to discuss so I hope to have separate post on it.


No comments


Self-Organizing Maps – Заженемо речі в гратку

March 20, 2010 KohonenAlgorithm, MasterDiploma 2 comments

Одним із хороших тестів Самоорганізаційної карти є двовимірна інтерпретація двовимірного вхідного простору. Нейрони нейромережі почитають заповняти той простір із якого приходять вхідні вектори, таким чином можна наочно спостерігати за тим чи нейромережа дає хороші результати.
Для цього я використав решітку розміру 10 на 10. Нейромережа була початково ініціалізована випадковими значеннями нейронів від 0.25 до 0.75. Таким чином якщо постійно вчити нейромережу випадковими значеннями (від 0 до 1), то гратка повинна “розвернутися” на всю площину.
Я використовую 500 кроків на кожному із яких проганяю 100 випадкових точок для того щоб згладити навчання.
Ініціалізація:
 
Перша ітерація:
Друга:
 
300:
 
Остання (500та):

Якщо вхідні значення подавати не із всієї множини X [0, 1], Y[0, 1], а із множини що займає певний об”єкт, то карта просто дуже легко впишеться в нього.
Щоб переконатися в цьому я використав силует дівчини і для навчання подавав тільки точки, які входили в площину, де знаходиться дівчина.
 

Зробити це для мене було, корисно, оскільки я таки знайшов недолугі частини моєї імплементації і виправив декілька помилок в алгоритмі. Надалі я можу спокійно працювати над паралелізацією обрахунків.

Я сподіваюся що вам сподобалося. Коментарі?


2 comments


How to add icon for your custom UserControl to the Toolbox

March 19, 2010 .NET, HowTo, WindowsForms No comments

I read about ToolboxBitmapAttribute and while doing my usual work have decided to use it.

First of all I created my UserControl named BufferedControl which should provide double buffering functionality for me. Once I finished with my control I navigated to Toolbox to add new tool like on the picture:

And do you know what happend next? It said to me that there is no controls which could be added to the Toolbox. But why? It is derived from UserControl and looks fine. So in order to see what is the difference I added empty UserControl1 and was able to add it to the Toolbox. I thought that the reason is because I do not have designer file for my control and some specific methods like Initialize(), but after I added them nothing helped. I did more research and finally figured out that I did not have default public constructor. My constructor was like here:

        public
BufferedControl(IBufferedControlController controller)
        {
            Controller = controller;
            BufferContext = new BufferedGraphicsContext();
            SizeGraphicsBuffer();
           
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
            SetStyle(ControlStyles.DoubleBuffer,
false);
        }

So lets move to adding icon of your UserControl to the Toolbox

1) First add your control and draw the icon. Below is screenshot of what I have for this.

a) Once you done, you should ensure that your control has public default constructor and that OnPaint method will not raise exceptions after it was called on instance created with default constructor.
b) Also go to properties of your icon and set Build Action –> Embedded Resource.

2) Add ToolboxBitmap attribute to your control class declaration. In my case it looks like below:

namespace
Som.Application.Grid
{
    [ToolboxBitmap(“Som.Application.Grid.BufferedControl.ico”)]
    public class BufferedControl : UserControl
    {
      //…

3) Navigate to ToolBox and add your control from your assembly:

That’s it!


No comments


I love Performance Profiler

March 14, 2010 IDE, Performance 2 comments

Honestly I haven’t used any Performance Profiler, since I did not feel need to use it and also I thought that it could be boring… How was I wrong! It is so easy and intuitive, I’m getting super good reports with highlighting of  expensive code and it keeps highlighting in Visual Studio. So I’m always aware which code is expensive.

Take a look:

I love it.


2 comments


Multithreading in CLR

March 14, 2010 .NET, C#, Concurrency No comments

Here I have code that provides some explanations to the multithreading in .NET. Wrote it to refresh what I know on concurrency.

    1 /********************************************************
    2  *
    3  *                CODE IS MY PRESENTATION
    4  *
    5  ********************************************************/
    6 using System;
    7 using System.IO;
    8 
    9 //1. CLR threading is based on Windows threading.
   10 //2. CLR threading is going away from correspondence with Windows threading.
   11 //SO do not use native windows functions if you already writing CLR code
   12 //that is for future, of course Microsoft is not sleeping
   13 
   14 //Let’s start
   15 //This is namespace where Multithreading lives…
   16 using System.Threading;
   17 
   18 namespace TheoryConsole
   19 {
   20     class Program
   21     {
   22         static void Main(string[] args)
   23         {
   24             MultiThreadingInCLR presentation = new MultiThreadingInCLR();
   25 
   26             //presentation.CLRHasPoolOfThreads();
   27             //presentation.UsingThreadPoolForAsynchCalculations();
   28             //presentation.UsingDedicatedThread();
   29             //presentation.PeriodicalCallinOfAsynchOperations();
   30             presentation.AsynchronousProgrammingModel();
   31 
   32             Thread.Sleep(100);
   33             //Console.WriteLine(“Press any key to exit…”);
   34             //Console.ReadLine();
   35         }
   36     }
   37 
   38     public class MultiThreadingInCLR
   39     {
   40         //Many developers uses multithreading too often,
   41         //but it is not cheap.
   42 
   43         //Because
   44         //to Switch context system needs:
   45         // – go to core -> save processor registers ->
   46         // put spin-blocker -> take another thread ->
   47         // unput blocker -> load registers > run thread
   48 
   49         //Pool of Threads
   50         public void CLRHasPoolOfThreads()
   51         {
   52             //Each Process has its oun Pool wich can be used
   53             // in all AppDomains of that Process
   54             ThreadPool.QueueUserWorkItem(DoAsynchWork, 10);
   55 
   56             //If there are no requests to Pool,
   57             //CLR will delete threads from it in about 2 minutes
   58 
   59             // Amount of threads in Pool
   60             // – Do not try to limit amount of threads in Pool
   61             // There are two types of threads: Worker and I/O
   62             int workingThreads = 0;
   63             int completionThreads = 0;
   64             //Get/Set Max/Min Threads
   65             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   66 
   67             //To GetAvailableThreads call it:
   68             //ThreadPool.GetAvailableThreads();
   69 
   70             for (int i = 0; i < 506; i++)
   71             {
   72                 ThreadPool.QueueUserWorkItem(DoAsynchWork, 100);
   73             }
   74 
   75             ThreadPool.GetMaxThreads(out workingThreads, out completionThreads);
   76             workingThreads = 1000;
   77         }
   78 
   79 
   80         public void UsingThreadPoolForAsynchCalculations()
   81         {
   82             //If you do not need I/O operations use Worker type of thread
   83             //For example spell-checker in some editor need to work asynchronously
   84             //
   85             //Most commonly these three methods are called:
   86             //
   87             //static Boolean QueueUserWorkItem(WaitCallback callBack);
   88             //static Boolean
   89             //   QueueUserWorkItem(WaitCallback callBack, Object state);
   90             //static Boolean
   91             //   UnsafeQueueUserWorkItem(WaitCallback callBack, Object state);
   92 
   93             //callBack is delegate with the next signature:
   94             //delegate void WaitCallBack(Object state);
   95             WaitCallBackExample_IDoHardWork(null);
   96 
   97             //Here is how to start doing hard work asynchromously
   98             ThreadPool.QueueUserWorkItem(WaitCallBackExample_IDoHardWork);
   99 
  100             //Use UnsafeQueueUserWorkItem if the time resource is very critical
  101             //Reason: QueueUserWorkItem is verifying
  102             // if the assemblies from Thread stack has permissions
  103             // to access file for example
  104             //SecurityException could be generated if there is no presmissions
  105         }
  106 
  107         #region Dedicated Thread
  108         public void UsingDedicatedThread()
  109         {
  110             //Commonly is used if we need to set some priority to thread
  111             // or if we need to change other properties of Thread
  112             // – we need set some properties to the thread
  113             // – we need set priority to our thread
  114             //        (ThreadPool has one priority for all threads in it)
  115             // – if we want run Thread in foreground
  116             //        (ThreadPoole runs threads in background)
  117 
  118             //please note that here we do NOT create actual thread,
  119             // because thread will be created only
  120             //when we will call our thread object
  121             Thread someNewThread = new Thread(ComputeBoundWork);
  122             //When we call Start method actuall thread is created
  123             // and process starts
  124 
  125             someNewThread.Start(1);
  126             Thread.Sleep(1000);//this imitates some work in main thread
  127 
  128             //Please note!
  129             // that after ComputeBoundWork finished its work,
  130             // actual system thread was deleted
  131 
  132             // this waits while the dedicated thread will finish all its work…
  133             someNewThread.Join();
  134 
  135             // so this is some kind of sysnch of threads..
  136         }
  137         #endregion
  138 
  139         #region Timer
  140         public void PeriodicalCallinOfAsynchOperations()
  141         {
  142             //System.Threading namespace has Timer defined
  143             //it has 4 very similar constructors
  144             //this used only TimerCallback
  145             //Timer timer1 = new Timer(ComputeBoundWork);
  146             Timer timer2 = new Timer(ComputeBoundWork, null, 0, 1000);
  147             // method will be called only once
  148             //Timer timer3 =
  149             //  new Timer(ComputeBoundWork, null, 0, Timeout.Infinite);
  150 
  151             //if you want to change timing behaviour of the timer
  152             // you could use Change() method, or Dispose() to stop…
  153             Thread.Sleep(10000);// this imitates some work here – 10 seconds
  154             timer2.Dispose();
  155 
  156             // Please note that there are 3 different Timers in FCL
  157             // – System.Threading.Timer
  158             //      is most suitable for doing asynch operations
  159             // – System.Windows.Forms.Timer
  160             //      is equivalent to WinAPI SetTimer.. events are added WM_TIMER
  161             // – System.Timers.Timer
  162             //      is some kind of wrapper of the Threading.Timer
  163         }
  164         #endregion
  165 
  166         #region Asynchronous Programming Model
  167 
  168         private IAsyncResult synchResultForFileWriting;
  169         private FileStream fs;
  170         public void AsynchronousProgrammingModel()
  171         {
  172             // Using of the asynchronous operations is the key to big programms :)
  173             // Combination of it with the ThreadPool
  174             //  is way to effectively use all processors of the system.
  175             // Examples where it is used…
  176             // – System.IO.Stream -> FileStream and NetworkStream
  177             //        derived classes has methods BeginRead(), BeginWrite()
  178             // – System.Net.Dns -> BeginGetHostAddresses(),
  179             //        BeginGetHostByName(), and so on…
  180             // – System.Net.Sockets -> BeginAccept(), BeginConnect(), …
  181             // all delegate types has BeginInvoke(), what could be used in APM
  182 
  183             //ok let we see file reading example
  184             fs = new FileStream(
  185                 “test.bin”, FileMode.OpenOrCreate,
  186                 FileAccess.Write, FileShare.None, 35000, FileOptions.Asynchronous);
  187             synchResultForFileWriting =
  188                 fs.BeginWrite(new byte[32738], 0, 32000, CallBackMethod, null);
  189             Console.WriteLine(
  190                 “This is called just after we said to write something to file.”);
  191 
  192 
  193             // There are 3 types of joining threads.. im APM
  194             // 1. Waiting for finish of work
  195             //Int32 readMeFile.EndRead(IAsyncResutl asyncResult)
  196 
  197             // 2. Regualar polling – is not effective method
  198             Stream readMeFile = new FileStream(“film.mp4”, FileMode.Open,
  199                   FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous);
  200 
  201             byte[] fileContent = new byte[450000000];
  202             IAsyncResult ar =
  203                 readMeFile.BeginRead
  204                     (fileContent, 0, fileContent.Length, null, null);
  205 
  206             while (!ar.IsCompleted)
  207             {
  208                 Console.WriteLine(
  209                     “Reading Large Music file operation is not completed…”);
  210                 Thread.Sleep(100);
  211             }
  212 
  213             //please note that this will not stop actuall
  214             //     thread because we were asking for finish above
  215             readMeFile.EndRead(ar);
  216             Console.WriteLine(“We already finished reading large music file.”);
  217 
  218             // 3. Callback!!
  219             // is the most efficient and commonly used joining type
  220         }
  221 
  222         private void UserAlreadyWantsToReadThatFile()
  223         {
  224             fs.EndWrite(synchResultForFileWriting);
  225             //now we are sure that ansynch writing to file has finished its work!!
  226             fs.Close();
  227         }
  228 
  229 
  230         private void CallBackMethod(IAsyncResult ar)
  231         {
  232             //this method will be called when writing to file will finish its work
  233             Console.WriteLine(“We just finished writing to file…”);
  234         }
  235 
  236         #endregion
  237 
  238         public void WaitCallBackExample_IDoHardWork(object hardParameter)
  239         {
  240             //actually if you see my body you know that I do not do work
  241             // I sleep for 2 seconds :)
  242             Thread.Sleep(2000);
  243         }
  244 
  245         public void DoAsynchWork(object miliseconds)
  246         {
  247             Thread.Sleep((int)miliseconds);
  248         }
  249 
  250         public void ComputeBoundWork(object opCode)
  251         {
  252             Thread.Sleep(1000);// this imitates some work…
  253             Console.WriteLine(
  254                 string.Format(“Compuing bound work with param: {0}”, opCode));
  255         }
  256     }
  257 }


No comments


Few notes about Designing System

March 14, 2010 Book Reviews, Design No comments

Designing is “dry”, non-deterministic and heuristic process. 

I just read one chapter from S. McConnell’s “Clean Code” book, and want make some review and summary without taking a look back into book. This should help me reinforce memories of what I’ve learnt.

When you are designing you always should keep in mind that you will not be able to make design good for all situations of life. Thus overthinking on problems could lead to overengineering, so you will get complex system with lot of unneeded tails. Future developers will not be able to work with your design. And project could even fail at some point of time.

To avoid this you should keep building system on easy to understand interfaces, that define how system behaves on different levels and that provide loose coupling.

Building your application like one solid system will lead to situation when you have everything coupled. I’m familiar with system, which is done like single exe file with more than 50 Mb size. You could not even imagine how everything there is coupled – you can get access to any part of the system from any other part. I understand that it is a legacy system and some things where done cause of ‘old school’ and so on and I understand that developers take this into account, but how on earth new guy will know how to work in that system? But how could it be sweet when you have system divided into subsystems, which of them has own responsibilities and depends only on one-two other subsystems, but at the same time provides functionality to good portion of other subsystems.

So, here we talk about low coupling, high cohesion and subsystems ordering. Here is how I do understand this terms:

Low coupling means that parts of the system should interact with each other by clearly defined interfaces, and you should work on decreasing number of interaction. Few characteristics that lead to low coupling are: Volume of connections should be low, Visibility of how two parts connects to each other should be high, Flexibility of changing connection should be also high.

High cohesion means that inside of one part of the system everything should be done compactly, part should have one responsibility well encapsulated inside.

Subsystems ordering means that once you have A and B, and B uses A, then A should not use B. If you need to grow your system you should decrease number of subsystems that you depend on and you should increase number of subsystems that depends on current subsystem. So you are getting tree.

When designing use Design Patterns. Why? Because they are found heuristically and if you think that you have a better decision to the same problem that known design pattern solves it is very possible that your solution will fail.

When designing ask Questions. Why? Designing is iterational  process, you always can improve your solution. Just ask yourself if your current design is enough good and if so how could you prove that. Ask if there are other solutions to problem and why did you select your. Ask a lot. Invite a friend let he ask you.

You can design top-bottom and bottom-top ways. Use both. Why and how? Because they have advantages and disadvantages – you can get stuck with top-bottom if you will not have tech solution to some problem, that was defined at the top or solution is very cumbersome, also you can lost vision of what you do with bottom-top and will lost how to clue everything. We are all now far from waterfall so I think that nowadays it is possible to combine those two ways to design.


No comments


Simple Web Page doesn’t work after Ctrl+F5 hit in VS under Windows 7

March 14, 2010 ASP.NET, Environment, QuickTip No comments

I’ve upgraded my system to Windows 7 couple of months ago, but I haven’t used web development.

The Problem
Few days ago, I created empty web application, added new page and added <p>bla-bla<p>, then I hit Ctrl+F5 and my default browser opened, but nothing happened. I was thinking that it is because of my browser, so I switched over 3 browsers and nothing helped, I also thought that it VS2010 broke something causing asp.net development server issues, so uninstalled it and installed back, but nothing helped.

I even had a thought to reinstall system, but decided to search over the internet more deeper and found that:

Reason
Reason is that when system uses IPv6 browsers could have issues with resolving localhost. 

Solution
Disabling IPv6 is solution for this problem.

You can disable IP 6 in your system by ensuring that you have this in your registry:
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpip6ParametersDisabledComponents set to 0xffffffff

Firefox settings change
Also when searching I found for myself that we can change settings of Firefox with writing about:config in address bar.


No comments