Archive for the Category ◊ .Net ◊

Wednesday, October 29th, 2014

Definition

Wiki says “Chain of responsibility is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain”. A mechanism also exists for adding new processing objects to the end of this chain and avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

 Participants

The classes and objects participating in this pattern are:

Handler  (Handler):

Defines an interface for handling the requests

ConcreteHandler  (EmployeeHandler, ChainTerminationHandler):

Handles requests it is responsible for. It can access its successor

If the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor

Client (Program.cs):

Initiates the request to a ConcreteHandler object on the chain

e1.SetNextHandler(e2);

e2.SetNextHandler(e3);

e3.SetNextHandler(e4);

 

Below sample code snippet explains chain of responsibility design pattern for approval of employee reimbursement application. An employee [ who can be an HR, Admin, CEO, etc] will have an approval limit. Once a reimbursement application is received, each of these employee would check if reimbursement amount is within the approval limit for which they are authorized to. If yes, they would approve else would pass it to the next employee in the chain for approval.

 

namespace COR.Emp.Reimbursement.Lib

{

public interface IReimbursementApprovar

{

Response ApproveReimbursement(IReimbursementReport reimbursementReport);

}

}

 

namespace COR.Emp.Reimbursement.Lib

{

public class Employee : IReimbursementApprovar

{

private string _name;

private readonly double _approvalLimit;

 

public Employee(string name, double approvalLimit)

{

_name = name;

_approvalLimit = approvalLimit;

}

 

public Response ApproveReimbursement(IReimbursementReport reimbursementReport)

{

return reimbursementReport.Total < _approvalLimit ? Response.Approve : Response.LimitExceeded;

}

}

}

 

namespace COR.Emp.Reimbursement.Lib

{

public enum Response

{

Approve,

Reject,

LimitExceeded

}

}

 

namespace COR.Emp.Reimbursement.Lib

{

public interface IReimbursementReport

{

double Total { get; set; }

}

}

 

namespace COR.Emp.Reimbursement.Lib

{

public class ReimbursementReport:IReimbursementReport

{

public ReimbursementReport(double value)

{

Total = value;

}

public double Total { get; set; }

}

}

 

 

namespace COR.Emp.Reimbursement.Lib

{

public abstract class Handler

{

// ReSharper disable once InconsistentNaming

protected Handler NextHandler;

protected IReimbursementApprovar Approvar { get; set; }

 

protected Handler(IReimbursementApprovar approvar)

{

Approvar = approvar;

NextHandler = ChainTerminationHandler.Instance;

}

public void SetNextHandler(Handler handler)

{

this.NextHandler = handler;

}

public abstract Response ApproveReimbursement(IReimbursementReport reimbursementReport);

}

}

 

// ConcreteHandlerHandles requests it is responsible for.

namespace COR.Emp.Reimbursement.Lib

{

public class EmployeeHandler: Handler

{

public EmployeeHandler(IReimbursementApprovar approvar) : base(approvar)

{

}

 

public override Response ApproveReimbursement(IReimbursementReport reimbursementReport)

{

var response = Approvar.ApproveReimbursement(reimbursementReport);

if (response == Response.LimitExceeded)

{

return NextHandler.ApproveReimbursement(reimbursementReport);

}

return response;

}

}

}

// ConcreteHandler : Handles requests it is responsible for.

namespace COR.Emp.Reimbursement.Lib

{

public class ChainTerminationHandler: Handler

{

private static readonly ChainTerminationHandler_instance = new ChainTerminationHandler (new Employee(string.Empty, 0));

 

public static ChainTerminationHandler Instance

{

get { return _instance; }

}

public ChainTerminationHandler(IReimbursementApprovar approvar) : base(approvar)

{

}

 

public override Response ApproveReimbursement(IReimbursementReport reimbursementReport)

{

return ApprovalResponse.Reject;

}

}

}

 

 

private static void Main(string[] args)

{

var e1 = new EmployeeHandler(new Employee(“Barikh”, 0));

var e2 = new EmployeeHandler(new Employee(“Amarnath”, 2000));

var e3 = new EmployeeHandler(new Employee(“Shanti”, 5000));

var e4 = new EmployeeHandler(new Employee(“Rahul”, 20000));

double inputValue;

 

// Construct chain to handle responsibility

e1.SetNextHandler(e2);

e2.SetNextHandler(e3);

e3.SetNextHandler(e4);

 

if (Double.TryParse(Console.ReadLine(), out inputValue))

{

var reimbursementReport= new ReimbursementReport(inputValue);

var response = e1.ApproveReimbursement(reimbursementReport);

Console.WriteLine(“The request was {0}”, response);

Console.ReadKey();

}

}

Tuesday, October 21st, 2014

This is a follow up post of Microsoft Release Management from scratch. In this section, we will look at following steps:-

  1. Spawning a new VM in Azure
  2. Installing Team Foundation Server with basic configuration.
  3. Configuration of the TFS Build Server

Creation a new VM in Azure. Select the option as shown below.

image

 

From the Gallery, we want to choose a server which has Visual Studio 2013 already installed. Click on next icon.

image

Configure the Virtual machine with it’s name and credentials. For this particular tutorial on Release Management, it is recommended to have minimum memory of 7 GB. Click on Next.

image

 

Let us leave the default as it is. Click on next.

image

Ensure “Install the VM Agent” is selected. Once this is done, Click on the tick icon to complete the creation of VM.

image

The next step is to download the installers for Team Foundation Server. The installers can be found here.

Once the installers are downloaded, we will proceed with the Team Foundation Server installation. Click on the tfs_server.exe. Accept the license terms and click on “Install Now”.

image

 

Select the basic installation of TFS. For our purpose, only basic installation of TFS is necessary. Click on “Start Wizard” to start the TFS installation wizard.

image

 

Click on Next.image

 

Install SQL Express since it is not available by default. Click on Next.image

 

Readiness check tells us that all is well. Click on “Configure” to proceed.

image

 

Team Foundation Server related setup succeeds.image

Click on “Close” to finish the setup of Team foundation Server.

image

 

Since the setup is complete, it is time to configure Team Foundation Server build. Open the Team Foundation Server Administration Console. Select Build Configuration and click on “Configure Installed features”.

image

Select “Configure Team Foundation Build Service”.  Click on “Start Wizard”

image

This opens up the Build Service Configuration wizard. Click on “Next”

image

 

Select the DefaultCollection and click on “Next”.

image 

 

Select “Use the default setting” and click on “Next”

image

 

Let TFS Build Service run as a System Account. By default it is configured to run as

NT AUTHORITY\LOCAL SERVICE. Click on Next.image

 

Click on Next for Readiness Checks.image

Build Configuration takes some time. Once it succeeds the following messages are shown. Click on Next.image

Click on Close.

image

 

Click on Build Configuration to see the Build Controller and Agent.

image

This completes the part 1 of the series Microsoft Release Management from scratch.

Tuesday, October 21st, 2014

I have been exploring Microsoft Release Management and I thought I will document the pain points which i went through while learning them it.

I will be starting from scratch here. Yes, absolutely from scratch! Right from spawning a new VM in Azure to the complete installation of Release Management.

These are the steps which we will follow to install Release Management

  1. Spawn a new VM in Azure.
  2. Install TFS with basic configuration
  3. Setup Build Controller
  4. Setup User Accounts for Release Management
  5. Install Release Management
    • Install Release Management Server
    • Install Release Management Client
    • Install Release Management Deployment Agent
  6. Configure Release Management Client
  7. Setup a Build Pipeline
  8. Trigger a release

Since, this is quite a long adventure I am documenting it in different parts.

Friday, October 17th, 2014

Transaction Commit Failure is another ground breaking feature that is available from EF 6.0.1 and above. While Connection Resilency handles the way to acquire connections !, Connection Resilency has no control on what happened with the connection, i.e the transaction succeeded with the connection or not. Here comes Transaction Commit Failure Feature to rescue.When an exception is raised during a transaction commit there are two possible causes:

  • The transaction commit failed on the server
  • The transaction commit succeeded on the server but a connectivity issue prevented the success notification from reaching the client

When the first situation happens the application or the user can retry the operation, but when the second situation occurs retries should be avoided and the application could recover automatically. The challenge is that without the ability to detect what was the actual reason an exception was reported during commit, the application cannot choose the right course of action. The new feature allows EF to double-check with the database if the transaction succeeded and take the right course of action transparently.So its very clear that, to put Second situation into practice, We would need to disable Connection Resilency temporarily.

To enable this feature, include the call to SetTransactionHandler(..) in the constructor of DbConfiguration., like below.

public class CustomConfiguration : DbConfiguration
    {
        public CustomConfiguration()
        {
            this.SetExecutionStrategy(SqlProviderServices.ProviderInvariantName, () => (IDbExecutionStrategy)new DefaultExecutionStrategy());

            this.SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler(c => new CustomTransactionContext(c)));
        }
    }

CommitFailureHandler is provided by EF out of the box, However other interesting class to note is CustomTransactionContext, inheriting from TransactionContext, provided by EF out of the box. Here is the definition of CustomTransactionContext

using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace ConsoleApplication1
{
    public class CustomTransactionContext : TransactionContext
    {
        public CustomTransactionContext(DbConnection existingConnection)
            : base(existingConnection)
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TransactionRow>().ToTable("TransactionHistory");
        }
    }
}

When the feature is enabled, EF will automatically add a new table to the database called “__Transactions”, which we renamed as “TransactionHistory”. A new row is inserted in this table every time a transaction is created by EF and that row is checked for existence if a transaction failure occurs during commit. If the row exists the exception will be ignored and the application will continue normally. If it does not then the exception is rethrown, triggering the retry logic for the failed operation.

using (var ctx = new StudentContext())
            {
                ctx.Database.Initialize(false);
                var commitHandler = CommitFailureHandler.FromContext(ctx);

                if (commitHandler != null)
                {
                    commitHandler.ClearTransactionHistory();
                }
                
                using (var transaction = ctx.Database.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    ctx.Students.Add(new Student()
                    {
                        Name = "Shashank",
                        Address = new Address() { AddressId = 121, AddressLine1 = "Bannerghatta Road", AddressLine2 = "JP Nagar Phase 4", AddressLine3 = "Near IIMB" },
                        DateOfBirth = new DateTime(1980, 1, 1)
                    });

                    ctx.Students.Add(new Student()
                    {
                        Name = "Meera",
                        Address = new Address() { AddressId = 131, AddressLine1 = "Behind Carlton Towers", AddressLine2 = "Old Airport Road", AddressLine3 = "Domlur" },
                        DateOfBirth = new DateTime(1982, 1, 1)
                    });

                    ctx.Students.Add(new Student()
                    {
                        Name = "Mohit",
                        Address = new Address() { AddressId = 141, AddressLine1 = "Inner Ring Road", AddressLine2 = "Near Sony Signal", AddressLine3 = "Eijapura" },
                        DateOfBirth = new DateTime(1986, 1, 1)
                    });

                    ctx.Students.Add(new Student()
                    {
                        Name = "Krishna",
                        Address = new Address() { AddressId = 181, AddressLine1 = "Old Airport Road", AddressLine2 = "Near Rajeswari Theatre", AddressLine3 = "Murghesh Palya" },
                        DateOfBirth = new DateTime(1984, 1, 1)
                    });

                    ctx.Students.Add(new Student()
                    {
                        Name = "Sai C",
                        Address = new Address() { AddressId = 191, AddressLine1 = "Behind KR Pural Railway Station", AddressLine2 = "Vijinapura", AddressLine3 = "Tin Factory" },
                        DateOfBirth = new DateTime(1986, 1, 1)
                    });

                    ctx.SaveChanges();

                    transaction.Commit();
                    
                }
            }

Once the above transaction is complete, EF inserts record in TransactionHistory table as below.
TransactionHistory

Category: .Net | Tags:  | Leave a Comment
Thursday, October 16th, 2014

In my previous blog posts on Connection Resilency, we went in to deep dive understanding what Connection Resilency is all about and possible work arounds for user initiated transactions. In this blog post,I am trying to address how to handle deadlocks and other timeout failures. When connection to sql server goes to deadlock, we need to provide mechanism of retrying to acquire a connection., Or when connection to sql server times out, we want to provide the mechanism of retrying. Inherit from DbExecutionStrategy and override methods to handle Retries as below. Since I am working with SqlServer, I know what error code sqlserver emits for Deadlock scenarios as below. Btw,These error codes may vary from one provider to another provider.

    public class SqlServerExecutionStrategy : DbExecutionStrategy
    {
        private readonly DateTime _establishTime;
        private readonly TimeSpan _maxDelay;
        public SqlServerExecutionStrategy()
        { }

        public SqlServerExecutionStrategy(int maxRetryCount, TimeSpan maxDelay)
        {
            this._establishTime = DateTime.UtcNow;
            this._maxDelay = maxDelay;
        }

        protected override bool ShouldRetryOn(Exception ex)
        {
            var sqlException = ex as SqlException;
            if (sqlException == null)
                return false; // donot retry

            foreach (var error in sqlException.Errors.Cast<SqlError>())
            {
                switch (error.Number)
                {
                    // Deadlock Error Code
                    case 1205:
                    // Timeout Error Code
                    case -1:
                    // Timeout Error Code
                    case -2:
                        return true; // retry
                }
            }

            return false;
        }

        protected override TimeSpan? GetNextDelay(Exception lastException)
        {
            return DateTime.UtcNow.Subtract(_establishTime.Add(this._maxDelay));
        }
    }

Now hook our SqlServerExecutionStrategy into our CustomConfiguration as below

public class CustomConfiguration : DbConfiguration
    {
        public CustomConfiguration()
        {
            this.SetExecutionStrategy("System.Data.SqlClient",()=>new SqlServerExecutionStrategy(1,TimeSpan.FromSeconds(30)));
        }

    }

You are done! Now if your application encounters any deadlock issues with sqlserver Or timeout issues, SqlServerExecutionStrategy will automatically hook into the pipeline to start retrying

Category: .Net | Tags:  | Leave a Comment
Wednesday, October 15th, 2014

In my previous blog post, we had a deep dive into Connection Resilency, In this post, I will be solving a problem – where we can control temporarily disable Connection Resilency for the cases where Retries does not make sense!. By default Entity Framework pushes all changes to database by using Transaction. If user initiates transaction, Entity Framework does not know, what are all subsequent deltas it needs to process post connection failure where retries come into action. In cases like this, where user initiates transaction, Suspend Execution Strategy would be handy.

using (var ctx = new StudentContext())
            {
                // Batch 1
                ctx.Students.Add(new Student()
                {
                    Name = "Shashank",
                    Address = new Address() { AddressId = 121, AddressLine1 = "Bannerghatta Road",AddressLine2 = "JP Nagar Phase 4", AddressLine3 = "Near IIMB"},
                    DateOfBirth = new DateTime(1980,1,1)
                });

                ctx.Students.Add(new Student()
                {
                    Name = "Meera",
                    Address = new Address() { AddressId = 131, AddressLine1 = "Behind Carlton Towers", AddressLine2 = "Old Airport Road", AddressLine3 = "Domlur" },
                    DateOfBirth = new DateTime(1982, 1, 1)
                });

                ctx.Students.Add(new Student()
                {
                    Name = "Mohit",
                    Address = new Address() { AddressId = 141, AddressLine1 = "Inner Ring Road", AddressLine2 = "Near Sony Signal", AddressLine3 = "Eijapura" },
                    DateOfBirth = new DateTime(1986, 1, 1)
                });

                ctx.SaveChanges();

                // Batch 2
                ctx.Students.Add(new Student()
                {
                    Name = "Krishna",
                    Address = new Address() { AddressId = 181, AddressLine1 = "Old Airport Road", AddressLine2 = "Near Rajeswari Theatre", AddressLine3 = "Murghesh Palya" },
                    DateOfBirth = new DateTime(1984, 1, 1)
                });

                ctx.Students.Add(new Student()
                {
                    Name = "Sai C",
                    Address = new Address() { AddressId = 191, AddressLine1 = "Behind KR Pural Railway Station", AddressLine2 = "Vijinapura", AddressLine3 = "Tin Factory" },
                    DateOfBirth = new DateTime(1986, 1, 1)
                });

                ctx.SaveChanges();
            }

In the above example, we are sending two batches to database, If it happens that first batch succeded and second batch failed, Entity Framework will be in no position to know where it has to start sending the batches to db i.e batch1 or batch2., In the cases like this, Suspend Execution Strategy will be useful, Remember: Suspend Execution is just a workaround, not a bullet proof solution.

public class SqlServerExecutionStrategy : DbExecutionStrategy
    {
        public SqlServerExecutionStrategy()
        { }

        public SqlServerExecutionStrategy(int maxRetryCount, TimeSpan maxDelay)
            : base(maxRetryCount, maxDelay)
        { }

        protected override bool ShouldRetryOn(Exception ex)
        {
            //TODO: Handle retries
        }
    }

Once I have SqlServerStrategy defined, all need to be done is hook this strategy in your code as below.

public class CustomConfiguration : DbConfiguration
    {
        public CustomConfiguration()
        {
            this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
              ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
              : new SqlServerExecutionStrategy(1,TimeSpan.FromSeconds(30)));
        }

        public static bool SuspendExecutionStrategy
        {
            get
            {
                return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
            }
            set
            {
                CallContext.LogicalSetData("SuspendExecutionStrategy", value);
            }
        }
    }

using (var ctx = new StudentContext())
            {
                CustomConfiguration.SuspendExecutionStrategy = true;

                // Batch 1
                // Insert 1
                // Insert 2
                // Insert 3

                ctx.SaveChanges();

                // Batch 2
                // Insert 4.......
                // Insert 5
                ctx.SaveChanges();

                CustomConfiguration.SuspendExecutionStrategy = false;
            }

With SuspendExecutionStrategy, we dont have to worry about transient failures!

Category: .Net | Tags:  | Leave a Comment
Tuesday, October 14th, 2014

Connection Resilency or Retry Logic is another ground breaking feature that is available from Entity Framework 6.0 +. Applications connecting to a database server have always been vulnerable to connection breaks due to Timeouts, Deadlocks and network instablitity leading to connection failure. This may not be a issue when database is on LAN and happens to be a big problem if the database server is on Cloud or out side the host network. Basically when the connection is opened, and query is executed on the database and in mean time, if the connection is lost, we would need to write lot of defensive code to reopen the connection and again execute the query, which is very much painful. Connection Resilency gives the ability to retry actions on a variety of failures automatically, minimizing the amount of defensive code and retry logic that is necessary to handle transient failures in common cloud data access scenarios. A user should be able to implement their own retry strategies and decide which exceptions should cause a retry and which should not.  Even though Connection Resilency is OFF by default, EF Runtime gives lot of information on transient failure exceptions. If for any reason, connection to data source is lost and retry limit is not reached, Entity Framework will still bubble up the exceptions in the same way as if Connection Resilency is disabled. Here are the possible operations that can be retried:

    • Executing an EF query:
    • On the DbContext API: DbSet, DbQuery
    • On the ObjectContext API: ObjectQuery (both for ESQL and LINQ to Entities) and CompiledQuery
    • Executing raw Sql:
    • On the DbContext API: SqlQuery and ExecuteSqlCommand
    • On the ObjectContext API: ExecuteStoreQuery and ExecuteStoreCommand
  • Invoking a stored procedure through ExecuteFunction
  • Calling SaveChanges on a DbContext or ObjectContext
  • Executing Migrations
  • Using Load or Reload on DbContext
  • Using Refresh on an ObjectContext

The capabilities of retry mechanism will be lost if you are using EntityClient in any form i.e using legacy EntityCommand

Entity Framework gives few connection resilency strategies out of the box:

  • DefaultExecutionStrategy:No retries, This default for databases other than SqlServer.
  • DefaultSqlExecutionStrategy: This execution strategy does not retry at all, however, it will wrap any exceptions that could be transient to inform users that they might want to enable connection resiliency.
  • DbExecutionStrategy: This class is suitable as a base class for other execution strategies. It implements an exponential retry policy, where the initial retry happens with zero delay and the delay increases exponentially until the maximum retry count is hit. This class has an abstract ShouldRetryOn method that can be implemented in derived execution strategies to control which exceptions should be retried.
  • SqlAzureExecutionStrategy: This execution strategy inherits from DbExecutionStrategy and will retry on exceptions that are known to be possibly transient when working with SqlAzure

In case you wish to have Connection Resilency in the way you want, all you need to do is implement interface IDbExecutionStrategy. Its very rare that you implement this interface, rather inherit from DbExecutionStrategy

Registering Execution Strategy:

public class CustomConfiguration : DbConfiguration
    {
        public CustomConfiguration()
        {
            SetExecutionStrategy(SqlProviderServices.ProviderInvariantName, () => new SqlAzureExecutionStrategy());
        }
    }

Or Incase you wish to query using a specific strategy temporarily for while, you can even do as below.

public class SqlServerExecutionStrategy : DbExecutionStrategy
    {
        public SqlServerExecutionStrategy()
        { }

        public SqlServerExecutionStrategy(int maxRetryCount, TimeSpan maxDelay)
            : base(maxRetryCount, maxDelay)
        { }

        protected override bool ShouldRetryOn(Exception ex)
        {
            //TODO: Handle how ever you wish to do retry
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            var sqlExecutionStrategy = new SqlServerExecutionStrategy(1, TimeSpan.FromSeconds(30));
            sqlExecutionStrategy.Execute(()=>GetStudent());
        }

        private static IEnumerable<Student> GetStudent()
        {
            using (var ctx = new StudentContext())
            {
                var students = ctx.Students.Where(x => x.Name == "Raghav");
                return students;
            }
        }
    }
Category: .Net | Tags:  | Leave a Comment
Saturday, October 11th, 2014

Command Interception is one of the “behind the scene” feature that’s been added with the release of Entity Framework 6.0. The high-level goal for the interception feature is to allow external code to observe and potentially intercept EF operations. The specific goal for EF6 is to allow generated SQL to be logged without using a wrapping provider. A sub-goal to this is to provide a simple way for applications to log generated SQL.
Interception Interfaces
The interception code is built around the concept of interception interfaces. These interfaces inherit from IDbInterceptor and define methods that are called when EF performs some action. The intent is to have one interface per type of object being intercepted. For example, the IDbCommandInterceptor interface defines methods that are called before EF makes a call to ExecuteNonQuery, ExecuteScalar, ExecuteReader, and related methods.
Let’s get started. In this case, i want to trace all sql queries emitted by EntityFramework to SqlServer. All you have to do is inherit from DbCommandInterceptor and override the appropriate methods.

public class CommandInterceptor : DbCommandInterceptor
    {
        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            base.ScalarExecuting(command, interceptionContext);
            LogQuery(command, interceptionContext.Exception);
        }

        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            base.NonQueryExecuting(command, interceptionContext);
            LogQuery(command, interceptionContext.Exception);
        }

        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            base.ReaderExecuting(command, interceptionContext);
            LogQuery(command, interceptionContext.Exception);
        }

        private static void LogQuery(DbCommand command, Exception exception)
        {
            if (exception != null)
            {
                Trace.TraceError(FormatException(exception, "Error executing command: {0}", command.CommandText));
            }
            else
            {
                Trace.TraceInformation(string.Format("Command: {0}", command.CommandText));
            }
        }

        private static string FormatException(Exception exception, string fmt, params object[] vars)
        {
            var sb = new StringBuilder();
            sb.Append(string.Format(fmt, vars));
            sb.Append(" Exception: ");
            sb.Append(exception.ToString());
            while (exception.InnerException != null)
            {
                sb.Append(" Inner exception: ");
                sb.Append(exception.InnerException.ToString());
                exception = exception.InnerException;
            }
            return sb.ToString();
        }
    }

Register the Interceptor
Inorder to consume Interceptor, we need to register the interceptor as below

DbInterception.Add(new CommandInterceptor());

Now that our interceptor is ready, F5 the application and you can see the queries in your output window interceptors

Category: .Net | Tags:  | Leave a Comment
Wednesday, October 08th, 2014

As much as we enjoy using Entity framework, we still have to be careful with the LINQ queries we write. Performance may be a big price we have to pay if the queries are not written efficiently.

I will take an example.

1.   var employeesWithIdLessThan100 = Repository.Employees.Where(e => e.EmployeeId < 100);

2.   if (employeesWithIdLessThan100.Any())

3.   {

4.   var employeeIds = employeesWithIdLessThan100.Select(x => x.EmployeeId);

5.  }

As much simple as the above code may seem, there is something really strange happening here.

employeesWithIdLessThan100.Any() in line 2 creates a query to get the count of the records and executes it. Also, in line 4, when we try to access the result employeesWithIdLessThan100 by selecting the field EmployeeId, a query is generated again to get the records. What we can infer here is that employeesWithIdLessThan100.Any() or employeesWithIdLessThan100.Count() does not bring the query result into memory.

Hence, there are two database hits, one at line 2 and one at line 5. Two database hits is a huge price to pay especially if the query is complex and the volume of data is huge. If it is a common practice to write queries this way, imagine the number of duplicate requests sent to the database again and again. This can be simply avoided by a minor tweak in the line 1.

1.   var employeesWithIdLessThan100 = Repository.Employees.Where(e => e.EmployeeId < 100).ToList();

2.   if (employeesWithIdLessThan100.Any())

3.   {

4.   var employeeIds = employeesWithIdLessThan100.Select(x => x.EmployeeId);

5.  }

As we already know, what .ToList() does is that it generates and executes a query with a database hit and brings the query result in memory and because of this there are no database hits at line 2 and 4. By only this change, we have reduced the number of database hits to half. This practice will help in better performance of our applications.

Category: .Net  | One Comment
Monday, September 29th, 2014

Including Windows PowerShell script as part of your build and deployment process, brings you the flexibility of easily and effectively customize your packaging and deployment process. With the proper combination of environment configuration files (XML) and PowerShell scripts you can achieve the impossible. This post will show you how to run Windows PowerShell scripts remotely from a TFS build process.

Using CredSSP for second-hop remoting

One common issue with PowerShell remoting is the “double hop” problem. When the scripts are executed remotely on a Server A and then it tries to connect from Server A to Server B, the second connection fails to send the credentials to that server. As a result the second server fails to authenticate the request and rejects the connection. To get around this issue you need to use the CredSSP authentication mechanism in PowerShell.
Credential Security Service Provider (CredSSP) is a new security service provider that is available through the Security Support Provider Interface (SSPI) in Windows. CredSSP enables an application to delegate the user’s credentials from the client (by using the client-side SSP) to the target server (through the server-side SSP). To setup the machines, for CredSSP you can follow the below given steps:
On the local computer that needs to connect to a remote server, execute the command Enable-WSManCredSSP -Role client -DelegateComputer *. This will  make the local computer role as client since so
that it can connect to remote computer which acts as server.

On the remote server run the command Enable-WSManCredSSP -Role server.

Remote execution of the PowerShell script from TFS build

For executing PowerShell scripts from the C# code you need to make use of the API’s in the System.Management.Automation.dll assembly. You can use the PowerShell instance directly but a better way is to create a Runspace instance. Every PowerShell instance works in a Runspace. You can have multiple Runspaces to connect to different remote hosts at the same time. To get the remote execution working properly you need to first construct an instance of WSManConnectionInfo and pass that on to the RunspaceFactory.CreateRunspace(..) method. You can use the following code snippet to construct the connection object.

private PSCredential BuildCredentials(string username, string domain, string password) {

    PSCredential credential = null;
    if (String.IsNullOrWhiteSpace(username))
    {
        return credential;
    }
    if (!String.IsNullOrWhiteSpace(domain))
    {
        username = domain + “\\” + username;
    }
    var securePassword = new SecureString();
    if (!String.IsNullOrEmpty(password))
    {
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
    }
    securePassword.MakeReadOnly();
    credential = new PSCredential(username, securePassword);
    return credential;
}
private WSManConnectionInfo ConstructConnectionInfo()
{
    //The connection info values are created after looking into the ouput of the command in the target machine
    /*
        * dir WSMan:\localhost\Listener\Listener_*\*
        * /
    //Output           

    /* 

        * Name                      Value                                                             Type
        * —-                      —–                                                             —-
        * Address                   *                                                                 System.String
        * Transport                 HTTP                                                              System.String
        * Port                      5985                                                              System.String
        * URLPrefix                 wsman                                                             System.String
        * 
        */

   const string SHELL_URI = http://schemas.microsoft.com/powershell/Microsoft.PowerShell;

    var credentials = BuildCredentials(“username”“domain”“password”);    var connectionInfo = new WSManConnectionInfo(false“remoteserver”, 5985, “/wsman”, SHELL_URI, credentials);    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Credssp;

    return connectionInfo;

}
Next you can use this connection object to pass it to the RunspaceFactory.CreateRunspace method and invoke the PowerShell script as given below.
var scriptOutput = new ScriptOutput();
var tfsBuildHost = new TFSBuildHost(scriptOutput);
var connection = ConstructConnectionInfo();
using (var runspace = RunspaceFactory.CreateRunspace(tfsBuildHost, connection)){
    runspace.Open();
    InvokePSScript(runspace, scriptOutput);
    runspace.Close();
}
private void InvokePSScript(Runspace runspace, ScriptOutput scriptOutput){
    using (var ps = PowerShell.Create())    {
        ps.Runspace = runspace;
        var commandToExecute = ConstructScriptExecutionCommand("path to script file""parameter1""parameter2");
        ps.AddScript(commandToExecute);
        try
        {            
var results = ps.Invoke();
            foreach (var result in results)
            {
                if (result.BaseObject != null)
                {
                    scriptOutput.WriteResults(result.BaseObject.ToString());
                }
            }
        }
        catch(Exception)
        {
            if (ps.InvocationStateInfo.State != PSInvocationState.Failed)
            {
                return;
            }
            scriptOutput.WriteError(ps.InvocationStateInfo.Reason.Message); 
        }
    }
}
You can also notice the TFSBuildHost object in the code. This class provides communications between the Windows PowerShell engine and the user. The implementation details are as given below.
internal class TFSBuildHost : PSHost{
    private ScriptOutput _output;
    private CultureInfo originalCultureInfo =         System.Threading.Thread.CurrentThread.CurrentCulture; 
    private CultureInfo originalUICultureInfo =         System.Threading.Thread.CurrentThread.CurrentUICulture;
    private Guid _hostId = Guid.NewGuid();
    private TFSBuildUserInterface _tfsBuildInterface;
    public TFSBuildHost(ScriptOutput output)
    {
        this._output = output;
        _tfsBuildInterface = new TFSBuildUserInterface(_output);
    }
    public override System.Globalization.CultureInfo CurrentCulture
    {
        get { return this.originalCultureInfo; }
    }
    public override System.Globalization.CultureInfo CurrentUICulture
    {
        get { return this.originalUICultureInfo; }
    }
    public override Guid InstanceId
    {
        get { return this._hostId; }
    }
    public override string Name
    {
        get { return "TFSBuildPowerShellImplementation"; }
    }
    public override Version Version
    {
        get { return new Version(1, 0, 0, 0); }
    }
    public override PSHostUserInterface UI
    {
        get { return this._tfsBuildInterface; }
    }
    public override void NotifyBeginApplication()
    {        _output.Started = true;    }
    public override void NotifyEndApplication()
    {
        _output.Started = false;
        _output.Stopped = true;
    }
    public override void SetShouldExit(int exitCode)
    {
        this._output.ShouldExit = true;
        this._output.ExitCode = exitCode;
    }
    public override void EnterNestedPrompt()
    {
        throw new NotImplementedException(
                "The method or operation is not implemented.");
    }
    public override void ExitNestedPrompt()
    {
        throw new NotImplementedException(
                "The method or operation is not implemented.");
    }
} 
internal class TFSBuildUserInterface : PSHostUserInterface{
    private ScriptOutput _output; 
    private TFSBuildRawUserInterface _tfsBuildRawUi = new TFSBuildRawUserInterface();
    public TFSBuildUserInterface(ScriptOutput output)    
   {
        _output = output;
    }
    public override PSHostRawUserInterface RawUI
    {
        get { return this._tfsBuildRawUi; }
    }
    public override string ReadLine()
    {        return Environment.NewLine;
    }
    public override void Write(string value)   
    {
        _output.Write(value);
    }
    public override void Write(
                                ConsoleColor foregroundColor,
                                ConsoleColor backgroundColor,
                                string value)
    {
        //Ignore the colors for TFS build process.
        _output.Write(value);
    }
    public override void WriteDebugLine(string message)
    {
        Debug.WriteLine(String.Format("DEBUG: {0}", message));
    }
    public override void WriteErrorLine(string value)
    {
        _output.WriteError(value);
    }
    public override void WriteLine()
    {
        _output.WriteLine();
    }
    public override void WriteLine(string value)
    {
        _output.WriteLine(value);
    }
    public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
    {
        //Ignore the colors for TFS build process.
        _output.WriteLine(value);
    }
}
internal class TFSBuildRawUserInterface : PSHostRawUserInterface{
    private ConsoleColor _backColor = ConsoleColor.Black;
    private ConsoleColor _foreColor = ConsoleColor.White;
    private Size _bufferSize = new Size(300, 900);
    private Size _windowSize = new Size(100, 400);
    private Coordinates _cursorPosition = new Coordinates { X = 0, Y = 0 };
    private Coordinates _windowPosition = new Coordinates { X = 50, Y = 10 };
    private int _cursorSize = 1;
    private string _title = "TFS build process"; 
    public override ConsoleColor BackgroundColor
    {
        get { return _backColor; }
        set { _backColor = value; }
    }
    public override Size BufferSize
    {
        get { return _bufferSize; }
        set { _bufferSize = value; }
    }
    public override Coordinates CursorPosition
    {
        get { return _cursorPosition; }
        set { _cursorPosition = value; }
    }
    public override int CursorSize
    {
        get { return _cursorSize; }
        set { _cursorSize = value; }
    }
    public override ConsoleColor ForegroundColor
    {
        get { return _foreColor; }
        set { _foreColor = value; }
    }
    public override bool KeyAvailable
    {
        get { return false; }
    }
    public override Size MaxPhysicalWindowSize
    {
        get { return new Size(500, 2000); }
    }
    public override Size MaxWindowSize
    {
        get { return new Size(500, 2000); }
    }
    public override Coordinates WindowPosition
    {
        get { return _windowPosition; }
        set { _windowPosition = value; }
    }
    public override Size WindowSize
    {
        get { return _windowSize; }
        set { _windowSize = value; }
    }
    public override string WindowTitle
    {
        get { return _title; }
        set { _title = value; }
    }
}