Leave a comment

Code Bytes #1 – PLINQ Basics

PLINQ /Parallel LINQ is part of the TPL (Task Parallel Library) and it makes your life easier when it comes to multi-core processor programming which is totally different from multithreading which allows more than one thread per process and you have no idea if they will be equally distributed across CPU cores. To use PLINQ your objects have to be in memory. This means you can’t use AsParallel on LINQ to SQL until you bring all your query results over to the local machine. When it comes to running your code in parallel the key to remember is that the AsParallel method is you friend. Every result that gets returned after your first call to AsParallel is always a ParallelQuery object. You can get more theory here. Now go code!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace OliverCode.CodeBytes
{
    class ParallelLinqCB
    {
        static void Main(string[] args)
        {
            Action action = (int itemFromList) => Console.Write(itemFromList + ",");
            var lst = Enumerable.Range(1, 10);

             //PLINQ will decide on the number of processors to use in this run up to 64 threads (if you have that much)
             lst.AsParallel().Select(i => i * i).ForAll(action);
            Console.WriteLine();
            //My machine has 4 cores but i only need it to use up to 2 cores so I use the WithDegreeOfParallelism to restrict it
            //Or I could have use all 4 with the statement WithDegreeOfParallelism(4) hereby not letting PLINQ choose for me
            lst.AsParallel().WithDegreeOfParallelism(2).ForAll(action);

            Console.Read();
        }
    }
}

Cropped diagram courtesy of MSDN PFX (Parallel Programming Framework)
Code Bytes 1 - PLINQ

3 Comments

Dynamic Programming in C# 4.0 – An Overview

One of the most interesting additions to C# 4.0, I think, is the dynamic addition. Just thinking about this makes me excited. I will jump right into a little theory then some code.

The Theory of Dynamic

So what is this here dynamic thingy? dynamic in C# 4.0 refers to dynamic binding and dynamic binding is what happens at runtime and not at compile time. This involves binding a method, property, operator, member etc of an object at runtime. Yes I know this sounds like polymorphism or like the var keyword or even like using the ultimate base class in C# – object. First and foremost you have to let go or what you know and remember this important fact.

dynamic != var && dynamic != object

The keyword dynamic, casually speaking, tells the compiler that “Even though it cannot resolve the member statically, it should trust the programmer and don’t worry because it will/may be resolved at runtime.”

Code

Here is a sample on how you use the dynamic keyword:

dynamic dyn = “My first time”;
Console.WriteLine(dyn);

Now let’s look at some similarities and differences of var, object, and dynamic for a sec.

var v = 1; // here the compiler will figure out (at compile time) the type for v which will be int.
Console.WriteLine(v.GetType().ToString());
//v.Compute(); // causes a compiler error
object o = 1; // this is boxed from value type to an object with type being int32
Console.WriteLine(o.GetType().ToString());
//o.Compute(); //also gives a compiler error
dynamic d = 1; //type here is int32
Console.WriteLine(d.GetType().ToString());
d.Compute(); // does not give compile time error but will throw a runtime RuntimeBinderException

Continue Reading »

6 Comments

MVVM (Model View View-Model) For Dummies/Simplified

Introduction

A few months ago I took the leap from WinForms programming to WPF and quite naturally, I took to it like a duck to water. Well, to be honest I had been developing Silverlight applications since its inception and being that Silverlight is a subset of WPF it required a low learning curve to catch on. However, the concept of Commanding was a bit different in WPF and I soon began to see how much more powerful Commanding in WPF was compared to Silverlight.

One of the areas in which Commanding is exemplary is in the way in which it complements MVVM.  But what is MVVM, and why is it useful? This is the toughest concept (In my opinion) to grasp when it comes to WPF (and Silverlight) programming. Why you ask? Because it is simple and as developers we often like code or concepts that warp our minds, so when we figure it out we can brag to our peers how it only took 2 hours to understand and implement the next BIG thing (No I am not projecting).  On a side not, I have found that everyone one who blogs about MVVM complicate it by adding too much code which just throws you for a loop. Simplicity is the key to all things complicated. So let’s delve into a little theory and we will finish up with some short-to-the-point code.

Purpose

The purpose of this post is to

a. Give a simple and clear definition of Model View View-Model

b. Provide a clear and simple sample that clearly illustrates MVVM usage

MVVM?

Figure 1.

MVVM - Model View ViewModel

MVVM - Model View ViewModel

Just in case you cannot read the text in the image here it is below:

  1. The View holds a reference to the ViewModel. The View basically displays stuff by Binding to entities in the View Model.
  2. The ViewModel exposes Commands, Notifiable Properties, and Observable Collections to the View. The View Binds to these ViewModel entities/members
  3. The Model is your data and or application objects that move data while applying Application Logic. If you have a Business Layer then you might not need this.

Above is a simple figure that tells you exactly what MVVM is. In my own words, the ViewModel is the most significant in the entire pattern as it is the glue that sits between the View and the Model and binds both of them together. Now let’s explore some code. Continue Reading »

Leave a comment

Nothing is as powerful as…

Nothing is as powerful as an idea whose time as come – Victor Hugo

Leave a comment

Blogging Again

Now I have some free time and a lot of cool things I want to blog about.  Sorry for the 2 year wait. I promise to make it up by publishing some awesome find. Keep a look out

2 Comments

Visual Studio 2010 RC – Cool New Features


I have been using Visual Studio 2010 Release Candidate and there are few cool things that I am pleasantly surprised about. I have list a few off the top of my head. See my list below – with pictures.

 


Sequence Diagram Generation
I find this to be a life saver. I don’t know about you but as a developer I want to dive right into code after I finish designing. There are times I have to sequence diagrams and this usually comes before you start coding. Now, with the sequence diagram generator in Visual Studio 2010, I can write code then simply generate. This not only saves you time but also lets you better understand your branches in your code that can lead to code complexity or cyclomatic complexity.

Here is the Code that we will work with in this post.

class Animal {
       public virtual void Description() { Console.WriteLine("Lives on earth"); }
    }

    class Bird : Animal {
        public override void Description() { Console.WriteLine("have feathers and a beak"); }
    }

    class Lion : Animal {
        public override void Description()
        {
            Console.WriteLine("roars and have large teeth");
        }
    }

    class Park
    {
        static void Main(string[] args)
        {
            List animalsInPark = new List();
            ShowDescriptions(animalsInPark);
        }

        static void ShowDescriptions(List animals)
        {
            animals.ForEach(animal => animal.Description());
        }
    }

Now right click on ShowDescriptions() and click generate sequence diagram. You should see this dialog.

And wallah – your very own Visual Studio 2010 crafted sequence diagram. I have to admit, I am really starting to like these diagrams

.

Code Window Zoom
Visual Studio 2010 allows you to zoom in and out just as in Internet Explorer. All you have to do is press Ctrl and use your mouse wheel or your equivalent mouse pad scroll to zoom in and out. This may not be so exciting but when it comes to giving presentations, this will make all our lives easier when it comes to changing font size. The beauty about zooming is that the font is crisp and smooth due to the fact that Visual Studio 2010 is built with WPF. Below is an image of me zooming in on the Animal class.

Code Generation
Most of us who use Visual Studio 2008 love the generate method feature. If you don’t know what this is, here is your intro. If you  write a method name and it doesn’t exists, you can right click on the method and tell visual studio to generate the stub and it will do it. No questions ask.

Visual Studio 2010 has taken this further and now you can even do classes. See below for demonstration.



Highlighted Reference
If you select a reference or even click on it, Visual Studio 2010 highlights all of the places it is used in your code.

Navigate To
Pressing Ctrl comma (,) brings up a dialog window that allows you to look for Methods, properties, classes, etc within your solution. It is case insensitive and it searches via partial name.

Click on any of the items found will take you to the line within the file where it is located.

Box Selection
This is one feature that I still have not found a suitable use for. This feature allows you to hold Ctrl + Alt and use either your mouse or arrow keys to select a rectangular area. If you now start typing, you will simultaneously be typing on all lines that you selected. If you happen to find a useful case for it, please let me know.

One thing I forgot to mention is that adding references to a project also seems faster. These are only some of the new features in Visual Studio 2010. Hope you find them as exciting as I do. Now go code!

1 Comment

Snowy Night in NYC

Its one of those nights where all I want to do is watch TV. I wont be publishing any code tonight. But just to let you know, this weekend there is a Software Engineer 101 Webcast this weekend (Feb 27)? If not and you want to add something extra to your arsenal the sign up here.  A sample from the overview is below which is from the Microsoft site in the link. See you there, now go code!

Overview
“This is a one-day, FREE event focused on core skills that modern developers need to have to be successful today.  This isn’t about learning the basics of Silverlight, WPF, or, rather, this conference will help you understand how to build software that is better designed, more maintainable, and more testable. “

Leave a comment

Code Bytes Series Intro

Today while on the F train home from work, I was thinking about how nice it would be to have these short series of code segments called Code Bytes (as Sound Bytes) that get straight to the point with little or no explanation. Yes there will be gaps in your learning if you are new to the topic or technology in the post. But 90% of the time when I stumble upon or search for code samples online, I already know something about what i am looking for. Plus I think this will stimulate more comments and conversation amoung this blog’s users.

Please share your thoughts and check back soon for the first in the series of CB (Code Bytes).

Leave a comment

Threading with the Thread Pool and BackgroundWorker

threadsToday I want to talk about threads since every programmer works with them and absolutely loves them. Typically, when we create a thread, your code can look like this:

static void Main(string[] args)
{
TraditionalThreadCreation();
Console.Read();
}

static void TraditionalThreadCreation()
{
// Create threads
Thread thread1 = new Thread(Task);
Thread thread2 = new Thread(Task);

// this guy will do even numbers
thread1.Start(0);
// this guy will do odd numbers
thread2.Start(1);
//wait for first thread to finish
thread2.Join();
}

static void Task(object p)
{
for (int i = int.Parse(p.ToString()); i <=10; i += 2)
Console.WriteLine(i);
}

There is nothing wrong with creating threads like the code above. But there is one thing you have to keep in mind. Thread creation and startup has overhead. A typical thread can take up 1MB of your precious memory. Shocked?? Well you are not alone. Continue Reading »

2 Comments

WPF Commanding

WPF Commanding: The Basics

Commanding in WPF is unlike your traditional events in Winforms. Commands were primarily designed to be used at the application level, but they have become one of the most popular features among developers when it comes to UI programming (we tend to use them more than they should be). Commands enable the developer to define a task once and “attach” it multiple times without having to go through the traditional means which would require duplicating the code or even calling it in more than one place (This is the magic). WPF intrinsically provides 5 commands that you can use out of the box.

  1. ApplicationCommands
  2. ComponentCommands
  3. EditingCommands
  4. MediaCommands
  5. NavigationCommands

Continue Reading »

Follow

Get every new post delivered to your Inbox.