AgileDotNet is Coming!!! Are you registered?

19. January 2012

AgileDotNet is a .NET centered agile conference that covers a wide band of topics ranging from leadership and adoption techniques to tools and development practices. It is a must see for every person interested in Agile, from the new comer trying to figure out what it is, to the experienced pro looking for some best practices.

I am speaking on Database Development for Agile teams, and there are a swath of great speakers on many other great topics!

Full details can be found here -- http://www.agiledotnet.com/

Hope to See you there!

 

AgileDotNet is brought to you by:

Improving Enterprises Microsoft

Community

How to constrain mocks for use with Complex Types

19. January 2012

Here are some tests to illustrate how to leverage RhinoMocks constraints. Notice that it is easier to get a passing test on failing code with a stub. The Strict mock will enforce the expectations at the time of the call, where the stub will only throw an exception on an AssertWasCalled. Due to this I would recommend that you explicitly do your setup and use strict mocks, or make sure to have the discipline to test those assertions.

 

With the method Matches() ,you can use any predicate or method call that returns a boolean. You cannot however use a lambda with a method body aka () =>{}. This will not compile.

[TestClass]

public class Tests

{

[TestMethod]
        public void Should_Allow_Constraint()
        {
            //Arrange
            var mock = MockRepository.GenerateStrictMock<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.First() is Test))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoIt();

            //Assert
            mock.VerifyAllExpectations();
            Assert.AreEqual("TestPass",result);
        }

        [TestMethod]
        public void Should_Enforce_Constraint_On_Strict_Mock()
        {
            //Arrange
            var mock = MockRepository.GenerateStrictMock<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.Any(t=> t is Test)))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoItWrong();

            //Assert
            mock.VerifyAllExpectations();
            Assert.AreEqual("TestPass", result);
        }

        [TestMethod]
        public void Should_Allow_Manual_Enforce_Constraint_On_Stub()
        {
            //Arrange
            var mock = MockRepository.GenerateStub<ITestExerciser>();
            mock.Expect(x => x.DoSomething(Arg<List<ITest>>.Matches(c => TestSomething(c)))).Return("TestPass");
            var tester = new Tester(mock);
            //Act
            var result = tester.DoItWrong();

            //Assert
            mock.AssertWasCalled(x => x.DoSomething(Arg<List<ITest>>.Matches(c => c.Any(t => t is Test))));
            Assert.AreEqual("TestPass", result);
        }

        private bool TestSomething(List<ITest> tests)
        {
            return true;
        }
    }

    public class Tester
    {
        private ITestExerciser _testExerciser;

        public Tester(ITestExerciser testExerciser)
        {
            _testExerciser = testExerciser;
        }

        public object DoIt()
        {
            return _testExerciser.DoSomething(new List<ITest>() {new Test()});
        }

        public object DoItWrong()
        {
            return _testExerciser.DoSomething(new List<ITest>() { new TestBase() });
        }
    }

    public class TestExerciser : ITestExerciser
    {
        public object DoSomething(List<ITest> args)
        {
            return null;
        }
    }

    public interface ITestExerciser
    {
        object DoSomething(List<ITest> args);
    }

    public class Test : TestBase
    {
       
    }

    public class TestBase : ITest
    {
        public int Id { get; set; }
    }

    public interface ITest
    {
        int Id { get; set; }
    }

C#, C# Helpful Functions, Testing, Unit Testing, RhinoMocks

Concurrency and Locking in Entity Framework

29. December 2011

So I was talking to a friend this afternoon and the question of how Entity Framework handles locking came up. It is important to know that no pessimistic locking exists in Entity framework. Save Changes uses implementation of DbTransaction for current store provider. It means that default transaction isolation level is set to default value for the database server. In SQL Server it is Read Committed.

Make sure you look at how the tables are defined when it comes to lock levels and how the server you are using is configured.

 

Here are the details that I pointed him to.

http://msdn.microsoft.com/en-us/library/ms184286.aspx

http://msdn.microsoft.com/en-us/library/bb738618.aspx

 

Enjoy.

Tulsa Tech Fest 2011

10. October 2011

Thank you to everyone who attended my talks, it was great. We had a great time. The talk on data access architecture had great feedback and interaction. If you came here looking for code the link is below. Enjoy.

http://db.tt/O5ajHj7N

Houston DNUG Presentation

9. September 2011

Great crowd at the Houston DNUG tonight!! Over 110 in attendance.

Great Questions from the group during the talk. I especially like the follow ups. Thank you all for attending. Below is a link to the code you saw tonight.

http://db.tt/oJFvvrf

Here are those EF links

http://archive.msdn.microsoft.com/EFExtensions

http://www.codeproject.com/KB/database/CodeFirstStoredProcedures.aspx

For everyone interested in how to specify unique constraints that are not keys, please check this out.

http://stackoverflow.com/questions/4413084/unique-constraint-in-entity-framework-code-first

This is very similar to how we talked about adding cascade delete to foreign keys.

Thanks again, look forward to seeing you all at Houston TechFest!

Entity Framework, Community, Data Access

Dallas TechFest 2011–Awesome Conference!

15. August 2011

This was a great conference. Tim Rayburn puts on one great show and the free sushi after party!!

 

 

For those that are hunting my presentation zips for code here they are.

Thank you all for attending, two packed rooms and some great questions.

Now for the Guy that I don’t know with the great question about single user mode, you were right! Here is the stack overflow link for that answer.

http://stackoverflow.com/questions/5288996/database-in-use-error-with-entity-framework-4-code-first

 

Architecture and EF not the odd couple

http://db.tt/m4teLVI

EF Code First Goodness

http://db.tt/Du99mJm

Reverse Engineer Code First–Jump start for existing Databases

30. May 2011

I know that we have all hit that point where we are going into a project, it has existing database structure and some old ADO.NET hand built data access layer. We think maybe this would be a great place for Entity Framework, and then we find that the business objects are serialized over WCF, or that they are somehow used in a way that makes standard EF cry. This is where we have that internal debate on if our boss will accept a week of writing code just to get code first running, not to solving the problem. In comes the EF Power Toys.

 

Just start up a new project in Visual Studio.

image

With nuget type Install-Package EntityFramework ( this avoids a bug later )

Right click the project and select Entity Framework Reverse Engineer Code first

image 

Punch in your connection information

image

Then watch the bottom left side status messages, it will load schema information, create objects and configuration for them.

You should now have a context, an entities folder, and a mappings folder.

image

This includes every entity in the database and a mapping for every property. It doesn’t leave off properties that could have taken advantage of convention.

You can use this the same way you used a code first context before.

Enjoy.

Data Access, Entity Framework, Productivity, Visual Studio 2010

Using Fluent Configuration with Entity Framework 4.1

24. May 2011

I have gotten the question several time over the last few weeks and usages for the fluent configuration of Code First POCO classes where the database does not match the convention. Here is a simple example on how to address this.

Take a product for example.

public class Product
   {
       public int ID { get; set; }
       public string Name { get; set; }
       public string ProductNumber { get; set; }
       public bool MakeFlag { get; set; }
   }

To configure this to use different column names for the properties you simply need to add a configuration for that class like so.

public class ProductConfiguration : EntityTypeConfiguration<Product>
   {
       public ProductConfiguration()
       {
           this.ToTable("Product","Production");
           this.HasKey(x => x.ID);
           this.Property(x => x.ID).HasColumnName("ProductID");
       }
   }

Notice how the inheritance tells it which class it is setting up a type configuration for.

Then you load the configuration to the context in an override like so.

public class AdventureWorkContext : DbContext
    {
        public AdventureWorkContext(string adventureWorks)
            : base(adventureWorks)
        {
            this.Database.CompatibleWithModel(false);
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ProductConfiguration());
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Product> Products { get; set; }

}

Entity Framework, Data Access

Dallas Tech Fest 2011–Call for Speakers Open

17. May 2011

Dallas TechFest 2011 has opened the Call For Speakers at our new website.  In order to submit sessions you must register on the website, complete your speaker profile, and then you will be able to add sessions.  We expect the end the call for speakers in early June, so please submit soon!

Dallas TechFest 2011 is a multi-day, multi-disciplinary technology conference focused on software development and IT professionals.  It will be held on August 12th and 13th 2011 at the University of Texas at Dallas.  We are interested in anything related to these subjects as talks, regardless of technology.  We have had talks covering everything from iPhone to Java, .NET to Android.

Twitter Tag : #dtf11
Twitter Account : @DallasTechFest

Check it out at http://dallastechfest.com and http://timrayburn.net/

Community

Dynamic Sort With LINQ

13. May 2011

We have all at one time or another gotten a user request for sorts based on columns. If that is a pre-built control it most likely has this, and if it is home grown then it will probably need some work. You could write a sort for every column or you could write on that takes the column name in and sorts based on a string. LINQ however doesn’t like this. If you want string based sorting then you must do either a really nasty case statement or use a sort extension like this one.

 

public static class LinqSortExtensions
{
    private const string Ascending = "ASC";

    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property, string dirrection)
    {
        return dirrection == Ascending ? source.OrderBy(property) : source.OrderByDescending(property);
    }

    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder(source, property, "OrderBy");
    }
    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
    {
        return ApplyOrder(source, property, "OrderByDescending");
    }
    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property, string dirrection)
    {
        return dirrection == Ascending ? source.ThenBy(property) : source.ThenByDescending(property);
    }
    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder(source, property, "ThenBy");
    }
    public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
    {
        return ApplyOrder(source, property, "ThenByDescending");
    }
    static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
    {
        var props = property.Split('.');
        var type = typeof(T);
        var arg = Expression.Parameter(type, "x");
        Expression expr = arg;
        foreach (var pi in props.Select(prop => type.GetProperty(prop)))
        {
            expr = Expression.Property(expr, pi);
            type = pi.PropertyType;
        }
        var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
        var lambda = Expression.Lambda(delegateType, expr, arg);

        var result = typeof(Queryable).GetMethods().Single(
                method => method.Name == methodName
                        && method.IsGenericMethodDefinition
                        && method.GetGenericArguments().Length == 2
                        && method.GetParameters().Length == 2)
                .MakeGenericMethod(typeof(T), type)
                .Invoke(null, new object[] { source, lambda });
        return (IOrderedQueryable<T>)result;
    }

 

This allows you to pass in a property name and a direction. It allows for multiple sorts, and in case some out there want them, here are the unit tests too..

 

[TestFixture]
    public class QueryTests
    {

        [Test]
        public void CanSortWithOnlyStrings()
        {
            IQueryable<TestObject> items = new List<TestObject>()
                            {
                                new TestObject(){id = 1, Test = "Test1"},
                                new TestObject(){id = 3, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test2"},
                               
                            }.AsQueryable();

            Assert.AreEqual(2, items.OrderBy("id", "ASC").ToArray()[1].id);
        }

        [Test]
        public void CanSortDescendingWithOnlyString()
        {
            IQueryable<TestObject> items = new List<TestObject>()
                            {
                                new TestObject(){id = 1, Test = "Test1"},
                                new TestObject(){id = 3, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test2"},
                               
                            }.AsQueryable();

            Assert.AreEqual(1, items.OrderBy("id", "DSC").ToArray()[2].id);

        }

        [Test]
        public void CanSortMultipleTimesAscending()
        {
            IQueryable<TestObject> items = new List<TestObject>()
                            {
                                 new TestObject(){id = 1, Test = "Test1"},
                                new TestObject(){id = 3, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test2"},
                                new TestObject(){id = 2, Test = "Test1"}
                               
                            }.AsQueryable();
            var item = items.OrderBy("id", "ASC").ThenBy("Test", "ASC").ToArray()[3];
            Assert.AreEqual("Test3", item.Test);
        }

        [Test]
        public void CanSortMultipleTimesWithMultipleDirrections()
        {
            IQueryable<TestObject> items = new List<TestObject>()
                            {
                                new TestObject(){id = 1, Test = "Test1"},
                                new TestObject(){id = 3, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test3"},
                                new TestObject(){id = 2, Test = "Test2"},
                                new TestObject(){id = 2, Test = "Test1"}
                               
                            }.AsQueryable();
            var item = items.OrderBy("id", "ASC").ThenBy("Test", "DSC").ToArray()[3];
            Assert.AreEqual("Test1", item.Test);

        }
    }

    public class TestObject
    {
        public int id { get; set; }
        public string Test { get; set; }
    }

Enjoy