C#

I gave up with Design Patterns in Java – I start my book

September 26, 2010 C#, Design Patterns, Java, Opinion, Personal, Success 12 comments

Yeah, title sounds not logically, but you will understand in a few why it is still relevant to this blog post.

It was and it is a good idea to…

In one of my blog posts I’ve decided to have all of the GoF Design Patterns written with Java. And idea itself is very good. Having all of the design patterns written by your own with you own examples gives you understanding of the DP that you cannot gain anywhere else plus to that if you have industrial experience of using all of them you can start think that you are guru of DP.

Process of writing my post on one of the Design Patterns looks like this: I read chapter of the GoF book on the particular DP, then I think up my own example if I do not have it already in my mind and after I’m done with some preliminary ideas I search over the internet for interesting articles on it and probably rethink some of the aspects of my example. After all of that I proceed to writing blog post and source code with Java.

Conclusion: Awesome and probably one of the best ways of learning DP is to have your own example of using it and industrial experience.

Design Patterns articles

One of the intents of having DP written in Java was to familiarize with that language. But it turns out that I did not learn much from Java (except of few things). Also few months ago I started keeping up Tuesday’s Design Pattern on the Lviv .NET User Group Page. Since it is .NET specific UG, I used to do following: 1) translate and 2) translate. In first place it is translation from English to Ukrainian and in second from Java to C#. When with item number one I have to apply some logic and rephrasing I cannot say the same about second item. I just copy code-paste code into Visual Studio and change few keywords. So what do I learn regarding of Java in this case?

I will continue learning Java, but I have to consider better way of doing it. I will also continue writing about Design Patterns, but with examples in C#.

Conclusion: Learning another programming language (Java) is really great idea, but be sure that you choose right approach of doing this.

First free e-book

On the road to Lviv I got perfect idea to start my first book. Of course this cannot be comprehensive stunning author’s book, but I have to start with something. In other words some probing book and this could be this “try it” case. I’m almost sure that there are no books about GoF Design Patterns in Ukrainian. (I suppose that there are in Russian, which can be easily understandable for most Ukrainians…)

How this book will be different?

  • It will be in Ukrainian.
  • It will NOT be a translation of GoF book in any way.
  • It will have my own unique examples.
  • It will be short and easy to understand.
  • It will be really cool kick-off book on DP for starting Developers.
  • It will be free to download.

Why do I need it?

I understand that this book might not be popular at all. But I have to start with something and plus to this it will help me familiarize with the whole process and build my confidence for future.

Also if you have some doubts about my idea I have a question for you: “Have you ever dreamt about your own book? If yes, do you have at least small book written?”

Conclusion: Never be skeptic about starting your first book. It might be a huge step to your success as anything else you are hesitating about but still dreaming about it!


12 comments


.NET Remoting Quickly

August 11, 2010 .NET, C#, HowTo No comments

As you may know recently I got junior to mentor him. In order to understand his capabilities and knowledge I asked him to do couple of things, like explain me one Design Pattern he knows, explain SCRUM and write the simplest .NET Remoting. So that was yesterday and today I verified that he failed with .NET Remoting, but it doesn’t mean that he is bad. He just need learn googling art more. I asked that for next day, and gave him stored procedure to write. Hope he will be smart enough to finish it till I come tomorrow from my English classes.

.NET Remoting

To ensure that I’m not asshole that asks people to do what I cannot do, I decided to write it by my own and see how long will it take for me. It took me 23 minutes. Hm… too much, but I should complain at VS about “Add Reference” dialog.

So here we have three projects in Visual Studio: one for Server, one for Client and of course Proxy class shared between client and server.

Shared proxy class ChatSender in ChatProxy assembly:

    public class ChatSender : MarshalByRefObject
    {
        public void SendMessage(string sender, string message)
        {
            Console.WriteLine(string.Format(“{0}: {1}”, sender, message));
        }
    }

Server (ChatServer):

    class Program
    {
        static void Main(string[] args)
        {
            var channel = new TcpServerChannel(7777);
            ChannelServices.RegisterChannel(channel, true);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(ChatSender),
                “ChatSender”, WellKnownObjectMode.Singleton );
            Console.WriteLine(“Server is started… Press ENTER to exit”);
            Console.ReadLine();
        }
    }

Client (ChatClient assembly):

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(“Client is started…”);
            ChannelServices.RegisterChannel(new TcpClientChannel(), true);
            var chatSender =
                (ChatSender)Activator.GetObject(typeof(ChatSender), “tcp://localhost:7777/ChatSender”);
            string message;
            while ((message = Console.ReadLine()) != string.Empty)
            {
                chatSender.SendMessage(“Andriy”, message);   
            }
        }
    }

My results


No comments


Threading.Timer vs. Timers.Timer

June 9, 2010 .NET, C#, Concurrency, Performance 6 comments

I agree that title doesn’t promise a lot of interesting stuff at first glance especially for experienced .net developers. But unless you encounter some issue due to incorrect usage of timers you will never think that root is in timers.

System.Threading.Timer vs. System.Windows.Forms.Timer

In few words what are differences between Threading and Forms timers just to start with something.
System.Threading.Timer executes some method on periodic bases. But what is interesting is that execution of method is performed in separate thread taken from ThreadPool. In other words it calls QueueUserWorkItem somewhere internally for your method at specified intervals.
System.Windows.Forms.Timer ensure as that execution of our method will be in the same thread where we’ve created timer.

What if operation takes longer than period?

Let’s now think what will happen if the operation we set for execution takes longer than interval.

When I have following code:

    internal class LearningThreadingTimer
    {
        private System.Threading.Timer timer;
        public void Run()
        {
            timer = new Timer(SomeOperation, null, 0, 1000);
        }
        private void SomeOperation(object state)
        {
            Thread.Sleep(500);
            Console.WriteLine(“a”);
        }
    }

my application behaves well – prints “a” twice a second. I took a look for number of threads in Task Manager and it stays constantly (7 threads).
Let now change following line: Thread.Sleep(500) to Thread.Sleep(8000). What will happen now? Just think before continue to read.
I’m almost completely sure that you predicted printing “a” every second after 8 seconds have passed. As you already guessed each of the “a” printings are scheduled in separate threads allocated from ThreadPool. So… amount of threads is constantly increasing… (Every 1.125 seconds :) )

Issue I’ve been investigating

Some mister X also figured out that Console.WriteLine(“a”) is critical and should run in one thread, at least because he is not sure how much does it take to execute Thread.Sleep(500). To ensure it will run in one thread he decided to have lock, like in code below:

    internal class LearningThreadingTimer
    {
        private System.Threading.Timer timer;
        private object locker = new object();
        public void Run()
        {
            timer = new Timer(SomeOperation, null, 0, 1000);
        }
        private void SomeOperation(object state)
        {
            lock (locker)
            {
                Thread.Sleep(8000);
                Console.WriteLine(“a”);   
            }
        }
    }

Yes, this code ensures that section under lock is executed in one thread. And you know this code works well unless your execution takes few hours and you will be out of threads and out of memory. :) So that is an issue I’ve been investigating.

My first idea was System.Windows.Forms.Timer

My first idea was to change this timer to the System.Windows.Forms.Timer, and it worked well in application, but that application is able to run in GUI and WinService modes. But there are so many complains over interned to do not use Forms.Timer for non UI stuff. Also if you put Forms.Timer into your console application it will simply not work.

Why System.Timers.Timer is good toy?

System.Timers.Timer is just wrapper over System.Threading.Timer, but what is very interesting is that it provides us with more developer-friendly abilities like enabling and disabling it.

My final decision which fixes issue is to disable timer when we are diving into our operation and enable on exit. In my app timer executes every 30 seconds so this could not be a problem. Fix looks like:

    internal class LearningTimersTimer
    {
        private System.Timers.Timer timer;
        private object locker = new object();
        public void Run()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += SomeOperation;
            timer.Start();
        }
        public void SomeOperation(object sender, EventArgs e)
        {
            timer.Enabled = false;
            lock (locker)
            {
                Thread.Sleep(8000);
                Console.WriteLine(“a”);
            }
            timer.Enabled = true;
        }
    }

And it looks that we don’t need lock there, but I left it there just to be sure is case if SomeOperation will be called from dozen of other threads.

MAKE DECISION ON TIMER BASING ON THIS TABLE (from msdn article)

System.Windows.Forms System.Timers System.Threading
Timer event runs on what thread? UI thread UI or worker thread Worker thread
Instances are thread safe? No Yes No
Familiar/intuitive object model? Yes Yes No
Requires Windows Forms? Yes No No
Metronome-quality beat? No Yes* Yes*
Timer event supports state object? No No Yes
Initial timer event can be scheduled? No No Yes
Class supports inheritance? Yes Yes No
* Depending on the availability of system resources (for example, worker threads

I hope my story is useful and when you will be searching like “C# Timer Threads issues” or “Allocation of threads when using timer” you will find my article and it will help you.


6 comments


Moving C# code to Java

May 9, 2010 C#, Java, MasterDiploma, Opinion 4 comments

Is CLR worse than JVM or it is just because my code is bad?

Today I had conversation with one man, who is great defender and evangelist of Java related technologies.

We talked about some algorithm implemented by me with C#. That is implementation of SOM algorithm and Concurrency stuff for it. My concurrency implementation doesn’t show time improvements unless grid size is big. He was able to achive better result with small grid sizes.

There could mean two reasons:

  • CLR concurrency model gives up in front of JVM concurrency
  • My implementation has gaps… which is more likely :)

Taking into consideration that I’m getting better results when grid is of bigger sizes I could suppose that in my algorithm there is code which takes constant (or near that) time and is not paralleled.

When I look at picture of Task Manager when my programm is executing I see that second processor has  gaps when it does nothing:

This could mean only one: I need to take better look what else is executed in one thread in my application and could be paralleled.

Converting C# code to Java

But back to that man and Java. I said to myself that it is possible to move my code to Java if something.

C# to Java Converter

Download C# to Java Converter demo version from here. Since it is demo you could not convert more than 1000 lines of your code. Order costs 119$.
Because of that I was forced to remove all not necessary code. I removed all concrete classes that I’m not using and GUI, but that did not help. I did not know how much should I delete more.

Number of lines in my project/solution

I googled for line numbers in C# and found this nice tool:

Now I know that my program has about 4000 lines of code. I left about 980 lines of code in two projects that I needed and was porting them to Java separately.

Converter GUI

And converted them to Java:

Is conversion an easy task?

Conversion could be painful if you have a lot of code that interacts with system, like threads, reading and writing to files, reading configuration file, etc.

Also it was not able to recognize ‘var’ keyword. It shows me this:

//C#
TO JAVA CONVERTER TODO TASK: There is no equivalent to implicit typing
in Java:

var neuronsCount =
getNetwork().getNeurons().size();

I moved back to my C# code and changed all var to the explicit types. And regenerated Java code.

There were some troubles when I’m delivering from List<T> and doing some stuff around that.
This code:

                int a =
this[next];
                this[next] = this[i];
                this[i] = a;

I rewrote manually to:

                int a =
super.get(next);
                super.set(next, super.get(i));
                super.set(i, a);

Also Converter was not able to convert this:

Console.ReadKey();

The biggest challenge is ThreadPool and synchronizing threads tech-nicks. This requires lot of google search that shows me that instead of ManualResetEvent I could use CyclicBarrier and how to utilize thread queuing in Java.

P/S I need to find gaps in my code to show that at least CLR and myself are not so much bad things in this world :)


4 comments


Null is not equal to null. How could that happen?

April 13, 2010 C# 2 comments

Today one of my colleagues bring me a present – a new blog post!

Please take a look on the following picture and think how could execution step into the if statement. See that oldPerson is null!

She has asked everyone if anyone knows how could this happen. Do you know?

Honestly my first thought was that it is something with Nullable<T>, or maybe method Find isn’t what we think about it. I had thought that it could be LinQ method, which is somehow wrong, whatever. But nothing of that is true. :(

She did not sent the whole picture so we did not know what is the type of oldPerson object. So far we don’t know the type and we know that “!=” behaves somehow different. That’s it! Operator is wrong and I won beer. (of course not :) )

So let’s take a look on implementation of the operator:

    1 using System.Collections.Generic;
    2 
    3 namespace ConsoleApplication1
    4 {
    5     internal class Person
    6     {
    7         public string Name { get; set; }
    8 
    9         public static bool operator ==(Person left, Person right)
   10         {
   11             if (ReferenceEquals(null, right)) return false;
   12             if (ReferenceEquals(left, right)) return true;
   13             return Equals(left.Name, right.Name);
   14         }
   15 
   16         public static bool operator !=(Person left, Person right)
   17         {
   18             return !(left == right);
   19         }
   20 
   21         public bool Equals(Person obj)
   22         {
   23             return (this == obj);
   24         }
   25 
   26         public override bool Equals(object obj)
   27         {
   28             if (ReferenceEquals(this, obj)) return true;
   29             if (obj.GetType() != typeof(Person)) return false;
   30             return (this == ((Person)obj));
   31         }
   32 
   33     }
   34 
   35     class Program
   36     {
   37         static void Main(string[] args)
   38         {
   39             var persons = new List<Person>()
   40                 {
   41                     new Person(){Name = “Ivan”},
   42                     new Person(){Name = “Andriy”}
   43                 };
   44 
   45             foreach (var item in persons)
   46             {
   47                 var oldPerson = persons
   48                     .Find(x => x.Name == item.Name+“Not Andriy”);
   49 
   50                 if (oldPerson != null)
   51                 {
   52                     item.Name = oldPerson.Name;
   53                 }
   54             }
   55         }
   56     }
   57 }

Do you already see where the problem is? It is definitely in line 11: if (ReferenceEquals(null, right)) return false;
if we will get null in right object it will say that null is not equal to null.

Reason why she needs that so much complicated is because she accesses properties of the object in return condition later:
return Equals(left.Name, right.Name);


2 comments


Get started with F#

April 4, 2010 .NET, C#, F# No comments

Renaissance of functional languages

We are at renaissance of functional languages. When I read blog posts I often see guys talking about functional programming and stuff related to it. Community wants more features that functional style provides for us. In response to that creators of languages and technologies are now introducing a lot of amazing cool features to make our life happier. They also create new languages, and so on.

What is going on with C# nowadays?

Let’s start with what we do have with C# nowadays. It has moved to functional side slightly. Introducing LINQ is big step in that direction. We are moving away from imperative programming to functional, for example this simple loop represents imperative way to work with list items.

      foreach (var element in
list)
      {
   
    Console.WriteLine(element);
      }

Using LinQ we can have so much elegant functional syntax:

      list.ForEach(Console.WriteLine);

So we pass function into function. Simply saying that is why we call this functional programming. If example above isn’t so bright take a look on next:

      Func<int, int>
doubleThat = delegate(int x) { return
x * 2; };
      var
from2To20 = from1To10.Select(doubleThat).ToList();

Another example of that C# is more close to those languages is introducing var keyword, which doesn’t mean that we can change type in further code like in dynamic languages, but that is thing which really helps us to write code without being really concerned about types, but the language itself is still strongly typed. If you would say here about C# dynamics, hm.. honestly I’m not a fan of that thing in C#, but maybe it gives some advantages for us.

Immutability

Few days ago I have heard podcast where guy from Microsoft .NET languages team spoke about different features that community had requested to language C#. One of them was immutability and it looks that they are going to introduce this in further releases (after 4.0 of course). So what is immutability? It is something that functional languages has by default and imperative hasn’t :).

For example we have

   int number = 1;
   number = number + 3;

We can change number as many times as we want. But the same in F# will produce compilation error:

(“<-” is assignment operator in F#). In order to make it work you will need another element result:

If you want variable with you 100% want to change you should declare this using mutable keyword:

Functions

So lets move to much interesting – declaring functions:

ten will be immutable variable which has value 10.

Are you familiar with parameter binding in C++ functors? It doesn’t matter but, currying of methods in F# reminds me that. Take a look how we get new method with mixing function multiply and using one frozen parameter.

Using F# library in other .Net languages 

I did all this fun stuff with creating new F# library in Visual Studio. I viewed results of code which interested me with selecting it and pressing ‘Send To Interactive’ from context menu. Next what was interested for me is how can I use that dll in my usual C# program. So I created console application, added reference to my F# lib. Now I can use it like below:

See how things differs out there. Method is seen as method, immutable variables as properties without setter and mutable as properties with setter. Forgot to mention that FirstFSharpProgram  defines with keyword module at the top of *.fs file.

Why?

When could F# be useful? Anywhere you would like. But as it creators says it has lot of multi-threading capabilities plus to that you write immutable code, which was the main root of stupid bugs in imperative programming. Plus to that you can easily use it in combination to other .NET languages.

Don’t miss chance to learn this language if you are interested in it.

Take a look on this elegant Fibbonachi solution: let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)


No 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


Constraints for my Generics

February 26, 2010 .NET, C# No comments

I have never used constraints for my generic classes. So in this article I just want to show how I’ve used it:

So for now I have ICustomer interface:

    public interface ICustomer
    {
        string Name { getset; }
        List<int> GetOrders();
    }

and two implementations like UsualCustomer and VipCustomer.

Also I’m going to have some OrderingProcessor which is supposed to be operating with different types of Customers. But when I want to call GetOrders method I just have not it in my list, like below:

but once I’ve changed the declaration of the OrderingProcess just a little bit, with specifying type of T

    public interface IOrderingProcessor<T>
        where T : ICustomer
    {
        void Process(T objectToProcess);
    }


World has smiled to me and I’m getting what I want, please see:

I expect that you are laughing while reading this post. Maybe because this thing is too simple to write article/post on it if you are familiar with C#/.NET. Yes, but I have never tried it myself. Did you?

To make you laughing not so much loud let us take a look on another architecture:

    public interface IOrderingProcessor<T>
        where T : ICustomer
    {
        void Process(T objectToProcess);
    }
    internal class VipOrderingProcessor<TCustomer> : IOrderingProcessor<TCustomer>
        where TCustomer : IVipCustomernew()
    {
        public void Process(TCustomer objectToProcess)
        {
            var vipCustomer = new TCustomer();
            var orders = objectToProcess.GetOrders();
        }
    }

As you see we can create specific VipOrderingProcessor and we are constraining it to use just VipCustomers or derived classes. This gives us opportunity to specify constraints on different levels of implementation.

But do you know what does another constraint  new() mean?
This constraint specifies that TCustomer objects will have public default constructor, so you can write

            var vipCustomer = new TCustomer();

This could be very useful for implementing Factory Design Pattern. I’m sure that next time I will need to develop whole family of Factories I will use constraints, since code could be much flexible in this case.


No comments


C# is language for my Diploma. It just won. What could I do?

February 21, 2010 C#, Java, MasterDiploma 2 comments

Today I committed initial version of my Diploma Work Sources.

And there are few interesting things regarding to my first commit.

Thing One (Language)

I re-wrote all my last year course work from Java to C#.
And I did it all in about 12 hours. Its just amazing how my developing speed differs in eclipse and Visual Studio IDEs. As I remember same took me 50+ hours with Java + eclipse and I did all without enthusiasm.

I hate writing properties in Java
This is one thing where I do think that Java is kind more verbose than C#. There are some others, like “var”, etc. Microsoft works on improving C# language.

C#

   public double[] Parameters {get; set;}
Java

    private double[] parameters;
    public double[] getParamateres(){
        return parameters;
    }
    public void setParamateres(){
        return parameters;

    }


How important is your knowledge of IDE?

I would say that even more then knowing of language. Nowadays most of  the languages are object-oriented, they all have similar principles and ideas and code looks almost the same. If we talk about C# and Java they are extremely alike.
I’m not very familiar with Java, but I can write Java code easily and if there are some Java specific gaps I quickly fulfill them with google search.
But when we talk about my speed of coding in eclipse IDE – it is really outstanding thing where my capabilities suck.

Code refactoring tool
That is another thing that could significantly increase your productivity. I’m using Resharper 5.0 Beta. Having experience of using it, I can think about what I want to have, but not how to type that.
Live templates that generates me unit test method after I just type “test”. Delivering from interface, I just created, without typing class name. Moving initialization of fields to the class constructor with single command. “Alt+Enter” just thing instead of me in contest of where mouse cursor is located and proposes me decisions.  — these all are things why I love Resharper. I wrote complex architecture with about 40 classes in about 12 hours. It generates what I think.

Thing Two (Architecture)


I improved my Self-Organizing Maps implementation architecture significantly. What is did is having all implemented in really decoupled interfaces. Main learning processor is just like preparing dinner. You just add component and you do have what you want.

        public LearningProcessorBase(
            ILearningData learningData,
            INetwork network,
            ITopology topology,
            IMetricFunction metricFunction,
            ILearningFactorFunction learningFactorFunction,
            INeighbourhoodFunction neighbourhoodFunction,
            int maxIterationsCount)
        {
            LearningData = learningData;
            Network = network;
            Topology = topology;
            MetricFunction = metricFunction;
            LearningFactorFunction = learningFactorFunction;
            NeighbourhoodFunction = neighbourhoodFunction;
            MaxIterationsCount = maxIterationsCount;
        }

What is the benefit?
Now I’m able easily setup few dependency Profiles and experiment with them. So I can play with different activation, neigbourhood, metric and leaning factor functions, at the same time I can use different topologies like matrix and hexagonal.
Also learning process is now really encapsulated and to add Concurrency implementation should be easily.

Thing Three (I have same results with less effort)

To prove that I have same results I’ve used same application of my Kohonen Maps: classification of animals.
Here is input data list of different animals. Each row describes animal’s properties.

Here is result matrix:

Thing Four (Conclusion)

I’m  really sorry that it is boring for me to have my Diploma written on Java. But I really think that my goal is to invent multi-threaded algorithm that could significantly improve SOM calculations. And I feel really comfortable with C#, so I can enjoy research work without spending time on convincing myself that I do need to accomplish all with Java.
But this doesn’t mean that I gave up with learning Java. No – I will continue implementing all GoF Design Patterns on this pretty language – see my table.


2 comments