Monday 25 June 2012

Reading xml field in sql 2008

Reading XML in sql



XML data saved in database:


<ArrayOfCustomers xmlns:xsd="http://www.w3.org/2001/XMLSchema"        
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Customer>
       <ItemId>1</ItemId>
       <Value>Mr Smith</Value>
   </Customer>
   <Customer>
      <ItemId>2</ItemId>
      <Value>Mr Bloggs</Value>
   </Customer>
</ArrayOfCustomers>



 You can read the fiels such as

SELECT
   Cust.value('(ItemId)[1]', 'int') AS 'ItemID',
   Cust.value('(Value)[1]', 'Varchar(50)') AS 'Customer Name'
FROM
   dbo.Sales.CustomerList.nodes('/ArrayOfCustomers/Customer') AS AOC(Cust)
 
 
This will return
 
ItemID  Customer Name
   1         Mr Smith
   2         Mr Bloggs
 



























Wednesday 20 June 2012

MS Workflow behavior extensions do not execute

MS Workflow behavior extensions do not execute

I just came across behaviour problem where I wanted to use custom behaviour, but the behaviour did not execute. I have added behaviour extension as below:

To add behaviour you need to specify your behaviour:

        <behaviorExtensions>
          <add name="dummyLogging" type="dummy.Logging, dummy"/>
        </behaviorExtensions>


Where:
name: name how its refered to.
type:- "object name" + "," +   name of the namespace"

my web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>   
  </system.web>  
  <system.serviceModel>
      <extensions>
        <behaviorExtensions>
          <add name="dummyLogging" type="dummy.Logging, dummy"/>
        </behaviorExtensions>
      </extensions>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>


Solution:


Now what I was missing was, say to MS Workflow to execute the custom behaviour. In behaviour we need to activate the behaviour, otherwise it does not get triggered.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>   
  </system.web>  
  <system.serviceModel>
      <extensions>
        <behaviorExtensions>
          <add name="dummyLogging" type="dummy.Logging, dummy"/>
        </behaviorExtensions>
      </extensions>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <dummyLogging />         
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

Tuesday 19 June 2012

Adding service behaviour into MS Workflow

Basically you use an IServiceBehavior to add the extension and a BehaviorExtensionElement to add the IServiceBehavior.


public class StringWriterBehavior : IServiceBehavior
{
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        var host = (WorkflowServiceHost)serviceHostBase;
        host.WorkflowExtensions.Add<TextWriter>(() => new StringWriter());
    }
}

public class StringWriterElement : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(StringWriterBehavior); }
    }

    protected override object CreateBehavior()
    {
        return new StringWriterBehavior();
    }
}
And the config file:

<system.serviceModel>
  <extensions>
    <behaviorExtensions>
      <add name=“stringWriter“
           type="OrderService.StringWriterElement, MyWorkflowService"/>
    </behaviorExtensions>
  </extensions>
  <services>
    <service name="OrderWorkflow“
             behaviorConfiguration="OrderWorkflowBehavior">
    </service>
  </services>
  <behaviors>
    <serviceBehaviors>
      <behavior name="OrderWorkflowBehavior">
        <serviceMetadata httpGetEnabled="True"/>
        <stringWriter />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>



source:
http://social.msdn.microsoft.com/Forums/en-US/wfprerelease/thread/a9b45eaf-c8e2-444c-819d-e448868e68bb/

Monday 18 June 2012

Error: Validation failed for one or more entities. See 'Entity ValidationErrors' property

Entity Framework 4 - Entity ValidationErrors.


I have came across my application where I got nice little error:

 Error: Validation failed for one or more entities. See 'Entity ValidationErrors' property

When I read the exception it has told me nothing but there is an error.
I have wrapped my data access with following code below to find out what is going on.




try{
       
 dbContext.Users.Add(user);
 dbContext.SaveChanges();


}catch (DbEntityValidationException dbEx)
{
 foreach (var validationErrors in dbEx.EntityValidationErrors)
 {
   foreach (var validationError in validationErrors.ValidationErrors)
    {
      Trace.TraceInformation(
        "Property: {0} Error: {1}",
        validationError.PropertyName,
        validationError.ErrorMessage);
   }
 }
}


The source of this code is here:
http://stackoverflow.com/questions/5400530/validation-failed-for-one-or-more-entities-while-saving-changes-to-sql-server-da

Tuesday 12 June 2012

Examples of mocking with Rhino Moq


Mocking with Rhino


We have interface that we need to mock
 
public interface IDataAccess
    {
   public List<int> GetIds(int serviceId, int standAlone, int saveChanges);
}

We want to set response as List of integers.

var listOfIds = new List<int>(){1,2,3};

Now we need to mock it

            var mocks = new MockRepository();
            IDataAccess _dataAccess = mocks.StrictMock<IDataAccess>();
           
            Expect.Call(_dataAccess.GetIds(serviceId, null,null))
                .IgnoreArguments()
                .Return(listOfIds);
           
            mocks.ReplayAll();

mocks.ReplayAll(); => will set up the collection ready to expect the call and return chosen results


Mocking void method

 Expect.Call(()=>_className.SaveData(1, null)).IgnoreArguments();  

IgnoreArguments(): Ignores all arguments passed into the method.


VerifyAll Expectations

when we have method where we pass in any parametrs and want to verify that incoming parameters are same as we expect them to be we can go about it as follows:
We will set up what do we expect to be passed into the method. And after we will check if the method has been called. When we specify parameters we need to be precise what goes into the call. If we use wrong parameters the method will never be called.

 var mocks = new MockRepository();
int storeId=12;
list<items> values = new List<items>();

Expect.Call(() => _dataAccess.Store(storeId, values));

mocks.ReplayAll();

//Verification of method call
_dataAccess.VerifyAllExpectations();

Friday 8 June 2012

Tutorial Entity Framework 4.1 - Code First


I have been looking around how to implement Entity Framework 4.1  but I have not found any nice all in one tutorial

Installing Entity Framework into  your project using nuget command:

 Use command:
      Install-Package EntityFramework

This will command will refister nuget package with your active project. It will add configuration into your target location as follows.

App.config


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" 
             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, 
                   EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory 
             type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter 
             value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>


Definition of classes


 public class Blog
    {
        public int Id { getset; }
        public string Title { getset; }
        public List<Post> Posts { getset; } 
    }
    public class Post
    {
        public int Id { getset; }
        public string Title { getset; }
        public string Content { getset; }
        public virtual Blog Blog { getset; }
    }

Setting up DbContext



using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using EntityFrameworkCodeFirst;
 
namespace DatabLayer
{
    public class Context : DbContext
    {
        public Context()
            : base("defaultConnection")
        {
            // Get the ObjectContext related to this DbContext
            var objectContext = (this as IObjectContextAdapter).ObjectContext;
 
            // Sets the command timeout for all the commands
            objectContext.CommandTimeout = 120;
 
        }
        public DbSet<Blog> Blogs { getset; }
        public DbSet<Post> Posts { getset; }
    }
}



Program itself


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DatabLayer;
using EntityFrameworkCodeFirst;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                CreateBlog(); 
                GetNumberOfBlogs(); 
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
        private static void GetNumberOfBlogs()
        {
            var dbContext = new Context();
            Console.WriteLine("Number of existing records: {0}", dbContext.Blogs.Count());
        }
        
        private static void CreateBlog()
        {
            var blog = new Blog {Title = "testing"};
            var dbContext = new Context();
            dbContext.Blogs.Add(blog);
            dbContext.SaveChanges();
        }
    }
}



Note
If you have added new class and you have set up migrations. All changes are saved in table
"__Migrations"
In case that you edit configuration of database, EF will not let you proceed with you code saying that your migrations are not correct.
You can delete the table and it will let you continue as all records about migrations are there and it is compared to current configuration