Pages

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();
                      

Monday, October 8, 2012

Ways to Make Top Performers Effective Managers


It's a common scenario: A managerial position becomes available and is filled by a top performer with minimal or no previous management experience. Yet it makes sense. Shouldn't a top performer be able to easily make the transition to manager? Shouldn't that person be able to guide others to his or her same level of productivity? The answer is a 100 percent, absolute maybe.
While top performers likely have solid domain skills, coupled with a strong motivation to succeed, there's a good chance they have not been afforded sufficient opportunity to develop effective management techniques. For some, these skills can be learned on the job. For others, the consequences of a poor managerial fit can be significant in terms of lost productivity and morale for the new manager and his or her direct reports.
Therefore, prior to promoting a top performer with minimal or no managerial experience, assess the candidate's strengths and forward-looking potential in nine core areas of effective management.
This analysis can ensure consistently smooth management transitions and keep a company operating at peak performance as it identifies whether a top performer is ready to lead now, is better-suited for some limited managerial experiences and additional training, or perhaps has a skill set and disposition that will only thrive in an individual contributor role. Consider: Can the new manager execute these nine core skills?

1. Move from tactical to strategic.
Is the employee ready to let go of his or her day-to-day responsibilities and play a more conceptual or strategic role? Some managers believe they need to understand every last detail of what their employees are working on.
Commonly referred to as "micro-managing," this type of behavior can make otherwise content employees burn out and leave a company. For a top performer who excels at the tactical level, managing others to achieve the same level of success may not seem as fulfilling.
Is the employee prepared for this potential shock? Many top performers are capable of the transition from tactical to strategic thinking, provided they have access to the right resources, such as a mentor or applicable management training courses.

2. Defend the team.
Is the employee ready to defend his or her new direct reports and support them in public? Is the employee ready to be a leader? Leaders absorb rather than deflect criticism. Leaders push praise downward to their employees and proactively look for ways to portray their direct reports in a positive light.
In short, leaders have a deep understanding of the phrase, "praise in public, condemn in private." Lots of top performers have healthy, competitive egos. Don't assume that deflecting praise and supporting direct reports is a natural instinct for new managers.

3. Build trusting relationships.
Can the employee develop a strong, trusting relationship that engenders compassion and prudent responses to change? As a cautionary tale, "Jerry" really enjoyed working for a manager until the reasons behind some recent absences came into question.
Jerry's son was in and out of the hospital, and thus, he needed to unexpectedly miss some work during a two-week period. Rather than show compassion and understanding, Jerry's manager accused him of interviewing. The manager's paranoia quickly became a self-fulfilling prophecy, as Jerry decided it wasn't worth working for someone who so quickly questioned his integrity. Jerry's example illustrates the risk associated with promoting a top performer before understanding his or her ability to trust and respect others.

4. Delegate.
Does the employee know how to assign work and shepherd that work through to completion? Consider the following scenario:
Manager: "[Employee], I need you to do X. I need this done because of Y. I'd really like to have this work completed by Z. Do you have any questions? Was this clear?"
Employee: "Got it."
Manager: "Great. Please let me know if you need any additional help."
This seems simple. Employees like to understand what work is expected of them, why the work is important, and when the work should be completed. Once the assignment is given, managers can use a variety of actions to stay on top of progress, including daily check-ins, one-on-one meetings and regular staff meetings. This example is deceptively easy; yet, in the frantic pace of business, this type of clear, concise, two-way communication often is lost.

5. Teach and mentor.
In the event that assignments require additional help or instruction, does the top performer embrace the idea of teaching and mentoring? Does he or she have the patience to answer employees' questions respectfully, in detail, more than once? Managers who return employee questions with an impatient or arrogant tone will eventually find they have fewer questions to answer, as employees will be more reluctant to expose their weaknesses or challenge ideas.
Managers who answer employee questions in an unassuming, non-condescending manner will be able to foster and sustain open communication channels that are vital for employee development and team productivity.

6. Admit mistakes.
Does the employee know how to apologize or acknowledge a mistake? For example, a new manager arrogantly corrects an employee in a cross-functional meeting and subsequently learns the employee's assertion was accurate. Does the manager have the self-awareness and willingness to admit the mistake not only to the employee but also to the other meeting participants? This is necessary to help restore cross-functional trust in the employee who the manager publicly and erroneously contradicted. These corrective steps will be appreciated by most employees. On the other hand, if the manager doesn't take these steps, he or she will quickly lose the team's respect.

7. Leverage others' strengths.
Is the employee threatened by colleagues who have greater subject matter expertise? For a newly promoted manager, there is an increased likelihood that certain employees will know more about a specific domain. For example, a new vice president of brand marketing may be asked to manage the product marketing group, as well. Is this vice president willing to roll up his or her sleeves and learn about that group on a tactical level?
Rather than hide from knowledge they don't have, the best managers ask the right questions to understand their employees' day-to-day responsibilities. By doing so, effective managers can engage subject matter experts to provide a well-articulated recommendation and then implement, adjust or reject that proposal based upon their sense of how it fits into the broader company strategy.

8. Manage each employee.
Can the new manager alter his or her managerial approach by direct report? Does the prospective manager have a one-size-fits-all management style, or does he or she recognize that individuals may need to be managed differently? Employees with young children are likely to request time to attend school events or unexpectedly miss work due to a child's illness.
Younger, single employees may be hungry to prove themselves by offering to own too much work. Can the potential manager recognize the employees' motivational differences and alter his or her managerial style accordingly? The best managers hold everyone on the team accountable for expected behaviors and results, while also understanding and capitalizing on the individual motivations of each team member.

9. Take time to manage.
Has the company given the new manager the time needed to actually manage? If a top performer has moved from individual contributor to managing a group of five or seven people, for example, there is undoubtedly a need to scale back on tactical, role-based activities to find the pulse of his or her new team.
A managerial role requires building a rapport, delegating responsibilities and architecting a team's broader long-term strategy. When promoted, many top performers will initially carve out more work time per day to ambitiously try to handle their legacy tasks and their newly acquired role. This early push is not sustainable. The new manager, and the company, will need to understand and be receptive to the fact that his or her individual responsibilities should now account for no more than 50 percent of work time, and likely much less.
Each of these nine components of effective management requires organization commitment and an adjustment period in order to achieve a smooth transition, best fit and continued productivity for new managers and their employees. However, there often is more accountability for the organization regarding this ninth and final point.
Are top performers expected to manage effectively and maintain their previous workloads? Or are they given the time they need to manage their new direct reports? Providing employees with a manager's title without supplying enough time for them to actually manage is a fruitless exercise.

The Case for Careful Selection
There are potential consequences of not incorporating these nine dimensions into the managerial selection process. Ineffective managers can alienate other departments, or worse, their employees, which can lead to significantly reduced group productivity and increased attrition. As merit budgets tighten and companies try to do more with less, the cascading effects of a toxic manager pose an even greater threat to organizational success.
Top-performing individuals don't necessarily become top-performing managers. To succeed, new managers require time, training and guidance. Management consultants may never reach full agreement on the components of effective management, but these nine core skills comprise a practical evaluation of a top performer's readiness to manage and a company's readiness to prepare employees for this next step.

Please share your views, comment on this...

Jitendra Singh

Monday, July 4, 2011

Using C# Yield for Readability and Performance

I must have read about "yield" a dozen times. Only recently have I began to understand what it does, and the real power that comes along with it. I’m going to show you some examples of where it can make your code more readable, and potentially more efficient.

To give you a very quick overview of how the yield functionality works, I first want to show you an example without it. The following code is simple, yet it’s a common pattern in the latest project I’m working on.

1.  IList<string> FindBobs(IEnumerable<string> names)  

2.  {  

3.      var bobs = new List<string>();  

4.    

5.      foreach(var currName in names)  

6.      {  

7.          if(currName == "Bob")  

8.              bobs.Add(currName);  

9.      }  

10.   

11.     return bobs;  

12. }  

Notice that I take in an IEnumerable<string>, and return an IList<string>. My general rule of thumb has been to be as lenient as possible with my input, and as strict as possible with my output. For the input, it clearly makes sense to use IEnumerable if you’re just going to be looping through it with a foreach. For the output, I try to use an interface so that the implementation can be changed. However, I chose to return the list because the caller may be able to take advantage of the fact that I already went through the work of making it a list.

The problem is, my design isn’t chainable, and it’s creating lists all over the place. In reality, this probably doesn’t add up to much, but it’s there nonetheless.

Now, let’s take a look at the "yield" way of doing it, and then I’ll explain how and why it works:

1.  IEnumerable<string> FindBobs(IEnumerable<string> names)  

2.  {  

3.      foreach(var currName in names)  

4.      {  

5.          if(currName == "Bob")  

6.              yield return currName;  

7.      }  

8.  }  

In this version, we have changed the return type to IEnumerable<string>, and we’re using "yield return". Notice that I’m no longer creating a list. What’s happening is a little confusing, but I promise it’s actually incredibly simple once you understand it.

When you use the "yield return" keyphrase, .NET is wiring up a whole bunch of plumbing code for you, but for now you can pretend it’s magic. When you start to loop in the calling code (not listed here), this function actually gets called over and over again, but each time it resumes execution where it left off.

Typical Implementation

Yield Implementation

  1. Caller calls function
  2. Function executes and returns list
  3. Caller uses list
  1. Caller calls function
  2. Caller requests item
  3. Next item returned
  4. Goto step #2

Although the execution of the yield implementation is a little more complicated, what we end up with is an implementation that "pulls" items one at a time instead of having to build an entire list before returning to the client.

In regards to the syntax, I personally think the yield syntax is simpler, and does a better job conveying what the method is actually doing. Even the fact that I’m returning IEnumerable tells the caller that its only concern should be that it can "foreach" over the return data. The caller can now make their own decisionif they want to put it in a list, possibly at the expense of performance.

In the simple example I provided, you might not see much of an advantage. However, you’ll avoid unnecessary work when the caller can "short-circuit" or cancel looping through all of the items that the function will provide. When you start chaining methods using this technique together, this becomes more likely, and the amount of work saved can possibly multiply.

One of my first reservations with using yield was that there is a potential performance implication. Since c# is keeping track of what is going on in what is essentially a state machine, there is a bit of overhead. Unfortunately, I can’t find any information that demonstrates the performance impact. I do think that the potential advantages I mentioned should outweigh the overhead concerns.

Conclusion

Yield can make your code more efficient and more readable. It’s been around since .NET 2.0, so there’s not much reason to avoid understanding and using it.

Have you been using yield in interesting ways? Have you ever been bitten by using it? Leave a comment and let me know!