Blog

  • Extract URL Information

    Extract URL Information

    To get information about the currently requested URL in ASP.NET use the Request.Url class. For example to extract the information from the URL http://www.example.com/myApp/myPage.aspx?myQs=14 the Request.Url class provides the following properties:

    Request.Url = "http://www.example.com/myApp/myPage.aspx?myQs=14"
    Request.Url.AbsolutePath: "/myApp/myPage.aspx"
    Request.Url.AbsoluteUri: "http://www.example.com/myApp/myPage.aspx?myQs=14"
    Request.Url.Authority: "www.example.com"
    Request.Url.DnsSafeHost: "www.example.com"
    Request.Url.Fragment: ""
    Request.Url.Host: "www.example.com"
    Request.Url.HostNameType: Dns
    Request.Url.IsAbsoluteUri: true
    Request.Url.IsDefaultPort: true
    Request.Url.IsFile: false
    Request.Url.IsLoopback: true
    Request.Url.IsUnc: false
    Request.Url.LocalPath: "/myApp/myPage.aspx"
    Request.Url.OriginalString: "http://www.example.com:80/myApp/myPage.aspx?myQs=14"
    Request.Url.PathAndQuery: "/myApp/myPage.aspx?myQs=14"
    Request.Url.Port: 80
    Request.Url.Query: "?myQs=14"
    Request.Url.Scheme: "http"
    Request.Url.Segments: {string[3]}
    Request.Url.UserEscaped: false
    Request.Url.UserInfo: ""
  • Entity Framework: StoreGeneratedPattern="Computed"

    Entity Framework: StoreGeneratedPattern="Computed"

    We recently had a problem where our fields with default values where not getting properly populated in the database during row creation. This can occur when the EDMX model is created in the designer and the default fields do not have their StoreGeneratedPattern property set to Computed or Identity.

    Easy enough to fix, simply open the model in the VS designer, select the field, open the properties view and make the required changes.

    However we have also seen a problem where these fields are still not getting set correctly even after this change has been applied. Looking into the EDMX model within an XML view we can see that in some cases the StoreGeneratedPattern=Computed property has been retained on the Entity, but removed from the EntitySet, for example:

    Entity: Product

    <entitytype name="Product">
    <key>
    <propertyref name="ProductId" />
    </key>
    <property name="ProductId" type="Int32" nullable="false"></property>
    <property name="ProductDescription" type="String" maxlength="30" fixedlength="false" unicode="false"></property>
    <property name="ProductType" type="String" maxlength="1" fixedlength="true" unicode="false"></property>
    <property name="EntityRowID" type="Guid" nullable="false" annotation:storegeneratedpattern="Computed"></property>
    <property name="EntityLastUpdated" type="DateTime" nullable="false" annotation:storegeneratedpattern="Computed"></property>
    <property name="EntityIsDeleted" type="Boolean" nullable="false" annotation:storegeneratedpattern="Computed"></property>
    </entitytype>
    

    EntitySet: Products

    The StoreGeneratedPattern has gone missing 😦

    <entitytype name="Products">
    <key>
    <propertyref name="ProductId" />
    </key>
    <property name="ProductId" nullable="false" type="Int32"></property>
    <property name="ProductDescription" type="String" unicode="false" fixedlength="false" maxlength="30"></property>
    <property name="ProductType" type="String" unicode="false" fixedlength="true" maxlength="1"></property>
    <property name="EntityRowID" nullable="false" type="Guid"></property>
    <property name="EntityLastUpdated" nullable="false" type="DateTime"></property>
    <property name="EntityIsDeleted" nullable="false" type="Boolean"></property>
    </entitytype>
    

    This has occurred on a lot of tables, and we don’t know how or why that has crept in. To fix this we have had to manually fix up the XML file for the EntitySets effected:

    <entitytype name="Products">
    <key>
    <propertyref name="ProductId" />
    </key>
    <property name="ProductId" nullable="false" type="Int32"></property>
    <property name="ProductDescription" type="String" unicode="false" fixedlength="false" maxlength="30"></property>
    <property name="ProductType" type="String" unicode="false" fixedlength="true" maxlength="1"></property>
    <property name="EntityRowID" nullable="false" type="Guid" storegeneratedpattern="Computed"></property>
    <property name="EntityLastUpdated" nullable="false" type="DateTime" storegeneratedpattern="Computed"></property>
    <property name="EntityIsDeleted" nullable="false" type="Boolean" storegeneratedpattern="Computed"></property>
    </entitytype>
    
  • The Art Of Unit Testing, TDD

    The Art Of Unit Testing, TDD

    My quote-of-the-day, regarding Test Driven Development:

    I am convinced that it [TDD] can work to your benefit, but it’s not without a price (time to learn, time to implement, and more). It’s definitely worth the admission price, though.

    Taken from the excellent The Art of Unit Testing: with Examples in .NET by Roy Osherove.

  • Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

    Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

    Unit testing is a tricky beast. As with all unit tests it is important to abstract any dependencies – so in the case of EF it’s the data persistence source. This must be handled carefully because EF creates a container that performs the interaction with the data source. Abstracting that container (via mocking or stubbing) is painfully hard.

    There are a few approaches for doing this, this is mine. I’m using the following tooling:

    The pattern uses the following DAL class structure (like a pseudo-repository pattern against an example Product database table):

    • ProductDataRepository: IProductDataRepository – A thin layer to EF, returns only IQueryable<T> types from raw EF lookups. No filters, sorting or other queries are applied here as this class is not unit testable. This class internal to the DAL assembly.
    • ProductRepository(IProductDataRepository repos) – Constructor takes an instance of the IProductDataRepository interface, and uses this for executing specific queries against the base IQueryable<T> values. This class is exposed for external calls. This is unit-tested.

    The unit tests can use Moles to stub an instance of IProductDataRepository (delegating the internal Get… methods to returning a hard coded collection of test data) that is then passed to the instance of ProductRepository under test.

    Looking at these classes from the bottom up, as an example:

    ProductDataRepository

    To Provide a thin layer that only returns IQueryable<T> (our example also filters out deleted rows):

    public class ProductDataRepository : IProductDataRepository {
    
    private MyDatabase_ModelContainer _model;
    protected internal MyDatabase_ModelContainer Model {
    get {
    if (_model == null) {
    _model = new MyDatabase_ModelContainer();
    }
    return _model;
    }
    }
    
    public IQueryable<product> GetProducts() {
    return Model.Products.Where(p => p.IsTombstoned == false);
    }
    }
    

    ProductRepository

    Core Requirement: Provide the implementation and execution of the data lookup. Consumes an instance of IProductDataRepository via constructor injection.

    public class ProductRepository{
    public ProductRepository() : this(new ProductDataRepository()) {
    }
    
    private IProductDataRepository _mRepository;
    public ProductRepository (IProductDataRepository iRepository) {
    _mRepository = iRepository;
    }
    
    public Product GetProduct(String productKey) {
    return mRepository.GetProducts().FirstOrDefault(p => p.ProductKey.Contains(productKey));
    }
    
    public List<Product> GetProducts (String productKey) {
    return mRepository.GetProducts().Where(p => p.ProductKey.Contains(productKey).ToList();
    }
    }
    

    So, we can see that this is making calls to:

    mRepository.GetProducts()

    Which returns an IQueryable<T> type, then implements required functionality:

    .Where(p => p.ProductKey.Contains(productKey))

    and then executes the Query:

    .ToList();

    GetProductsTest

    To test the ProductRepository we can create an instance and stub the IProductDataRepository. The mocking and standard setup is done in an abstract class, to provide reusability for other tests that may require this functionality:

        [TestClass]
    public abstract class ProductTestContext
    {
    private IProductDataRepository _dataRepository;
    private IProductDataRepository DataRepository
    {
    get {
    if (_dataRepository == null) {
    _dataRepository = new SIProductDataRepository() {
    GetProducts = () => Products.AsQueryable()
    };
    }
    return _dataRepository;
    }
    }
    
    private ProductRepository _ProductRepository;
    public ProductRepository ProductRepository
    {
    get {
    if (_ProductRepository == null) {
    _ProductRepository = new ProductRepository(DataRepository);
    }
    return _ProductRepository;
    }
    }
    
    private List<Product> _products;
    public List<Product> Products
    {
    get {
    if (_products == null) {
    _products = new List<Product>();
    
    for (int i = 1; i <= 9; i++) {
    _products.Add(new Product(){ ProductKey = "MyKey" + i });
    }
    }
    return _products;
    }
    }
    
    }
    

    So, here we can see the IProductDataRepository readonly property returns a stubbed instance new new SIProductDataRepository. This stub is generated by the Moles framework (see Moles documentation on how to do this). During the creation of this object we delegate the GetVouchers method to return the concrete (and hardcoded because this is a unit test) instance of Products.AsQueryable():

    GetProducts = () => Products.AsQueryable()

    The .AsQueryable() is essential to insure the instance of IProductDataRepository, that is used during the test, returns the same type as the instance used in the real world.

    Now our unit test class can inherit ProductTestContext and Arrange, Act and Assert the required tests easily:

        [TestClass]
    public class GetProductsTest : ProductTestContext
    {
    
    [TestMethod]
    public void GetSingleProduct()
    {
    // repeat the test for each instance in the test collection
    for (int i = 1; i <= 9; i++) {
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey" + i;
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var product = ProductRepository.GetProduct(goodProductKey);
    
    // Assert – make sure the correct product is returned from the stubbed data
    Assert.IsNotNull(product);
    Assert.IsTrue(product.ProductKey.Equals(goodProductKey));
    }
    }
    
    [TestMethod]
    public void GetIndivudalFilteredProducts()
    {
    // repeat the test for each instance in the test collection
    for (int i = 1; i <= 9; i++) {
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey" + i;
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var products = ProductRepository.GetProducts(goodProductKey);
    
    // Assert – make sure the correct products are returned from the stubbed data
    Assert.IsNotNull(products);
    Assert.IsTrue(products.Count == 1);
    }
    }
    
    [TestMethod]
    public void GetMultipleFilteredProducts()
    {
    // Expectation – all the results in the abstract Products collection should be returned
    var expectation = Products.Count;
    
    // Arrange – most of the Arrangement is done in the abstract
    var goodProductKey = "MyKey";
    
    // Act – on the abstract instance of ProductRepository,
    //            which is using the stubbed instance of ProductDataRepository
    var products = ProductRepository.GetProducts(goodProductKey);
    
    // Assert – make sure the correct products are returned from the stubbed data
    Assert.IsNotNull(products);
    Assert.AreEqual(expectation, products.Count);
    }
    }
    
  • Microsoft Mocking

    Microsoft Mocking

    As a .NET developer I don’t like using third party controls when there is tooling available from MS that will do the job I need. For example I prefer using the “baked in” MSTest suit as opposed to NUnit or MBUnit.

    The same is true for a mocking framework. I have tried with varying levels of success to implement licenced and open-source variants, for example;

    • JustMock
    • TypeMocks
    • Moq
    • Rhino

    Then I found Microsoft Moles (part of the Pex toolkit) from MS Research labs. These tools are not officially released not supported, but they have matured for a couple of years, and whilst not as fully featured as something like JustMock, it has enough functionality to do what I need – simple mocking and stubbing and delegation of methods and properties.

    With Moles I managed stub my data access repository (with a little refactoring) with very satisfactory results:Real World: Unit Testing Queries Against Entity Framework (EF) Model / Repositories

  • SoapUI Pro – Browser Component is Disabled (Win7 64)

    SoapUI Pro – Browser Component is Disabled (Win7 64)

    Recording web tests on Soap UI Pro won’t work in full-blown 64 Bit environments (64bit windows, SoapUI and JRE). This is due to incompatibility with the Mozilla browser engine. Updates are expected soon. This will except with the following message: “Browser Component is Disabled”

    In the mean time install the 32bit version from http://dl.eviware.com/4_0/soapUI-Pro-x32-4_0_0.exe

    For more information see: http://www.eviware.com/forum/viewtopic.php?f=2&t=7797&p=22648&hilit=disabled+browser#p22648

  • WCF Configuration

    WCF Configuration

    During the deployment of a WCF service to an HTTPS QA server recently had us stumped… The service didn’t respond, didn’t display any error messages and didn’t log any issues in the Windows Event Log.

    The issues turned out to be (as expected) a type in the configuration file, we had used;

    system.serviceModel/services/service/endpoint/behaviorName

    and this should have been;

    system.serviceModel/services/service/endpoint/behaviorConfiguration

    Grrr!!!

  • SSMS Trusted

    SSMS Trusted

    It is possible to run SQL Server Management Studio under the guise of another user account from the command line:

    runas /netonly /user:domain\user c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\ssms.exe

    The command line will request a password which (quite rightly!) cannot be entered into the command. Successful authentication will launch an instance of SSMS 2008. Lovely.

  • 10% Project Ideas

    10% Project Ideas

    So I have a ream of ideas and techs to look into… which one(s) first?…

    Technologies?

    • Continuous Integration
    • Web Unit Testing
    • Mocking
    • Prototyping
    • Android Dev
    • Atlassian Suite 

    Ideas / Concepts?

    • 10% Project Website
    • Team Holiday Planner
    • Room / Resource Booker
    • Travel Toiletries Website