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();