Sunday, February 24, 2013

Difference between Select and SelectMany in LINQ

The difference between select and selectMany can be seen when we are accessing data from multilevel classes.

Download Sample Code – 2.62 Kb

In the below example we shall see what exactly is the difference while accessing the properties.

When we access some data by using select it gives us the data that is grouped under the parent (i.e gives multiple arrays). To access the output we need to loop twice.

////This code shows how to use Select()             
var Query2 = Builders.Select(Build => Build.Locations);
// Notice that two foreach loops are required to iterate through
// the results because the query returns a collection of arrays.            
foreach (List<String> BuildList in Query2)
        foreach (string builds in BuildList)

But using the same sample when we use select many it gives the selected items in one array(i.e it give the output as it is joining all the output from select command)

// Query using SelectMany().            
var query1 = Builders.SelectMany(Build => Build.Locations);
// Only one foreach loop is required to iterate through the
// results because it is a one-dimensional collection.
// Select many joins the output of all the sub collections in to one.            
foreach (string Loc in query1)


Tuesday, February 19, 2013

WPF Architecture

For every new technology, it is very essential to have a clear idea about its architecture. So before beginning your application, you must grab a few concepts. If you would not like to know WPF in detail, please skip this section. As mentioned earlier, WPF is actually a set of assemblies that build up the entire framework. These assemblies can be categorized as:
Managed Layer
UnManaged Layer
Core API

Managed Layer: Managed layer of WPF is built using a number of assemblies. These assemblies build up the WPF framework, communicate with lower level unmanaged API to renderits  content. The few assemblies that comprise the WPF framework are:
PresentationFramework.dll: Creates the top level elements like layout panels, controls, windows, styles, etc.

PresentationCore.dll: It holds base types such as UIElement, Visual from which all shapes and controls are Derived in PresentationFramework.dll.

WindowsBase.dll: They hold even more basic elements which are capable of being used outside the WPF environment like Dispatcher object, Dependency Objects. I will discuss each of them later.

Unmanaged Layer (milcore.dll): The unmanaged layer of WPF is called milcore or Media Integration Library Core. It basically translates the WPF higher level objects like layoutpanels,buttons, animation, etc. into textures thatDirect3D expects. It is the main rendering engine of WPF.

WindowsCodecs.dll: This is another low level API which is used for imaging support in WPF applications.WindowsCodecs.dll comprises a number of codecs which encode / decode images into vector graphics that would be rendered into WPF screen.

Direct3D: It is the low level API in which the graphics of WPF is rendered.

User32: It is the primary core API which every program uses. It actually manages memory and process separation.

GDI & Device Drivers: GDI and Device Drivers are specific to the operating system which is also used from the application to access low level APIs.
In the above figure, you can see how different framework elements communicate between one another.

Visual Tree and Logical Tree

Every programming style contains some sort of LogicalTree which comprises the Overall Program. TheLogicalTree comprises the elements as they are listed in XAML. Thus they will only include the controls that you have declared in you XAML.
VisualTree on the other hand, comprises the parts that make up the individual controls. You do not generally need to deal with VisualTree directly, but you should know how each control is comprised of, so it would be easier to build custom templates using this.

Dispatcher & Thread Affinity

When WPF application starts, it actually creates two threads automatically. One is Rendering Thread, which is hidden from the programmer, so you cannot use the rendering thread directly from your program; while the other is Dispatcher Thread, which actually holds all the UI elements. So in other words, you might say Dispatcher is actually the UI thread which ties all the elements created within the WPF application. Conversely, WPF requires all the UI elements to be tied with Dispatcher thread, this is called Thread Affinity. Thus you cannot change any element created on Dispatcher thread from any other threads, thus it follows the same Win32 based APIs. Thus it allows you to inter-operate any WPF component into HWNDbased API. For more, read this. [^]

Dispatcher is a class that handles thread affinity. It is actually a prioritized message loop through which all elements are channeled through. Every UIElement is derived from DispatcherObject which defines a property called Dispatcher which points to the UI thread. Thus from any other thread, if you want to invoke or access UI component, you need to Invoke using Dispatcher thread. DispatcherObjectactually has two chief duties, to check and verify if the thread has access to the object.


Routed Events in WPF / Silverlight

Routed events are events which navigate up or down the visual tree acording to their RoutingStrategy. The routing strategy can be bubble, tunnel or direct. You can hook up event handlers on the element that raises the event or also on other elements above or below it by using the attached event syntax: Button.Click="Button_Click".
Routed events normally appear as pair. The first is a tunneling event called PreviewMouseDown and the second is the bubbling called MouseDown. They don't stop routing if the reach an event handler. To stop routing then you have to set e.Handled = true;
  • Tunneling The event is raised on the root element and navigates down to the visual tree until it reaches the source element or until the tunneling is stopped by marking the event as handeld. By naming convention it is called Preview... and appears before corresponding bubbling event.
  • Bubbling The event is raised on the source element and navigates up to the visual tree until it reaches the root element or until the bubbling is stopped by marking the event as handled. The bubbling event is raised after the tunneling event.
  • Direct The event is raised on the source element and must be handled on the source element itself. This behavior is the same as normal .NET events.
Create a Custom Routed Event
// Register routed event
public static readonly RoutedEvent SelectedEvent = 
    EventManager.RegisterRoutedEvent( "Selected", RoutingStrategy.Bubble, 
    typeof(RoutedEventHandler), typeof(MyCustomControl));
// .NET wrapper
public event RoutedEventHandler Selected
    add { AddHandler(SelectedEvent, value); } 
    remove { RemoveHandler(SelectedEvent, value); }
// Raise the routed event "selected"
RaiseEvent(new RoutedEventArgs(MyCustomControl.SelectedEvent));


Thursday, February 14, 2013


What Is an AntiPattern?
AntiPatterns, like their design pattern counterparts, define an industry vocabulary for the common defective processes and implementations within organizations. A higher-level vocabulary simplifies communication between software practitioners and enables concise description of higher-level concepts.
An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences. The AntiPattern may be the result of a manager or developer not knowing any better, not having sufficient knowledge or experience in solving a particular type of problem, or having applied a perfectly good pattern in the wrong context.
AntiPatterns provide real-world experience in recognizing recurring problems in the software industry and provide a detailed remedy for the most common predicaments. AntiPatterns highlight the most common problems that face the software industry and provide the tools to enable you to recognize these problems and to determine their underlying causes.
Furthermore, AntiPatterns present a detailed plan for reversing these underlying causes and implementing productive solutions. AntiPatterns effectively describe the measures that can be taken at several levels to improve the developing of applications, the designing of software systems, and the effective management of software projects.

Software Development AntiPatterns
A key goal of development AntiPatterns is to describe useful forms of software refactoring. Software refactoring is a form of code modification, used to improve the software structure in support of subsequent extension and long-term maintenance. In most cases, the goal is to transform code without impacting correctness.

Software Architecture AntiPatterns
Architecture AntiPatterns focus on the system-level and enterprise-level structure of applications and components. Although the engineering discipline of software architecture is relatively immature, what has been determined repeatedly by software research and experience is the overarching importance of architecture in software development.

Software Project Management AntiPatterns
In the modern engineering profession, more than half of the job involves human communication and resolving people issues. The management AntiPatterns identify some of the key scenarios in which these issues are destructive to software processes.

Tuesday, February 12, 2013

LINQ GroupBy Count

class Program


        static void Main(string[] args)


            var employeeProducts = new List<EmployeeProduct>();

            employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));

            employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));

            employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));


            var way1 = employeeProducts.Select(

                ep => new ProductCount


                    ProductNumber = ep.ProductID,

                    EmployeeNumber = ep.EmployeeID,

                    CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)



            var way2 = employeeProducts

                .GroupBy(ep => ep.ProductID)

                .SelectMany(epg => epg.Select(

                    ep => new ProductCount


                        ProductNumber = ep.ProductID,

                        EmployeeNumber = ep.EmployeeID,

                        CountProducts = epg.Count()




        public class EmployeeProduct


            public EmployeeProduct(int employeeID, int productID, string name)


                EmployeeID = employeeID;

                ProductID = productID;

                Name = name;



            public int EmployeeID { get; set; }

            public int ProductID { get; set; }

            public string Name { get; set; }



        public class ProductCount


            public int ProductNumber { get; set; }

            public int EmployeeNumber { get; set; }

            public int CountProducts { get; set; }



Types of WCF concurrency

WCF concurrency helps us configure how WCF service instances can serve multiple requests at the same time. You will need WCF concurrency for the below prime reasons; there can be other reasons as well but these stand out as important reasons:
  • Increase throughput: Many times you want to increase the amount of work your WCF service instance does at any moment of time. In other words, you would like to increase the throughput. Throughput means how much work a given thing can do.
  • By default, a WCF service handles only one request at a given moment of time.
  • Integration with a legacy system: Many times your WCF services interact with legacy systems like VB6, COM, etc. It’s very much possible that these systems are not multithreaded, in other words they handle only one request at any given time. So even though your WCF service has concurrent capabilities, you would still like to handle one request at a time. This is achieved by using throttling in combination with WCF concurrency capabilities.

There are three ways by which you can handle concurrency in WCF: single, multiple, and reentrant. To specify WCF concurrency, we need to use the ServiceBehavior tag as shown below, with the appropriate ‘ConCurrencyMode’ property value.
Single: A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is completed.
Multiple: In this scenario, multiple requests can be handled by the WCF service object at any given moment of time. In other words, requests are processed at the same time by spawning multiple threads on the WCF server object. So you have great throughput here but you need to ensure concurrency issues related to WCF server objects.
Reentrant: A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.

Monday, February 11, 2013

WCF Service Throttling

WCF Throttling provide provision to set Limit for number of  concurrent call, number of  instances and number of session is created by the application.
Performance can be improve by setting these properties according to the application uses.

Limits the total number of calls that can currently be in progress across all service instances. The default is 16.
The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.
Service Throttling can be configured either by service configuration file or Programmatically.

configuration file

Using <serviceThrottling> tag of the Service Behavior, you can configure the maxConcurrentCallsmaxConcurrentInstances ,maxConcurrentSessions property as shown below.
    <services >
      <service behaviorConfiguration="ServiceBehavior"  name="MyService">
        <endpoint address="" binding="wsHttpBinding" contract="IMyService">
            <dns value="localhost"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true "/>
          <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/>

Programming Model
Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property.
           ServiceHost host = new ServiceHost(typeof(MyService));
           ServiceThrottlingBehavior throttle  = host.Description.Behaviors.Find();
            if (throttle == null)            {
                throttle = new ServiceThrottlingBehavior();
                throttle.MaxConcurrentCalls = 500;
                throttle.MaxConcurrentSessions = 200;
                throttle.MaxConcurrentInstances = 100;