February 13, 2014

Lazy Loading Vs Eager Loading in LINQ

In Entity Framework, we have two types of loading available. Lazy Loading and Eager Loading. Both types of loading is related to database hits in an application that can effect the performance of application. 

In Lazy Loading, we load the parent table data only.

In Eager Loading, when we load the parent table data, at the same time we also get the data from its related table (child table).

Let's start with an example:

int[] listOfNumbers = new int[] { 5, 9, 8, 1, 7, 3, 6, 4, 2, 0 }; 
       int i = 0;
       var query = from num in listOfNumbers select ++i;
       // Note, the local variable 'i' is not incremented until each element is evaluated (as a side-effect):
       foreach (var x in query)
       {
           Console.WriteLine("x = {0}, i = {1}", x, i);
       }
Now without deferred execution we would expect that after the variable “query” is declared, “i” would have the value 10 and the output would be: “x = {1-10}, i = 10”  However since the LINQ statement is lazy loaded, the “++i” is not evaluated until each element is requested by the for each loop. Thus, the output instead is: 
x = 1, i = 1
x = 2, i = 2
x = 3, i = 3
x = 4, i = 4
x = 5, i = 5
x = 6, i = 6
x = 7, i = 7
x = 8, i = 8
x = 9, i = 9
x = 10, i = 10
Eager Loading :
int[] listOfNumbers new int[] { 5, 9, 8, 1, 7, 3, 6, 4, 2, 0 };
        int i = 0;
        var query = (from num in listOfNumbers select ++i).ToList();
        foreach (var x in query)
        {
            Console.WriteLine("x = {0}, i = {1}", v, i);
 }
 Output:
v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10

As we can see, with eager loading “++i” is evaluated during the declaration of “query” and “i” is equal to 10 for the entire duration of the output.

Display Row Values In Columns In SQL Server 2008

There are several ways that you can transform data from multiple rows into columns. 

1. In SQL Server you can use the PIVOT function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

2. If you don't want to use the PIVOT function, then you can use an aggregate function with a CASE expression.
select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See SQL Fiddle with Demo.

3. If you have an unknown number of column names that you want to transpose, then you can use the Dynamic SQL using PIVOT.
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + ')
            ) p '

execute(@query)
Hope these options will help you out. Let me know if any query remains.

Cheers

February 6, 2014

6 Habits of True Strategic Thinkers

In the beginning, there was just you and your partners. You did every job. You coded, you met with investors, you emptied the trash and phoned in the midnight pizza. Now you have others to do all that and it's time for you to "be strategic." Whatever that means.

If you find yourself resisting "being strategic," because it sounds like a fast track to irrelevance, or vaguely like an excuse to slack off, you're not alone. Every leader's temptation is to deal with what's directly in front, because it always seems more urgent and concrete. Unfortunately, if you do that, you put your company at risk. While you concentrate on steering around potholes, you'll miss windfall opportunities, not to mention any signals that the road you're on is leading off a cliff.

This is a tough job, make no mistake. "We need strategic leaders!" is a pretty constant refrain at every company, large and small. One reason the job is so tough: no one really understands what it entails. It's hard to be a strategic leader if you don't know what strategic leaders are supposed to do.
After two decades of advising organizations large and small, my colleagues and I have formed a clear idea of what's required of you in this role. Adaptive strategic leaders — the kind who thrive in today's uncertain environment – do six things well:

Anticipate 

Most of the focus at most companies is on what's directly ahead. The leaders lack "peripheral vision." This can leave your company vulnerable to rivals who detect and act on ambiguous signals. To anticipate well, you must:
  • Look for game-changing information at the periphery of your industry
  • Search beyond the current boundaries of your business
  • Build wide external networks to help you scan the horizon better

Think Critically

"Conventional wisdom" opens you to fewer raised eyebrows and second guessing. But if you swallow every management fad, herd like belief, and safe opinion at face value, your company loses all competitive advantage. Critical thinkers question everything. To master this skill you must force yourself to:
  1. Re-frame problems to get to the bottom of things, in terms of root causes
  2. Challenge current beliefs and mindsets, including your own
  3. Uncover hypocrisy, manipulation, and bias in organizational decisions

Interpret 

Ambiguity is unsettling. Faced with it, the temptation is to reach for a fast (and potentially wrongheaded) solution.  A good strategic leader holds steady, synthesizing information from many sources before developing a viewpoint. To get good at this, you have to:
  • Seek patterns in multiple sources of data
  • Encourage others to do the same
  • Question prevailing assumptions and test multiple hypotheses simultaneously

Decide

Many leaders fall prey to "analysis paralysis." You have to develop processes and enforce them, so that you arrive at a "good enough" position. To do that well, you have to:
  • Carefully frame the decision to get to the crux of the matter
  • Balance speed, rigor, quality and agility. Leave perfection to higher powers
  • Take a stand even with incomplete information and amid diverse views

Align

Total consensus is rare. A strategic leader must foster open dialogue, build trust and engage key stakeholders, especially when views diverge.  To pull that off, you need to:
  • Understand what drives other people's agendas, including what remains hidden
  • Bring tough issues to the surface, even when it's uncomfortable
  • Assess risk tolerance and follow through to build the necessary support

Learn

As your company grows, honest feedback is harder and harder to come by.  You have to do what you can to keep it coming. This is crucial because success and failure--especially failure--are valuable sources of organizational learning.  Here's what you need to do:
  • Encourage and exemplify honest, rigorous debriefs to extract lessons
  • Shift course quickly if you realize you're off track
  • Celebrate both success and (well-intentioned) failures that provide insight

Do you have what it takes?

Obviously, this is a daunting list of tasks, and frankly, no one is born a black belt in all these different skills. But they can be taught and whatever gaps exist in your skill set can be filled in.Let me know what you learned from it.
  
Paul J. H. Schoemaker: Founder and Chairman, Decision Strategies Intl. Speaker, professor, and entrepreneur. Research Director, 

February 1, 2014

8 Qualities of Remarkable Employees

Great employees are reliable, dependable, proactive, diligent, great leaders and great followers... they possess a wide range of easily-defined—but hard to find—qualities.

A few hit the next level. Some employees are remarkable, possessing qualities that may not appear on performance appraisals but nonetheless make a major impact on performance.

Here are eight qualities of remarkable employees:

1. They ignore job descriptions. The smaller the company, the more important it is that employees can think on their feet, adapt quickly to shifting priorities, and do whatever it takes, regardless of role or position, to get things done.

When a key customer's project is in jeopardy, remarkable employees know without being told there's a problem and jump in without being asked—even if it's not their job.

2. They're eccentric... The best employees are often a little different: quirky, sometimes irreverent, even delighted to be unusual. They seem slightly odd, but in a really good way. Unusual personalities shake things up, make work more fun, and transform a plain-vanilla group into a team with flair and flavor.

People who aren't afraid to be different naturally stretch boundaries and challenge the status quo, and they often come up with the best ideas.

3. But they know when to dial it back. An unusual personality is a lot of fun... until it isn't. When a major challenge pops up or a situation gets stressful, the best employees stop expressing their individuality and fit seamlessly into the team.

Remarkable employees know when to play and when to be serious; when to be irreverent and when to conform; and when to challenge and when to back off. It's a tough balance to strike, but a rare few can walk that fine line with ease.

4. They publicly praise... Praise from a boss feels good. Praise from a peer feels awesome, especially when you look up to that person.

Remarkable employees recognize the contributions of others, especially in group settings where the impact of their words is even greater.

5. And they privately complain. We all want employees to bring issues forward, but some problems are better handled in private. Great employees often get more latitude to bring up controversial subjects in a group setting because their performance allows greater freedom.

Remarkable employees come to you before or after a meeting to discuss a sensitive issue, knowing that bringing it up in a group setting could set off a firestorm.

6. They speak when others won't. Some employees are hesitant to speak up in meetings. Some are even hesitant to speak up privately.

An employee once asked me a question about potential layoffs. After the meeting I said to him, "Why did you ask about that? You already know what's going on." He said, "I do, but a lot of other people don't, and they're afraid to ask. I thought it would help if they heard the answer from you."

Remarkable employees have an innate feel for the issues and concerns of those around them, and step up to ask questions or raise important issues when others hesitate.

7. They like to prove others wrong. Self-motivation often springs from a desire to show that doubters are wrong. The kid without a college degree or the woman who was told she didn't have leadership potential often possess a burning desire to prove other people wrong.

Education, intelligence, talent, and skill are important, but drive is critical. Remarkable employees are driven by something deeper and more personal than just the desire to do a good job.

8. They're always fiddling. Some people are rarely satisfied (I mean that in a good way) and are constantly tinkering with something: Reworking a timeline, adjusting a process, tweaking a workflow.

Great employees follow processes. Remarkable employees find ways to make those processes even better, not only because they are expected to… but because they just can't help it.


Jeff Haden learned much of what he knows about business and technology as he worked his way up in the manufacturing industry. Everything else he picks up from ghostwriting books for some of the smartest leaders he knows in business. @jeff_haden

Decision Making

You won't make your decisions easier just by putting them off until later. When a decision is called for, go ahead and make it.

If you keep your options open for too long, those options will no longer be available to you. Choose one option based on your best information, and go with it.

Give sufficient thought and consideration to your decisions, but don't drag them on endlessly. The sooner you get start implementing a decision, the more effective you'll be.

Accept the fact that you won't make a perfect decision every time. And remember that you'll have opportunities to adjust your approach if things don't work out the way you planned.

You cannot predict the future yet there is much you can do to intelligently and effectively prepare for it. Instead of agonizing over what might or might not happen, get busy creating value that will be there no matter what happens.

Go ahead and decide. The sooner you decide, the more time and energy you'll have to make the decision work out the way you intended.

~Ralph Marston