Thursday, November 28, 2013

The S.O.L.I.D. Object Oriented Programming(OOP) Principles

Introduction

What does it take to be an Object Oriented Programmer? There was a time where I believed all that meant was that you worked with a language such as C#, C++, or Java. However, the more I get acquainted with newer technologies, the more I realize that there is a set of fundamentals core to the title. And really, these fundamentals are about architecting the best, most update-able, scalable systems. Just yesterday while diving into DataObjects.NET, I was greeted by Domain Driven Design(DDD)-- a popular architectural abstraction. It motivated me to think about the basics, which is the purpose of this article.

The S.O.L.I.D. Principles of Class Design

The S.O.L.I.D. principles seem to be the least common denominator of creating great classes; even before Design Patterns. I recommend taking some time to really think about each of them and how you can apply them. Let's dive in, one by one.

The Single Responsibility Principle

There should never be more than one reason for a class to change. Basically, this means that your classes should exist for one purpose only. For example, let's say you are creating a class to represent a SalesOrder. You would not want that class to save to the database, as well as export an XML-based receipt. Why? Well if later on down the road, you want to change database type (or if you want to change your XML schema), you're allowing one responsibility's changes to possibly alter another. Responsibility is the heart of this principle, so to rephrase there should never be more than one responsibility per class.

The Open Closed Principle

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. At first, this seems to be contradictory: how can you make an object behave differently without modifying it? The answer: by using abstractions, or by placing behavior(responsibility) in derivative classes. In other words, by creating base classes with override-able functions, we are able to create new classes that do the same thing differently without changing the base functionality. Further, if properties of the abstracted class need to be compared or organized together, another abstraction should handle this. This is the basis of the "keep all object variables private" argument.

The Liskov Substitution Principle

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. In other words, if you are calling a method defined at a base class upon an abstracted class, the function must be implemented properly on the subtype class. Or, "when using an object through its base class interface, [the] derived object must not expect such users to obey preconditions that are stronger than those required by the base class." The ever-popular illustration of this is the square-rectangle example. Turns out a square is not a rectangle, at least behavior-wise.

The Dependency Inversion Principle

Depend on abstractions, not on concretions or High level modules should not depend upon low level modules. Both should depend upon abstractions. Abstractions should not depend upon details. Details should depend upon abstractions. (I like the first explanation the best.) This is very closely related to the open closed principle we discussed earlier. By passing dependencies (such as connectors to devices, storage) to classes as abstractions, you remove the need to program dependency specific. Here's an example: an Employee class that needs to be able to be persisted to XML and a database. If we placed ToXML() and ToDB() functions in the class, we'd be violating the single responsibility principle. If we created a function that took a value that represented whether to print to XML or to DB, we'd be hard-coding a set of devices and thus be violating the open closed principle. The best way to do this would be to:
 
   Create an abstract class (named DataWriter, perhaps) that can be inherited from for XML (XMLDataWriter) or DB (DbDataWriter) Saving, and then
CCreate a class (named EmployeeWriter) that would expose an Output(DataWriter saveMethod) that accepts a dependency as an argument. See how the Output method is dependent upon the abstractions just as the output types are? The dependencies have been inverted. Now we can create new types of ways forEmployee data to be written, perhaps via HTTP/HTTPS by creating abstractions, and without modifying any of our previous code! No rigidity--the desired outcome.

The Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they do not use. My favorite version of this is written as "when a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class." Kinda sounds like the inheritance specific single responsibility principle.

Sources

     The Interface Segregation Principle
     http://www.oodesign.com/liskov-s-substitution-principle.html 
    http://codesignals.blogspot.in/2017/02/simplifying-liskov-substitution.html

Wednesday, August 14, 2013

WPF Input Validation Using MVVM

Data validation is a key part in WPF.

Validation is used to alert the user that the data he entered is illegal.

In this post we will see how to validate user input using MVVM binding.

I have created 2 different templates for input validation:

Click WPFInputValidation Link To Download full source.

Example 1 :

To impelment validation we need to use IDataErrorInfo interface.

IDataErrorInfo  interface provides the functionality to offer custom error information that a user  interface can bind to.

It has 2 Properties :

- Error : Gets an error message indicating what is wrong with this object.

- string this[string columnName] Indexer : it will return the error message for the property. The default is an empty string ("")

Let's go through step by step to understand validation with mvvm binding and styling the validation template.

Step 1 :  First change ErrorToolTip style by customizing the Template.
 
<ControlTemplate x:Key="ErrorToolTipTemplate_1">
 <ControlTemplate.Resources>
  <Style x:Key="textblockErrorTooltip" TargetType="TextBlock">
   <Setter Property="HorizontalAlignment" Value="Center" />
   <Setter Property="VerticalAlignment" Value="Center" />
   <Setter Property="FontWeight" Value="Bold" />
   <Setter Property="Foreground" Value="White" />
   <Setter Property="Margin" Value="10 0 10 0" />
  </Style>
 </ControlTemplate.Resources>
 <DockPanel LastChildFill="true">
  <Border Height="Auto"
   Margin="5,0,0,0"
   Background="#DC000C"
   CornerRadius="3"
   DockPanel.Dock="right">
    <TextBlock Style="{StaticResource textblockErrorTooltip}" 
Text="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
  </Border>
  <AdornedElementPlaceholder Name="customAdorner">
   <Border BorderBrush="#DC000C" BorderThickness="1.3" />
  </AdornedElementPlaceholder>
 </DockPanel>
</ControlTemplate> 
 

As shown in above source, created ControlTemplate and changed the error tooltip style by Adding Border control in DockPanel, within Border TextBlock placed with Text property binded to the error message set to the property from viewmodel.
 changed Backgroud of the border to Red so it will display error message surround with  border fill with red color. This will dispaly error on right side of the TextBox control. like :


ErrorTemplate uses adorner layer. which is drawing layer, using adorner layer you can add visual appearance to indicate an error without replacing controltemplate.

AdornedElementPlaceholder is part of the Validation feature of data binding. it specify where a decorated control is placed relative to other elements  in the ControlTemplate.

Step 2 : Create TextBox style and set Validation ErrorTemplate.
<Style TargetType="TextBox">
 <Setter Property="HorizontalAlignment" Value="Left" />
 <Setter Property="VerticalAlignment" Value="Top" />
 <Setter Property="Width" Value="150" />
 <Setter Property="Height" Value="30" />
 <Setter Property="Validation.ErrorTemplate" 
                 Value="{DynamicResource ErrorToolTipTemplate_1}" />
 <Style.Triggers>
  <Trigger Property="Validation.HasError" Value="true">
   <Setter Property="ToolTip" 
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
  </Trigger>
 </Style.Triggers>
</Style> 

Created style of TargetType=TextBox, and Validation.ErrorTemplate is set to previously created template (DynamicResource ErrorToolTipTemplate)

you have to set Resource using DynamicResource, if your temaplate/style is available at global place (App.xaml)
if your control style and template is created in page itself then set resource using StaticResource keyword.

Step 3 : Create ViewModel class, that contains Properties to Bind into view.
public class InputValidationViewModel : ViewModelBase
{
 public InputValidationViewModel()
 {   
 }
 private string employeeName;
 public string EmployeeName
 {
  get { return employeeName; }
  set { employeeName = value; RaisePropertyChanged("EmployeeName"); }
 }
 private string email;
 public string Email
 {
  get { return email; }
  set {email = value; RaisePropertyChanged("Email"); }
 }
 private long phoneNumber;
 public long PhoneNumber
 {
  get { return phoneNumber; }
  set { phoneNumber = value; RaisePropertyChanged("PhoneNumber"); }
 }
 private bool IsValidEmailAddress
 {
  get { return emailRegex.IsMatch(Email); }
 }
} 
 
as shown in above code, ViewModel created and added some propeties that need to bind in UserControl.

Step 4 : Implement IDataErrorInfo Interface
 
public class InputValidationViewModel : ViewModelBase, IDataErrorInfo
{
 private Regex emailRegex = new Regex(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");  
 public InputValidationViewModel()
 {   
 }
 
        private string error = string.Empty;
 public string Error
 {
  get { return error; }
 }
 public string this[string columnName]
 {
    get
    {
  error = string.Empty;
  if (columnName == "EmployeeName" && string.IsNullOrWhiteSpace(EmployeeName))
  {
   error = "Employee name is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber == 0)
  {
   error = "Phone number is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber.ToString().Length > 10)
  {
   error = "Phone number must have less than or equal to 10 digits!";
  }
  else if (columnName == "Email" && string.IsNullOrWhiteSpace(Email))
  {
   error = "Email address is required!";
  }
  else if (columnName == "Email" && !IsValidEmailAddress)
  {
   error = "Please enter valid email address!";
  }
  return error;
 
      }
       }
} 

IDataErrorInfo has Error property which returns the validation error that does not match the codition.

in above code, i set the error for each propeties by checking the codition, it coditiion is false then set the error for that property.

For valid email validation, created Regex expression to check entered email address is valid ro not.

This error appear on right side of the control that has property binded.

Step 5 : Last, Add TextBox cotrol in View
 
<TextBox Grid.Row="1"
 Grid.Column="1"
 Text="{Binding EmployeeName,
           Mode=TwoWay,
           UpdateSourceTrigger=PropertyChanged,
    ValidatesOnDataErrors=True}" /> 
 
  

Here EmployeeName proeprty is binded to TextBox control, you have to set ValidatesOnDataErrors=True to throw data error ( entered data is valida or not.)

Mode=TwoWay will allow user to change property from UI as well update UI from ViewModel property.

UpdateSourceTrigger=PropertyChanged will notify changes  is updated as soon as the property changes.

If UpdateSourceTrigger is not set, then TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox.

This behavior is controlled by a property on the binding called UpdateSourceTrigger.

Example 2 :


In this example, only ControlTemplate is chaned, other things like : ViewModels Property, Controls are same.


As shown in above image, tooltip style is changed, ! mark with red circle surrounded image is added on the errortemplate.

small triangle added on template, to show top right corner of the control if any data error exists.

below are the  template change compare to previous example template :
 
<Border x:Name="ValidationErrorElement"
 BorderBrush="#FFDB000C"
 BorderThickness="1.2"
 CornerRadius="1"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <Grid Width="12"
  Height="12"
  Margin="1,-4,-4,0"
  HorizontalAlignment="Right"
  VerticalAlignment="Top"
  Background="Transparent">
  <Path Margin="1,3,0,0"
        Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"
        Fill="#FFDC000C" />
  <Path Margin="1,3,0,0"
        Data="M 0,0 L2,0 L 8,6 L8,8"
        Fill="#ffffff" />
 </Grid>
</Border>
<Border Grid.Column="0"
 Width="15"
 Height="15"
 Margin="0 0 3 0"
 HorizontalAlignment="Right"
 VerticalAlignment="Center"
 Background="Red"
 CornerRadius="10"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <TextBlock HorizontalAlignment="center"
  VerticalAlignment="center"
  FontWeight="Bold"
  Foreground="white"
  Text="!" />
</Border> 
 
 
as shown in above code,

In First border, 2 shapes is created using path, this will create Triangle shape to disply on top right corner of the control.

it will help you to create your custom shapes based on your requirement.

Second border will create red cirlce (by setting CornerRadius proeprty) with ! text wihin cirlce area.

it will display right side of the cotrol, if any data error is there for property.

Conclusion

This way you can create you custom error template for input controls.

Dwonload link

Sunday, July 21, 2013

Delegate Command class for WPF Application

public class DelegateCommand : ICommand

         {

                 private readonly Action executeMethod = delegate { };

 

                 private readonly Func<bool> canExecuteMethod;

 

                 public DelegateCommand(Action executeMethod)

                          : this(executeMethod, null)

                 {

                 }

 

                 public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)

                 {

                          this.executeMethod = executeMethod;

                          this.canExecuteMethod = canExecuteMethod;

                 }

 

                 public bool CanExecute(object parameter)

                 {

                          return canExecuteMethod != null ? canExecuteMethod() : true;

                 }

 

                 public void Execute(object parameter)

                 {

                          executeMethod();

                 }

 

                 public event EventHandler CanExecuteChanged;

         }

 

         public class DelegateCommand<T> : ICommand

         {

                 private readonly Action<T> executeMethod = delegate { };

 

                 private readonly Func<T, bool> canExecuteMethod;

 

                 public DelegateCommand(Action<T> executeMethod)

                          : this(executeMethod, null)

                 {

                 }

 

                 public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)

                 {

                          this.executeMethod = executeMethod;

                          this.canExecuteMethod = canExecuteMethod;

                 }

 

                 public bool CanExecute(object parameter)

                 {

                          T tobj = (T)parameter;

                          return canExecuteMethod != null ? canExecuteMethod(tobj) : true;

                 }

 

                 public void Execute(object parameter)

                 {

                          T tobj = (T)parameter;

                          executeMethod(tobj);

                 }

 

                 public event EventHandler CanExecuteChanged;

         }

 

WPF Input Validation Using MVVM

Data validation is a key part in WPF.

Validation is used to alert the user that the data he entered is illegal.

In this post we will see how to validate user input using MVVM binding.

I have created 2 different templates for input validation:

Click WPFInputValidation Link To Download full source.

Example 1 :

To impelment validation we need to use IDataErrorInfo interface.

IDataErrorInfo  interface provides the functionality to offer custom error information that a user  interface can bind to.

It has 2 Properties :

- Error : Gets an error message indicating what is wrong with this object.

- string this[string columnName] Indexer : it will return the error message for the property. The default is an empty string ("")

 

Let's go through step by step to understand validation with mvvm binding and styling the validation template.

Step 1 :  First change ErrorToolTip style by customizing the Template.

 
<ControlTemplate x:Key="ErrorToolTipTemplate_1">
 <ControlTemplate.Resources>
  <Style x:Key="textblockErrorTooltip" TargetType="TextBlock">
   <Setter Property="HorizontalAlignment" Value="Center" />
   <Setter Property="VerticalAlignment" Value="Center" />
   <Setter Property="FontWeight" Value="Bold" />
   <Setter Property="Foreground" Value="White" />
   <Setter Property="Margin" Value="10 0 10 0" />
  </Style>
 </ControlTemplate.Resources>
 <DockPanel LastChildFill="true">
  <Border Height="Auto"
   Margin="5,0,0,0"
   Background="#DC000C"
   CornerRadius="3"
   DockPanel.Dock="right">
    <TextBlock Style="{StaticResource textblockErrorTooltip}" 
Text="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
  </Border>
  <AdornedElementPlaceholder Name="customAdorner">
   <Border BorderBrush="#DC000C" BorderThickness="1.3" />
  </AdornedElementPlaceholder>
 </DockPanel>
</ControlTemplate> 
 


As shown in above source, created ControlTemplate and changed the error tooltip style by Adding Border control in DockPanel, within Border TextBlock placed with Text property binded to the error message set to the property from viewmodel.
 changed Backgroud of the border to Red so it will display error message surround with  border fill with red color. This will dispaly error on right side of the TextBox control. like :



ErrorTemplate uses adorner layer. which is drawing layer, using adorner layer you can add visual appearance to indicate an error without replacing controltemplate.

AdornedElementPlaceholder is part of the Validation feature of data binding. it specify where a decorated control is placed relative to other elements  in the ControlTemplate.

Step 2 : Create TextBox style and set Validation ErrorTemplate.

<Style TargetType="TextBox">
 <Setter Property="HorizontalAlignment" Value="Left" />
 <Setter Property="VerticalAlignment" Value="Top" />
 <Setter Property="Width" Value="150" />
 <Setter Property="Height" Value="30" />
 <Setter Property="Validation.ErrorTemplate" 
                 Value="{DynamicResource ErrorToolTipTemplate_1}" />
 <Style.Triggers>
  <Trigger Property="Validation.HasError" Value="true">
   <Setter Property="ToolTip" 
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
  </Trigger>
 </Style.Triggers>
</Style> 


Created style of TargetType=TextBox, and Validation.ErrorTemplate is set to previously created template (DynamicResource ErrorToolTipTemplate)

you have to set Resource using DynamicResource, if your temaplate/style is available at global place (App.xaml)
if your control style and template is created in page itself then set resource using StaticResource keyword.

Step 3 : Create ViewModel class, that contains Properties to Bind into view.

public class InputValidationViewModel : ViewModelBase
{
 public InputValidationViewModel()
 {   
 }
 private string employeeName;
 public string EmployeeName
 {
  get { return employeeName; }
  set { employeeName = value; RaisePropertyChanged("EmployeeName"); }
 }
 private string email;
 public string Email
 {
  get { return email; }
  set {email = value; RaisePropertyChanged("Email"); }
 }
 private long phoneNumber;
 public long PhoneNumber
 {
  get { return phoneNumber; }
  set { phoneNumber = value; RaisePropertyChanged("PhoneNumber"); }
 }
 private bool IsValidEmailAddress
 {
  get { return emailRegex.IsMatch(Email); }
 }
} 
 

as shown in above code, ViewModel created and added some propeties that need to bind in UserControl.

Step 4 : Implement IDataErrorInfo Interface

 
public class InputValidationViewModel : ViewModelBase, IDataErrorInfo
{
 private Regex emailRegex = new Regex(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");  
 public InputValidationViewModel()
 {   
 }
 
        private string error = string.Empty;
 public string Error
 {
  get { return error; }
 }
 public string this[string columnName]
 {
    get
    {
  error = string.Empty;
  if (columnName == "EmployeeName" && string.IsNullOrWhiteSpace(EmployeeName))
  {
   error = "Employee name is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber == 0)
  {
   error = "Phone number is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber.ToString().Length > 10)
  {
   error = "Phone number must have less than or equal to 10 digits!";
  }
  else if (columnName == "Email" && string.IsNullOrWhiteSpace(Email))
  {
   error = "Email address is required!";
  }
  else if (columnName == "Email" && !IsValidEmailAddress)
  {
   error = "Please enter valid email address!";
  }
  return error;
 
      }
       }
} 


IDataErrorInfo has Error property which returns the validation error that does not match the codition.

in above code, i set the error for each propeties by checking the codition, it coditiion is false then set the error for that property.

For valid email validation, created Regex expression to check entered email address is valid ro not.

This error appear on right side of the control that has property binded.

Step 5 : Last, Add TextBox cotrol in View

 
<TextBox Grid.Row="1"
 Grid.Column="1"
 Text="{Binding EmployeeName,
           Mode=TwoWay,
           UpdateSourceTrigger=PropertyChanged,
    ValidatesOnDataErrors=True}" /> 
 
  


Here EmployeeName proeprty is binded to TextBox control, you have to set ValidatesOnDataErrors=True to throw data error ( entered data is valida or not.)

Mode=TwoWay will allow user to change property from UI as well update UI from ViewModel property.

UpdateSourceTrigger=PropertyChanged will notify changes  is updated as soon as the property changes.

If UpdateSourceTrigger is not set, then TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox.

This behavior is controlled by a property on the binding called UpdateSourceTrigger.

Example 2 :


In this example, only ControlTemplate is chaned, other things like : ViewModels Property, Controls are same.

 


As shown in above image, tooltip style is changed, ! mark with red circle surrounded image is added on the errortemplate.

small triangle added on template, to show top right corner of the control if any data error exists.

below are the  template change compare to previous example template :

 
<Border x:Name="ValidationErrorElement"
 BorderBrush="#FFDB000C"
 BorderThickness="1.2"
 CornerRadius="1"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <Grid Width="12"
  Height="12"
  Margin="1,-4,-4,0"
  HorizontalAlignment="Right"
  VerticalAlignment="Top"
  Background="Transparent">
  <Path Margin="1,3,0,0"
        Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"
        Fill="#FFDC000C" />
  <Path Margin="1,3,0,0"
        Data="M 0,0 L2,0 L 8,6 L8,8"
        Fill="#ffffff" />
 </Grid>
</Border>
<Border Grid.Column="0"
 Width="15"
 Height="15"
 Margin="0 0 3 0"
 HorizontalAlignment="Right"
 VerticalAlignment="Center"
 Background="Red"
 CornerRadius="10"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <TextBlock HorizontalAlignment="center"
  VerticalAlignment="center"
  FontWeight="Bold"
  Foreground="white"
  Text="!" />
</Border> 
 
 

as shown in above code,

In First border, 2 shapes is created using path, this will create Triangle shape to disply on top right corner of the control.

it will help you to create your custom shapes based on your requirement.

Second border will create red cirlce (by setting CornerRadius proeprty) with ! text wihin cirlce area.

it will display right side of the cotrol, if any data error is there for property.

Conclusion

This way you can create you custom error template for input controls.

Dwonload link

Tuesday, May 28, 2013

How to turn your Windows 7 laptop into a wireless hotspot

Sharing your Windows internet connection via software has traditionally been a tricky business.

There are programs that can help you do it, but they're often awkward to set up, and prone to complicated security and reliability issues, so most people don't even try.

But that could all be about to change, thanks to a new Windows 7 feature called Virtual Wi-Fi.

The idea is a simple one: the operating system can virtualise any compatible wireless adapter, to make it appear as though you've as many additional adapters as you need.

The effect is dramatic. Once it's set up, then any Wi-Fi compatible device that can connect to you - another desktop, laptop, or an iPod Touch, say - will immediately be able to get online, by sharing your internet connection through a duplicate of your wireless adapter.

Getting this working isn't too difficult, either, as long as you can get over the first hurdle: finding a virtual Wi-Fi-compatible driver for your wireless adapter.

Intel's latest 32-bit and 64-bit drivers now include support, as do various others for Atheros, Broadcom, Realtek and other big players, but these don't apply to every chipset. Check the support site for your wireless adapter to see what's available.

If you're in luck and manage to find and install an up-to-date Windows 7 driver for your adapter, then the next step is to set it up, and for that you'll need an elevated command prompt. Click Start, type CMD, right-click the Cmd.exe link and select "Run as Administrator".

Now type the following command:

netsh wlan set hostednetwork mode=allow ssid=MyNet key=MyPassword

and press [Enter]. Replace "MyNet" with the name you'd like to use for your custom network, and "MyPassword" with a password that's a little harder to guess.

Still at the command line, type

netsh wlan start hostednetwork

and press [Enter] to fire up the virtual adapter.

Now click Control Panel > Network and Internet > Network and Sharing Centre > Change Adapter Settings, right-click your internet connection and select Properties. Click the Sharing tab, check "Allow other network users to connect...", choose your virtual Wi-Fi adaptor - and that's it.

 

Thursday, April 4, 2013

Employees leave managers, not companies

Today I found out one of my good friends left their position at a well-known technology company that many people would “kill” to work for. I asked him why he left, expecting an answer like “I needed more of a challenge”, or “I outgrew the position and there was nowhere for me to grow”, but instead he said “I couldn’t work with my boss”.

As he said this I thought about all the people leaving their positions because they simply couldn’t work with their manager. The work was stimulating, the team was great but their manager was unbearable to work with. In these situations, what seems to happen is companies lose good employees on a regular basis and all the managers sit around a conference table trying to address employee attrition, developing strategies for employee retention.

Employee retention is a real problem that all managers face. The key to being able to keep the good employees is not so much the salary you offer them or even the actual work, it is more about how you manage them and how they feel working under you as their manager. Do they feel valued within your team? Do you provide them with timely feedback? Do they feel your support as a manager leading their team or company?

Abraham Maslow was an American psychologist who was best known for creating Maslow’s hierarchy of needs which can be seen below.

Source: Diana Vanbrabant

As a manager we are able to affect three levels of needs within this hierarchy – safety, love & belonging and esteem. These 3 levels represents different elements within the workplace. The first level - safety refers to job security, career progression as well as health benefits and perhaps even gym membership. How do your employees feel about their job? Are they constantly afraid of cuts due to the recession? Do they know that as a manager you care about their wellbeing as well as their work?

The next level is love and belonging. People want to feel as if they are making a difference and are part of something bigger. As a manager how you approach giving out tasks, mentoring employees and interacting with them show how much you value their work. It is your duty as a manager to show employees how their work is making a difference and is part of a much larger plan. The worst thing for an employee is for them to think they are just another cog in a machine.

The last level is esteem. This refers to confidence and respect. It is important to manage your staff in terms of how they feel towards the work and to their peers and managers. Respect within the workplace is extremely important and can be the difference between keeping a good employee or losing them. Training and development when necessary is a good way to boost confidence and equip staff with the right skills. Investing in your staff to help them upskill benefits both the company and the employees. Zig Ziglar once said that there was only one thing worse than training (or growing) your staff and having them leave, and that is not training or developing them and having them stay.

A Florida State University (FSU) professor and two of his doctoral students have conducted a study which highlights the impacts of an abusive or poor manager/boss. They surveyed over 700 people who work in a variety of jobs and asked for their opinions of supervisor treatment on the job.

The study revealed these results:

39%: Their supervisor failed to keep promises
37%: Their supervisor failed to give credit when due
31%: Their supervisor gave them the “silent treatment” in the past year.
27%: Their supervisor made negative comments about them to other employees or managers.
24%: Their supervisor invaded their privacy.
23%: Their supervisor blames others to cover up mistakes or minimize embarrassment

Source: Florida State University

These points act as a good checklist to see how you are managing your staff because at the end of the day employees leave managers and bosses, not companies!

 

Tuesday, March 26, 2013

Create database from existing mdf file in sql server

EXEC sp_attach_single_file_db @dbname = 'AdventureWorks2012_Data',

@physname = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\data\AdventureWorks2012_Data.mdf'

 

Monday, March 18, 2013

DataContract and MessageContract

1. Comparison

Data Contracts

WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service.

you can say “Data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged”. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. A data contract precisely defines, for each parameter or return type, what data is serialized (turned into XML) to be exchanged.

Message Contracts

Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.

Using message contracts gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

2. Why use MessageContract when DataContract is there?

Data contracts are used to define the data structure. Messages that are simply a .NET type, lets say in form of POCO (plain old CLR object), and generate the XML for the data you want to pass.

Message contracts are preferred only when there is a need to “control” the layout of your message(the SOAP message); for instance, adding specific headers/footer/etc to a message.

Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.

3. Why we use MessageContract to pass SOAP headers ?

Passing information in SOAP headers is useful if you want to communicate information “out of band” from the operation signature.

For instance, session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself.

Another example is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.

A third example, again with security, is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

4. Can’t mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.