My 100-th blog post: Blogging Pays Off

July 3, 2010 Success No comments

Hello my Dear Readers, this post is my 100-th blog post.
Almost 9 months past since I’ve posted my first words here. I went through different topics here. Starting with design patterns and different educational stuff (my master year), and finishing with different book reviews and tips on how to become successful.

But why do I need blog?

First of all I love blogging. It helps me feel that I’m needed in this world and that I bring something valuable to others. Also it takes me closer to my life goals. One of those is to become successful world known developer. And even if I’ll switch to some managing position in the future I will still be developer of my and people’s around lives.
Blogging keeps me concentrated on different topics I write about, helping me understand them better. I would bet that most of the software developers think that they know Gof design patterns, but when you ask them about main concepts they could list only obvious. Ask them to perform research over internet and create own example and bright understanding will come to their mind. Same things happen to me. It is just amazing how something could be clear after you wrote a blog post about it.
Sometimes I’ve been posting short quick tips. They could look useless, but when I come to the same problem I just go to my blog and see the solution. It happened to me few times, and I was really proud that I have this blog.
Blogging helps me stand out. My colleagues see that I do the best to keep in touch with new technologies and that I’m trying to self-improve. Sometimes it makes me sad when I see others being much more proactive and productive, as Scott Hanselman (blogging god?). I’m afraid that I could make someone upset because of my mood. On the other hand when I see those active people it drives me to become super active. I hope I help my coworkers in their passion to became famous.
Blogging increases my visibility. I’ve been asked few times for meetings outside of my company. Once it was about creating user group, finally it was created without me, but now I’m with those guys, doing some presentations for the best .NET UG in Ukraine ;). Few other times it were job opportunities but I did not leave my company, hope it was the right decision.
Finally, blogging pays off! Week ago I had performance appraisal and besides of my usual capabilities like result orientation and knowledge, my blog played evident role in how that meeting went. Now I have possibility to be Senior Developer in my company with higher salary, I hope :). But remember that it is not just your blog (aka. public visibility) to lead you to success. It is your hard work and attitude to things you do!
Be directed to your goal and move forward!

[2013-11-21 EDIT: some language corrections]


No comments


Sketching and prototyping with Firefox

July 3, 2010 Prototyping, Tools, UI No comments

I was thinking about what to post and I’ve got nice twits like this one:

@sbohlen I am quite impressed by this http://bit.ly/ci3fxn Its no #balsamiq but its still amazing (and free); runs in and OUT of your browser

So why not to try that thing. So I installed Pencil add-on.

Here is screenshot of my try:

Toolbar on the left is rich of different shape collections. Sadly I did not find one for UML diagrams, but they could be easily added and that is great.

So this is the simplest way to have light prototyping machine just in your browser.


No comments


Few simple mocking scenarios

July 3, 2010 RhinoMocks, TDD, UnitTesting No comments

Are you married? Yeah, quite not usual question for blog post about mocking, but if you are married you probably asked your girl to become your wife.

So you are playing role of PotentialHasband:

    public interface IPotentialHusband
    {
        string
AskForHerHandInMarriage();
    }

and she is PotentialWife, taking your ask into consideration and answering you true or false.

    public interface IPotentialWife
    {
        bool
GiveHimAnswer(string hisSpeech);
    }

If she is Linda, you would need to have “I love you” in your speech to get her agreement:

    public class Linda : IPotentialWife
   
{
        public
bool GiveHimAnswer(string hisSpeech)
 
      {
            return hisSpeech.Contains(“I love you”);
        }
    }
Btw, if your wife is indeed Linda, you just need  put some comments below :)

What we are going to test is to see that after you asked, she will definitely give you at least some answer and not ignore you. Also if her answer is “YES” we would like to see MarriageService called Marry method.

    public class MarriageService
    {
        public virtual void
Marry(IPotentialHusband
almostHusband, IPotentialWife
almostWife)
        {
            Console.WriteLine(“You are now husband and wife!”);
        }
    }

Class which we are going to test is named LearningMocking and has constructor that accepts potential husband/wife and marriageService. Whole story takes place in RestaurantDinner method.

First let’s test that after you asked she gives at least some answer. Since we are not interested in concrete instances we just generate mocks for our interfaces, and passing null instead of marriage service. I’m using RhinoMocks in this example.

        [Test]
        public void EnsureThatAfterHeAskedSheAnswers()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var
potentialWife = MockRepository.GenerateMock<IPotentialWife>();
            var
learningRhino = new LearningMocking(potentialHusband,
potentialWife, null);
           
learningRhino.RestaurantDinner();
            potentialHusband.AssertWasCalled(x
=> x.AskForHerHandInMarriage());
         
  potentialWife.AssertWasCalled(y => y.GiveHimAnswer(Arg<string>.Is.Anything));
     
  }

This ensured that at least she will give you some answer. In next test we will have some mix and will use concrete class Linda. We have generated Stub for return value of your speech, so instead of
writing concrete class for husband we’ve used stub. This test shows that
she will not marry you:

        [Test]
        public void EnsureLindaWillRejectHim()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var
linda = new Linda();
         
  var marriageService = MockRepository.GenerateStub<MarriageService>();
            var
learningRhino = new LearningMocking(potentialHusband,
linda, marriageService);
           
potentialHusband.Stub(x => x.AskForHerHandInMarriage())
                .Return(“Hey lady, would you marry me?”);
           
learningRhino.RestaurantDinner();
            marriageService.AssertWasNotCalled(x
=>
                x.Marry(Arg<IPotentialHusband>.Is.Anything,
Arg<IPotentialWife>.Is.Equal(linda)));
        }

Let’s use another strategy to ask Linda:

        [Test]
        public void GiveHimAnotherTry()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var
linda = new Linda();
         
  var marriageService = MockRepository.GenerateStub<MarriageService>();
            var
learningRhino = new LearningMocking(potentialHusband,
linda, marriageService);
           
potentialHusband.Stub(x => x.AskForHerHandInMarriage())
                .Return(“Linda, I love you, would you marry
me?”
);
   
        learningRhino.RestaurantDinner();
            marriageService.AssertWasCalled(x
=> 
                x.Marry(Arg<IPotentialHusband>.Is.Anything,
Arg<IPotentialWife>.Is.Equal(linda)));
        }

Except of verifying that Marry method was called we also verify that it was called with instance of linda and none else with line Arg<IPotentialWife>.Is.Equal(linda). As well you could setup constructor arguments for MarriageService, since it is not an interface. Also with Rhino.Mocks you will need to have method Marry to be virtual. If it is not virtual and you don’t have interface for it you may need to extend that class with your own.

In the end we’ve got this method:

        public
void RestaurantDinner()
        {
            string wouldYou =
PotentialHusband.AskForHerHandInMarriage();
 
          if(PotentialWife.GiveHimAnswer(wouldYou))
            {
         
      MarriageService.Marry(PotentialHusband, PotentialWife);
            }
        }

Nice picture:

Please write down if you would like to see more complex mocking examples.


No comments


Book Review: The Goal: A Process of Ongoing Improvement

July 2, 2010 Book Reviews, Success No comments

Last weekend I had a chance to read very interesting book, kind of business novel. I was given this book by my managers after we finished with my performance appraisal. Which (btw) went very well.

Book talks about guy, who manages plant where he encounter problem of going behind the schedule and his bosses wanted to close out his plant. But he with colleges, using Theory of Constraints and sophisticated thinking, was able to get plant to the new level.

From first pages I was not sure if book is kind of my thing, since I usually don’t read novels,  but it turns out that book is only a bit hard going at the beginning. From page to page it was more gripping to read and in the end it just became a real page-turner.

Book forces us to think that everything is possible, you just need to take a look for wider solutions without using any of your stereotypes. Book never gives you ready answers, so it is thought-provoking one. First it states the problem, describing it in details, after that main hero is bombarded with different questions by friends, which provoke us think in pair with him.

Reading book was really-really enjoyable and I would highly recommend it for your reading. Book indeed is exciting for those who are interested in career development and in manager’s positions.

P.S. I’ve changed this post a bit to use more specific words like: interesting, exciting, thought-provoking, a real page-turner, gripping, kind of my thing, hard going at the beginning, gripping. That was English course activity to have review on some book. I’m lazy to write new one.



No comments


Memento

July 2, 2010 Design Patterns 2 comments

If you ever played any shooter game, you probably know what do hot-keys F5 & F9 mean. If you did not play those anyway you should be aware of usefulness of quick-save/quick-load functionality. By pressing F5 you save your current location your health/armor levels and maybe some other information, like how many monsters did you kill already. This defines your state which is going to be saved. On pressing F9 you return to your previous saved state (kind of undo operation).

When you are saving your state you don’t wanna it to be accessible by other classes (encapsulation of state), so you will be sure that none will decrease you health level. Also you wanna keep track of savings and maybe you are going to add functionality that will get back through two-three saves by pressing Shift+F9 (+F9).

How can you accomplish this?

MEMENTO

Memento pattern is used when you want do undo operations without exposing internal state of the Originator (Game). Coordination of operations is done by Caretaker, or something that simply lists mementos and therefore remembers states without knowing what are they.

Let’s take a look at implementation:

Originator (Game)

public
class
GameOriginator {
    private
GameState _state = new GameState(100, 0);//Health & Killed Monsters


    public void Play(){
        //During
this Play method game’s state is continuously changed

        System.out.print(_state.toString());
        _state = new GameState((int) (_state.Health
* 0.9),
_state.KilledMonsters + 2);
    }

    public
GameMemento gameSave(){
        return
new
GameMemento(_state);
    }

    public void loadGame(GameMemento memento){
        _state = memento.getState();
    }

    public class
GameMemento {
        private
final
GameState _state;
       
        private GameMemento(GameState state) {
            _state = state;
        }

        private GameState getState(){
            return
_state;
        }
    }
}

So it is able to generate memento instance with current game state, as well it is able to get state from existing memento, BUT none else could get that state, since GameMemento is inner class of Game and methods are private.

Caretaker

Or the guy, who keeps track of your F5/F9th. Currently it is able to load the latest one quick save, but it could be easily enhanced.

public
class
Caretaker {
    private
GameOriginator _game;
    private
Stack<GameOriginator.GameMemento> _quickSaves = new Stack<GameOriginator.GameMemento>();

    public
Caretaker() {
        _game = new
GameOriginator();
    }

    public void
shootThatDumbAss(){
        _game.Play();
    }

    public void F5(){
        _quickSaves.push(_game.gameSave());
    }
   
    public void F9(){
        _game.loadGame(_quickSaves.peek());
    }
}

Output

With following usage code:

        Caretaker caretaker = new
Caretaker();
        caretaker.F5();
        caretaker.shootThatDumbAss();

        caretaker.F5();

        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();

        caretaker.F9();

        caretaker.shootThatDumbAss();

our application generates:

Health: 100
Killed Monsters: 0
Health: 90
Killed Monsters: 2
Health: 81
Killed Monsters: 4
Health: 72
Killed Monsters: 6
Health: 64
Killed Monsters: 8
Health: 90
Killed Monsters: 2

Here is quick UML, that I drew for my example:

My
Design Patterns Table


2 comments


How I taught my sister to accumulate some money

June 27, 2010 InfluenceOnPeople, Personal No comments

Yesterday I’ve been in parents home and I had conversation with my youngest sister. I have two of them. She was complaining about her MP3 player, she said that I have much better one and her is completely out of battery and she could not listen to music even longer than hour. Also she continued saying that it was cheap player and that is the reason why it is useless.

She always gets some money from me. I do not say that give her much money. Sometimes 20, sometimes 50, rarely 100 (those are Ukrainian hryvnias). And I do not like how she spends it, so I’ve decided to have a test with her. I asked her following: “How much money do you have now?” “60 hryvnia” – she said. Then I asked how she wants to spend them. She said that she wants roller-skates. Ok, then I followed with questions that brought to her mind and if she will not spend money this month she will get 120 next month or much more. Finally we went to the 1400 next year, but ONLY if she will not spend them on different useless things and if she will not buy rollers. She admitted that if she will stop spending money on crap she will get “rich” in her understanding .

After that I asked question: “Decide now, you either give me your 60 hryvnias and my MP3 is yours, or either you keep them for future!” She tried to avoid direct answer, but I gave her firm offer. Finally she came to me and said, that she will keep money. I praised her and with words “Keep in mind that sometimes right decisions bring your much more than you expect” I gifted her with MP3.

She was so surprised and with shining face ran to my parents saying that she gained MP3 and that is because she is smart girl. I’m sure that if we had no have that conversation before she most likely chose MP3 instead of keeping money.

I think this is simple example how you could show others that some things are good. So you basically change her mind, then you examine her and if she admits your ideas praise her (This will happen most likely, because now she thinks that this is part of her thoughts). In this way you will keep lesson in her mind for some evident time.

P/S Why have I posted this? With my future career growth I will have to be good on managing people. That is why time-to-time you will see such blog posts. But be calm, my blog is still tech blog unless I’m manager.


No comments


Resharper: Suspend – Resume

June 25, 2010 Resharper No comments

Sometimes when you have few huge solutions opened performance of your PC is very critical and having Resharper over that is notable.

For our good luck with new versions of Resharper you could suspend it easily:

But going into menu is boring thing, so I think you would prefer to setup few hotkeys for that.

Basicly you will need to map Resharper_Suspend and/or Resharper_Resume. I bound those to “Ctrl+R, Ctrl+S” for Suspend and “Ctrl+R, Ctrl+R” for Resume.

Also, as I found over internet, JetBrains promise to have 5.1 being faster and without performance issues, but did not found any official words about this, just twits.

Personally I use Resharper Nightly Builds and enjoy them very much.

Hope this helps.


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


AppDomain.UnhandledException and Application.ThreadException events

May 19, 2010 .NET, Concurrency, Fun No comments

Today I was playing with exception handling and threading in .NET. It was really fun.

Do you know guys that like to have everything in global try-catch block? I have two news for them.

Bad one

Exception will not be caught in try-catch block if it was thrown in another thread. Those guys also could think that Application.ThreadException could help them to catch those.

        [STAThread]
        static
void
Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
         
            Application.Run(new Form1());
        }

        static
void
Application_ThreadException(object
sender, System.Threading.ThreadExceptionEventArgs
e)
        {
            MessageBox.Show(“This is
something that I would not recommend you to have in your application.”
);
        }

But indeed this event fires only if exception has been thrown as result of Windows message or any other code that runs in same thread were your WinForms application lives. I tried to use two timers to verify that.
System.Windows.Forms.Timer – which ensures that code you have in your tick method runs in the same thread as your application. In this case I got message box.
System.Threading.Timer – which runs in separate thread, so my app just crashed.

But if those guys are writing all code in Form1.cs file… then maybe it worth for them to have handling of Application.ThreadException event :)

“Good” one

There is event which will be fired when exception is thrown from any code/thread withing your application domain. It is AppDomain.UnhandledException and it occurs when exception is not caught.

Lets take a look on code snippet that shows this:

        [STAThread]
        static
void
Main()
        {
            AppDomain currentDomain =
AppDomain.CurrentDomain;
            currentDomain.UnhandledException +=
currentDomain_UnhandledException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
         
            Application.Run(new Form1());
        }

        static
void
currentDomain_UnhandledException(object
sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(“This is
shown when ANY thread is thrown in ANY point of your Domain.”
);
        }

To test this I created Threading.Timer and fired it every 2 seconds and throwing exception on each tick, I put breakpoint into event. I got everything expected and application after that failed.

But one of our smart guys could guess to put Thread.Sleep(1000000); into handler code like below:

        static void currentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
        {
            Thread.Sleep(1000000); //
Try to guess what will happen

        }

Everyone is happy. Exception is thrown each 2 seconds or less and UI continue to respond. I hope you already see what is wrong with all of this.

This screenshot talks for itself:

 (My app already ate 705 threads and still eats…)

And as you know process could have up to 1024 threads. My process is not exclusion and it also crashed after reached that number.

Ok, looks like guys should change their mind.

Hope it was a bit fun.


No comments


Few threading performance tips I’ve learnt in recent time

May 16, 2010 .NET, Concurrency, MasterDiploma, Performance 4 comments

In recent time I was interacted with multithreading in .NET.
One of the intersting aspects of it is performance. Most of books says that we should not overplay with performance, because we could introduce ugly-super-not-catching bug. But since I’m using multithreading for my educational purposes I allow myself play with this.

Here is some list of performance tips that I’ve used:

1. UnsafeQueueUserWorkItem is faster than QueueUserWorkItem

Difference is in verification of Security Privileges. Unsafe version doesn’t care about privileges of calling code and runs everything in its own privileges scope.

2. Ensure that you don’t have redundant logic for scheduling your threads.

In my algorithm I have dozen of iterations on each of them I perform calculations on long list. So in order to make this paralleled I was dividing this list like [a|b|c|…]. My problem was in recalculating bounds on each iteration, but since list is always of the same size I could have calculating bounds once. So just ensure that don’t have such crap in your code.

3. Do not pass huge objects into your workers.

If you are using delegate ParameterizedThreadStart and pass lot of information with your param object it could decrease your performance. Slightly, but could. To avoid this you could put such information into some fields of the object that contains method for threading.

4. Ensure that you main thread is also busy guy!

I had this piece of code:

    for
(int i = 0; i < GridGroups;
i++)
    {
        ThreadPool.UnsafeQueueUserWorkItem(AsynchronousFindBestMatchingNeuron,
i);
    }
    for (int i = 0; i < GridGroups;
i++) DoneEvents[i].WaitOne();

Do you see where I have performance gap? Answer is in utilizing my main thread. Currently it is only scheduling some number of threads (GridGroups) to do some work and than it waits for them to accomplish. If we divide work to approximately equivalent partitions, we could gave some work to our main thread, and in this way waiting time will be eliminated.
Following code gives us persormance increase:

    for
(int i = 1; i < GridGroups;
i++)
    {
        ThreadPool.UnsafeQueueUserWorkItem(AsynchronousFindBestMatchingNeuron,
i);
    }
    AsynchronousFindBestMatchingNeuron(0);
    for (int i = 1; i < GridGroups;
i++) DoneEvents[i].WaitOne();

5. ThreadPool and .NET Framework 4.0

Guys, from Microsoft improved performance of the ThreadPool significantly! I just changed target framework of my project to the .Net 4.0 and for worst cases in my app got 1.5x time improvement.

What’s next?

Looking forward that I also could create more sophisticated synchronization with Monitor.Pulse() and Monitor.WaitOne().

Good Threading Reference

Btw: I read this quick book Threading in C#. It is very good reference if you would like to remind threading in C# and to find some good tips on sync approaches.

P.S. If someone is interested if I woke up at 8am. (See my previous post). I need to say that I failed that attempt. I woke at 12pm.


4 comments