Friday, May 25, 2012

Windows 8 - XAML: Implementation of Application.DoEvents method

This is how we can implement DoEvents method in Windows 8 , and VS 11.

public class Application

{
#region Static Methods
 

public static void DoEvents(object sender)
{
Window.Current.CoreWindow.Dispatcher.Invoke(CoreDispatcherPriority.Normal, (task, args) =>
{ }, sender, sender);

}

#endregion

}

Tuesday, May 22, 2012

SQL Azure : Migrating ASPNet Database to Sql Azure

If you ever wondered about how you will migrate your ASPNet DB to cloud, here is the solution.

1) Create a Blank  Database "ASPNet" using your SQL Azure connection.
2) Launch "Microsoft SQL Server Management Studio" and connect to your SQL Azure Database by using your credentials. Now Run following script against database created in Step. I have created this script by using "SQL Azure Migration Wizard" available at codeplex.



SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Applications]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Applications](
    [ApplicationName] [nvarchar](235) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [ApplicationId] [uniqueidentifier] NOT NULL,
    [Description] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
    [ApplicationId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Users]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Users](
    [ApplicationId] [uniqueidentifier] NOT NULL,
    [UserId] [uniqueidentifier] NOT NULL,
    [UserName] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [IsAnonymous] [bit] NOT NULL,
    [LastActivityDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [UserId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UserApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Users]'))
ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [UserApplication] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UserApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Users]'))
ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [UserApplication]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Memberships]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Memberships](
    [ApplicationId] [uniqueidentifier] NOT NULL,
    [UserId] [uniqueidentifier] NOT NULL,
    [Password] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PasswordFormat] [int] NOT NULL,
    [PasswordSalt] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Email] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [PasswordQuestion] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [PasswordAnswer] [nvarchar](128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [IsApproved] [bit] NOT NULL,
    [IsLockedOut] [bit] NOT NULL,
    [CreateDate] [datetime] NOT NULL,
    [LastLoginDate] [datetime] NOT NULL,
    [LastPasswordChangedDate] [datetime] NOT NULL,
    [LastLockoutDate] [datetime] NOT NULL,
    [FailedPasswordAttemptCount] [int] NOT NULL,
    [FailedPasswordAttemptWindowStart] [datetime] NOT NULL,
    [FailedPasswordAnswerAttemptCount] [int] NOT NULL,
    [FailedPasswordAnswerAttemptWindowsStart] [datetime] NOT NULL,
    [Comment] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
    [UserId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MembershipApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Memberships]'))
ALTER TABLE [dbo].[Memberships]  WITH CHECK ADD  CONSTRAINT [MembershipApplication] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MembershipApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Memberships]'))
ALTER TABLE [dbo].[Memberships] CHECK CONSTRAINT [MembershipApplication]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MembershipUser]') AND parent_object_id = OBJECT_ID(N'[dbo].[Memberships]'))
ALTER TABLE [dbo].[Memberships]  WITH CHECK ADD  CONSTRAINT [MembershipUser] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MembershipUser]') AND parent_object_id = OBJECT_ID(N'[dbo].[Memberships]'))
ALTER TABLE [dbo].[Memberships] CHECK CONSTRAINT [MembershipUser]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Profiles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Profiles](
    [UserId] [uniqueidentifier] NOT NULL,
    [PropertyNames] [nvarchar](4000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PropertyValueStrings] [nvarchar](4000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [PropertyValueBinary] [image] NOT NULL,
    [LastUpdatedDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [UserId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UserProfile]') AND parent_object_id = OBJECT_ID(N'[dbo].[Profiles]'))
ALTER TABLE [dbo].[Profiles]  WITH CHECK ADD  CONSTRAINT [UserProfile] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UserProfile]') AND parent_object_id = OBJECT_ID(N'[dbo].[Profiles]'))
ALTER TABLE [dbo].[Profiles] CHECK CONSTRAINT [UserProfile]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Roles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Roles](
    [ApplicationId] [uniqueidentifier] NOT NULL,
    [RoleId] [uniqueidentifier] NOT NULL,
    [RoleName] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Description] [nvarchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
    [RoleId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RoleApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Roles]'))
ALTER TABLE [dbo].[Roles]  WITH CHECK ADD  CONSTRAINT [RoleApplication] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[RoleApplication]') AND parent_object_id = OBJECT_ID(N'[dbo].[Roles]'))
ALTER TABLE [dbo].[Roles] CHECK CONSTRAINT [RoleApplication]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UsersInRoles]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[UsersInRoles](
    [UserId] [uniqueidentifier] NOT NULL,
    [RoleId] [uniqueidentifier] NOT NULL,
PRIMARY KEY CLUSTERED
(
    [UserId] ASC,
    [RoleId] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
END
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UsersInRoleRole]') AND parent_object_id = OBJECT_ID(N'[dbo].[UsersInRoles]'))
ALTER TABLE [dbo].[UsersInRoles]  WITH CHECK ADD  CONSTRAINT [UsersInRoleRole] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([RoleId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UsersInRoleRole]') AND parent_object_id = OBJECT_ID(N'[dbo].[UsersInRoles]'))
ALTER TABLE [dbo].[UsersInRoles] CHECK CONSTRAINT [UsersInRoleRole]
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UsersInRoleUser]') AND parent_object_id = OBJECT_ID(N'[dbo].[UsersInRoles]'))
ALTER TABLE [dbo].[UsersInRoles]  WITH CHECK ADD  CONSTRAINT [UsersInRoleUser] FOREIGN KEY([UserId])
REFERENCES [dbo].[Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[UsersInRoleUser]') AND parent_object_id = OBJECT_ID(N'[dbo].[UsersInRoles]'))
ALTER TABLE [dbo].[UsersInRoles] CHECK CONSTRAINT [UsersInRoleUser]
GO
-- BCPArgs:1:[dbo].[Applications] in "c:\SQLAzureMW\BCPData\dbo.Applications.dat" -E -n -b 10000 -a 16384
GO
-- BCPArgs:1:[dbo].[Users] in "c:\SQLAzureMW\BCPData\dbo.Users.dat" -E -n -b 10000 -a 16384
GO
-- BCPArgs:1:[dbo].[Memberships] in "c:\SQLAzureMW\BCPData\dbo.Memberships.dat" -E -n -b 10000 -a 16384
GO

Thursday, May 17, 2012

CQRS : Command Query Responsibility Segregation (A Design by contract methodology)

CQRS design pattern is generally used in Business Layer or Data-Access Layer, its purpose is to keep data access methods simple, and should adhere to their purpose.

It mandates Each method to perform a single operation and purpose of method should be clearly indicated by method name. For example if method name is GetEmployees then that method should only be returning Employees collection not modifying any employee object.

Using CQRS patter, lets design a Data access component for Employee , we will have a IEmployeeRepository Interface as shown below




As we can see for each action related to Employee Repository we have a method, and that method will only perform that operation (either command or query not both).

Wednesday, May 16, 2012

Code Contract : A Design by contract programming

Code contracts are used to define preconditions, postconditions and object invariants in a particular piece of code. These conditions are defined as contracts which will see below.

They let you specify a pass/fail condition for your application within code, which indirectly helps you in writing more meaningful unit tests without worrying about data and its context.

You con download dlls required for code contracts from this location.

Contracts are expressed using static method calls at method entries. Tools take care to interpret these declarative contracts in the right places. These methods are found in the System.Diagnostics.Contracts namespace.

• Contract.Requires takes a boolean condition and expresses a precondition of the method. A precondition must be true on entry to the method. It is the caller's responsibility to make sure the pre-condition is met.

• Contract.Ensures takes a boolean condition and expresses a postcondition of the method. A
postcondition must be true at all normal exit points of the method. It is the implementation's responsibility that the postcondition is met.

 After you have downloaded above installer and installed on your machine, you can open your project and open Properties tab in your application and select Contract tab as shown below.


Here you select "Perform Runtime Checking" & "Contract Reference Assembly" as Build as shown in following image.


 Now you are ready to use all contract methods, in our code sample I am going to show how we make sure that user enters a number which is greater than Zero. In my code sample I am calculating Factorial for a passed number and before I calculate Factorial I need to make sure that user enters a number which is grater than Zero. Here we can see code execution fails when user enters number which is zero.


Now, when we disassemble generated exe, we can see that application when Builds, it inject a class "__ContractsRuntime" under System.Diagnostic.Contracts namespace , this class implementation is shown in following image.

And when we see our disassembled code it looks like, it injects __ContractsRuntime.Requires method which executes condition which was specified earlier.









Tuesday, May 15, 2012

Calculating Factorial using old school & Func Delegate

Hi, I am going to show 2 different implementation of calculating Factorial, first  by using old school format and then using Func delegates.
Important thing to note that using while using Func Delegate, its tricky as you can not define a recursive function using Func, so  what you do is you define a function variable and use that variable to perform recursion as shown in code below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace TestConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine("Using old school factorial method:" + Factorial(number));
            var f = FactorialUsingFunc();
            Console.WriteLine("Using Func Delegate method :" +f(number));
            Console.ReadLine();
        }
 
        private static int Factorial(int n)
        {
            return (n > 1) ? n*Factorial(n - 1) : n;
        }
 
        static Func<intint> FactorialUsingFunc()
        {
            Func<intint> factorial = null;
            factorial = n => n < 1 ? 1 : n * factorial(n - 1);
            return factorial;
        }
 
    }
}

Wednesday, May 9, 2012

MEF : Beyond Export and Import

I am going to describe some of advanced features of MEF

1) Container.SatisfyImportOnce Or Container.ComposeParts methods satisfies import/export only when they are called, any further changes in catalogs doesn't impact old created object.
eg.
AssemblyCatalog catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);
container.SatisfyImportsOnce(this);
 
2) AllowRecomposition attribute is used to stop any changes in old composed objects if there is any changes in Container's catalog items.
eg.
[ImportMany(AllowRecomposition = false)]
public IEnumerable<ICustomType> Strings { getset; } 


3) PartCreationPolicyis used to specify whether to create a Singleton instance of required object or multiple instance based on request. You can RequiredCreattionPolicy attribute to specify PartCreationPolicy for a particular type.

eg. Following line will give error as it will fail to satisfy PartCreationPolicy.
[ExportPartCreationPolicy(CreationPolicy.NonShared)] public class CustomClass {..}
[Import(RequiredCreationPolicy = CreationPolicy.Shared)] CustomClass _inst1;


4) AllowDefault attribute can be used when you don't have any export to satisfy for a required import. If you dont set this attribute as true, you will get an exception if there is no export to satisfy an import.

5) InhertitedExport attribute can be used with a base class / interface to specify that all its child classes will export base-class or interface types.

eg. In following example Type1 and Type2 will export ICustomType as ICustomType is marked with InheritedExport attribute.

    [InheritedExport(typeof (ICustomType))]
    public interface ICustomType
    {
    }
 
    public class Type1 : ICustomType {}
    public class Type2 : ICustomType {}
 
6) You can implement IPartImportsSatisfiedNotification interface for your class, 
when you want to be notified about Imports satisfied event.
 
7) You can use ImportingConstructor attribute, if you are using parametrized constructors 
and have a constructor parameter which can which needs to be imported. 

Sunday, May 6, 2012

Metro : 5 Metro Design Prinicipal

I am going to discuss 5 Metro design principals and how they help a UX in designing a better , easily usable UI for any application. Microsoft has a done a lot of homework in putting together these principals and if we developer stick to these principals we can definable make a s/w which will help users in getting a maximum return for their investment in s/w.

Lets see what are famous 5 Metro design principals:

1) Pride in Craftsmanship
This talks about how you put together different pieces in UI. In Metro we have Tiles, and these tiles are nothing but a group of tables. Since HTML was used to design applications, Developer & Designers have been using Tables every where.

Metro puts a lot of stress in using Grids for UI. Using a grid helps in Developer making sure each and every UI element is properly aligned.

This principal also puts a lot of stress in making a proper use of Pixels. Each and every UI element should be properly sized and follow a consistent size across applications.
For example Heading should be 42", contents should be 11" in font-size.


2) Do more with Less

This talks about how you are planning to use UI elements in your applications. Lets if you have a grid and it shows employee records which can be edited and deleted. Now a developer will normally end up showing Delete and Edit button with every record, but if we follow Metro guidelines we should not have a separate Edit and Delete for each record infact we should let user select a record in Employee grid and then he should see Edit or Delete button to perform any action.

3) Be fast and fluid
This principal talks about UIs which are fluid in nature, By letting your UI being fluid you let your application expand and collapse based on available Screen. If a user has a bigger monitor and better display then he deserves to see the contents in a better way. By letting your application adjust its display based on available screen, an application can have recommendation than being rigid.

This principal also encourage application to be better responsive, don't try to block UI thread while executing resource intensive task. If you are querying database or service for data then try to get data in smaller chunks and keep user updated about available data.


 4) Authentically Digital
This principal talks about authenticating and sharing user's profile and experience for an application across different devices.
Lets say if a user is using customer search feature of your application and goes for a lunch break. While having if suddenly something strikes user and he wants to do some operation on Customer search page, luckily he realizes that he has his I-Pad and he starts your application,,,so definitely at this point if your application figures out that last time same user was on customer search page and if it launches same page for user then definitely it will be a great help for user.


5) Win as One
This principal talks about sharing contracts across application. Best example is sharing themes across application. Lets a user whose favourite color is Green and has used Green Theme for its Operating System, then for same user if your application has more of a Green color. This way if all application shares and obey each others contract then it will help user in having a consistent feeling across all applications.