Pages

Wednesday, February 20, 2013

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.

 

Tuesday, February 19, 2013

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

AntiPatterns

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.


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.



Attribute
Description
maxConcurrentCalls
Limits the total number of calls that can currently be in progress across all service instances. The default is 16.
maxConcurrentInstances
The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
maxConcurrentSessions
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.
<system.serviceModel>
    <services >
      <service behaviorConfiguration="ServiceBehavior"  name="MyService">
        <endpoint address="" binding="wsHttpBinding" contract="IMyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true "/>
          <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>


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;
                host.Description.Behaviors.Add(throttle);
            }

            host.Open();