• NHibernate basic 2 table example

    I’m slowly becoming intrigued by NHibernate and was playing around with it against AdventureWorks tonight.

     

    I came up with this basic 2 table tutorial using Employee and Contact.

     

    First, I created a wpf project for my user interface and I slapped a ListView on the main window like this:

    <Window x:Class="NHAdventureWorks.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="300" Width="300"

         Loaded="Window_Loaded">

        <Grid>

            <ListView x:Name="lvwEmployees">

                

            </ListView>

        </Grid>

    </Window>

     

    Then I hooked up the Loaded Event:

    private void Window_Loaded(object sender, RoutedEventArgs e)

            {

                this.lvwEmployees.ItemsSource = LoadEmployeesFromDatabase();

            }

     

    Then I added this code from the ‘hello world’ example in Manning’s “NHibernate in action” book:

            static ISession OpenSession()

            {

                if (factory == null)

                {

                    Configuration c = new Configuration();

                    //c.AddClass(typeof(Employee));

                    c.AddAssembly(Assembly.GetCallingAssembly());

                    factory = c.BuildSessionFactory();

                }

                return factory.OpenSession();

            }

            static ISessionFactory factory;

     

            static IList<Employee> LoadEmployeesFromDatabase()

            {

                using (ISession session = OpenSession())

                {

                    IQuery query = session.CreateQuery(

                    "from Employee as emp order by emp.Contact.LastName asc");

                    IList<Employee> foundEmployees = query.List<Employee>();

                    return foundEmployees;

                }

            }

     

    Then I declared my domain model classes Employee and Contact as such:

        internal class Employee

        {

            internal int EmployeeId;

            internal string LoginId;

            internal Contact Contact { get; set; }

            internal int ContactId;

            public override string ToString()

            {

                return string.Format("{0} : {1} {2}", LoginId, Contact.FirstName, Contact.LastName);

            }

     

        }

        internal class Contact

        {

            internal int ContactId;

            internal string FirstName;

            internal string LastName;

     

        }

     

    Then I had to do the NHibernate specific stuff. First I added an xml file to the project called Employee.hbm.xml and then changed it’s build action to “Embedded Resource” (VERY IMPORTANT)

    Then I added a Contact.hbm.xml file as well (also marked as Embedded Resource). Then their contents looked like this respectively:

     

    <?xml version="1.0"?>

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

    auto-import="true">

      <class name="NHAdventureWorks.Employee, NHAdventureWorks"

             table="HumanResources.Employee" lazy="false">

        <id name="EmployeeId"

            column="EmployeeID"

            access="field">

          <generator class="native" />

        </id>

        <property name="LoginId" access="field" column="LoginID"/>

        <many-to-one

          name="Contact"

          column="ContactID"

          class="NHAdventureWorks.Contact, NHAdventureWorks"

          not-null="true" />

      </class>

    </hibernate-mapping>

     

    <?xml version="1.0"?>

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"

    auto-import="true">

      <class name="NHAdventureWorks.Contact, NHAdventureWorks"

             table="Person.Contact"

             lazy="false">

        <id name="ContactId"

           column="ContactID"

           access="field">

          <generator class="native" />

        </id>

        <property name="FirstName" access="field" column="FirstName"/>

        <property name="LastName" access="field" column="LastName"/>

      </class>

    </hibernate-mapping>

     

    Of course there are some app.config settings that had to be put into place:

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

      <configSections>

        <section name="hibernate-configuration"

                 type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />

        <section name="log4net"

                 type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

      </configSections>

      <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

        <session-factory>

          <property name="connection.provider">

            NHibernate.Connection.DriverConnectionProvider

          </property>

          <property name="connection.driver_class">

            NHibernate.Driver.SqlClientDriver

          </property>

          <property name="connection.connection_string">

            Server=(local);database=AdventureWorks;Integrated Security=SSPI;

          </property>

          <property name="dialect">

            NHibernate.Dialect.MsSql2000Dialect

          </property>

          <property name="show_sql">

            false

          </property>

          <property name='proxyfactory.factory_class'>NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>

        </session-factory>

      </hibernate-configuration>

      <log4net>

        <appender name="ConsoleAppender"

        type="log4net.Appender.ConsoleAppender, log4net">

          <layout type="log4net.Layout.PatternLayout, log4net">

            <param name="ConversionPattern" value="%m" />

          </layout>

        </appender>

        <root>

          <priority value="WARN" />

          <appender-ref ref="ConsoleAppender" />

        </root>

      </log4net>

    </configuration>

    Full story

    Comments (0)

  • Scrum Starting Practices: Sprint Planning

    This may or may not be helpful to some people but i just wanted to do a walk-through of a typical sprint planning 'process' I just tried using with the current team I'm on. We have me (programmer/scrum master), a tester, a business person, a requirement writer, and various 'specialists' giving us hours here and there (mainframe, webservices, and database). I'm basically acting as scrum master and sometimes as 'product owner' in many regards. (generally the product owner situations i end up in are ones where the technical team must prioritize and the customer team does not care one way or another on the priority at that low of level)

    1. I fire up Breeze (it's basically like a Webex or typical desktop sharing utility)
    2. I get everyone connected so they can see my desktop.
    3. I launch scrumworks (our chosen tool for distributed scrum) - maybe you use a spreadsheet or story cards or whatever.
    4. I load up our PRD (product requirements document) for a particular project (usually to add to our existing 'evergreen' product)
    5. I read the first "Detailed Business Requirement" outloud or ask the team to read it on the their own. (usually they have their own copy of the word document.
    6. Create a backlog item in scrumworks that represents that requirement.
    7. Have a timeboxed discussion (i usually don't set a time limit because people already have a tough time speaking up, but if it goes on too long in silence i start asking specific people questions... like 'if you had this software in front of you and you were going to validate this requirement, what would you do?)
    8. Ask the QA people what they would plan on testing. Maybe ask the business what QA might have missed or vice versa.
    9. break down the feature/backlog item into tasks. In scrumworks i usually denote each task with a functional group and then the task. for example the backlog item might be "User can save their settings". The tasks would maybe be "Dev: build aspx page layout", "Dev: build model classes", "Dba: setup tables and sprocs", "QA: write test scripts", "QA: execute test scripts" "BIZ: user acceptance test"
    10. Once the tasks have been decomposed and estimated in 'ideal hours' i total that up and assign the backlog item that as the 'ideal hour' size. Yes most tasks can run concurrently but the point is getting a general 'complexity' or 'size' to it so i figure there's a bit of shwag to it anyhow.
    11. Ask the team if they have enough room to commit to this backlog item taking into consideration all the functional groups needed to get to "Done" on it.
    12. Add it to the Sprint or skip it depending on 10
    13. Repeat steps 5-12 as needed until no more backlog items can be committed to.
    14. Some requirements may need consolidated into one backlog item (for example if a requirement is Dependant on another, I put them together as one and see if it makes sense... sometimes then we split them back out if it makes sense to split them in a different way by 'features' instead of by layers of software)
    15. Revisit estimates on the next reasonable amount of backlog items or estimate any un-estimated backlog items in the product backlog.

    Full story

    Comments (0)

  • Why is my scrum team not reporting impediments?

    5 little things I have done to lose the scrum team’s trust

     

    1. Turned responsibility back solely on the individual reporting the impediment.
    2. Tell them that it’s ‘just the way things work’ at this company or otherwise keep status quo
    3. Lose track of open impediments. Fall through the cracks.
    4. Assign someone different work when they’re impeded
    5. Embarrass them for silly questions or use “but” language in front of peers.

     

    Things we can do to get people to report all impediments

    1. Take every single impediment seriously
    2. be genuinely concerned and interested. Note your body language.
    3. Write it down somewhere visible.
    4. Make the solution to every impediment clearly visible to the whole team
    5. Take personal responsibility to ‘facilitate’ a solution with ‘team accountability’
    6. Thank them for reporting the issue

    Full story

    Comments (0)

  • Making a custom mouse cursor in silverlight 3

    When you write games in silverlight you are going to want to make a custom mouse cursor. Maybe you want a gun cross hair or maybe an animated cursor of some sort. I’ve found no way to do this other than to turn off the cursor and hook an image up to the mouse move events.

     

    Basically let’s start with a silverlight application and change the Grid to a Canvas like this:

    <UserControl x:Class="MouseCursorReplacement.MainPage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">

        <Canvas x:Name="LayoutRoot">

           

        </Canvas>

    </UserControl>

     

    Now add a cursor representation as an image tag and point it to your new cursor file. In this case I’m using a cross hair. I make the ZIndex high so it floats on top of anything I put in.

    <UserControl x:Class="MouseCursorReplacement.MainPage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">

        <Canvas x:Name="LayoutRoot">

            <Image x:Name="CustomCursorImage" Source="cross.png" Canvas.ZIndex="100"/>

        </Canvas>

    </UserControl>

     

    Now go into your code behind and setup a load event and disable the cursor:

        public partial class MainPage : UserControl

        {

            public MainPage()

            {

                this.Loaded += new RoutedEventHandler(MainPage_Loaded);

                InitializeComponent();

            }

     

            void MainPage_Loaded(object sender, RoutedEventArgs e)

            {

                this.Cursor = Cursors.None;

            }

        }

     

    Now add a mouse move event and finally the code that will make the image move around as your new cursor.

            public MainPage()

            {

                this.Loaded += new RoutedEventHandler(MainPage_Loaded);

                this.MouseMove += new MouseEventHandler(MainPage_MouseMove);

                InitializeComponent();

            }

     

            void MainPage_MouseMove(object sender, MouseEventArgs e)

            {

                Point position = e.GetPosition(LayoutRoot);

                double leftOffset = CustomCursorImage.ActualWidth / 2;

                double topOffset = CustomCursorImage.ActualHeight / 2;

                double newLeft = position.X - leftOffset;

                double newTop = position.Y - topOffset;

                Canvas.SetLeft(CustomCursorImage, newLeft);

                Canvas.SetTop(CustomCursorImage, newTop);

            }

     

    The last part. And I find this a little ‘magical’ is that when the background was white the mouse kept “losing” the new cursor. So I changed the background to classic ‘directx’ cornflowerblue and the problem went away (I don’t know why and believe me I don’t usually fall for the ‘it must be magic’ comment, but apparently it works?):

     

    <UserControl x:Class="MouseCursorReplacement.MainPage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">

        <Canvas x:Name="LayoutRoot" Background="CornflowerBlue">

            <Image x:Name="CustomCursorImage" Source="cross.png" Canvas.ZIndex="100"/>

        </Canvas>

    </UserControl>

     

     

    Full story

    Comments (0)

  • Some TDD in the real world

    One of the most common things that I run into when doing TDD with NUnit in the 'real world' is that the ugly truth is dependencies are either hard or impossible to test.

     

    Take for example this code snippet where we're calling a webservice a couple times to do some work.

        public class HumanResources

     

        {

            public void FireThisGuy(long employeeId)

            {

                HumanResourcesService service = new HumanResourcesService();

                GetEmployeeRequest request = new GetEmployeeRequest();

                request.EmployeeId=employeeId;

                Employee emp = service.GetEmployee(request).Employee;

                emp.TerminationDate = DateTime.Now;

     

                SetEmployeeRequest setRequest = new SetEmployeeRequest();

                setRequest.Employee = emp;

                service.SetEmployee(setRequest);

            }

        }

     

     

     

     

     

    We know it's a bad practice to call webservices in our unit tests for a few reasons. (namely it's slow). So let's refactor a little and remove anything related to the webservices out. I extract method on the get...

           public void FireThisGuy(long employeeId)

            {

                Employee emp = GetEmployeeById(employeeId);

                emp.TerminationDate = DateTime.Now;

     

                HumanResourcesService service = new HumanResourcesService();

                SetEmployeeRequest setRequest = new SetEmployeeRequest();

                setRequest.Employee = emp;

                service.SetEmployee(setRequest);

            }

     

            protected Employee GetEmployeeById(long employeeId)

            {

                Employee emp;

                HumanResourcesService service = new HumanResourcesService();

                GetEmployeeRequest request = new GetEmployeeRequest();

                request.EmployeeId=employeeId;

                emp = service.GetEmployee(request).Employee;

                return emp;

            }

     

    notice this wasn't a straight up 'extract to method' on your refactoring tool. I did about 5 small refactorings before i did the extract but just notice the complete extraction of the dependency on the webservice to a new method "GetEmployeeById".

     

    now the same for the set:

     

           public void FireThisGuy(long employeeId)

            {

                Employee emp = GetEmployeeById(employeeId);

                emp.TerminationDate = DateTime.Now;

                SetEmployee(emp);

            }

     

            protected void SetEmployee(Employee emp)

            {

                HumanResourcesService service = new HumanResourcesService();

                SetEmployeeRequest setRequest = new SetEmployeeRequest();

                setRequest.Employee = emp;

                service.SetEmployee(setRequest);

            }

     

            protected Employee GetEmployeeById(long employeeId)

            {

                Employee emp;

                HumanResourcesService service = new HumanResourcesService();

                GetEmployeeRequest request = new GetEmployeeRequest();

                request.EmployeeId=employeeId;

                emp = service.GetEmployee(request).Employee;

                return emp;

            }

     

    now for my unit test the only thing i really want to test is the "FireThisGuy" logic. so first i would need to inherit from HumanResources and make a testing class that overrides the 2 dependencies i do not want.

        public class HumanResources

        {

            public void FireThisGuy(long employeeId)

            {

                Employee emp = GetEmployeeById(employeeId);

                emp.TerminationDate = DateTime.Now;

                SetEmployee(emp);

            }

     

            protected virtual void SetEmployee(Employee emp)

            {

                HumanResourcesService service = new HumanResourcesService();

                SetEmployeeRequest setRequest = new SetEmployeeRequest();

                setRequest.Employee = emp;

                service.SetEmployee(setRequest);

            }

     

            protected virtual Employee GetEmployeeById(long employeeId)

            {

                Employee emp;

                HumanResourcesService service = new HumanResourcesService();

                GetEmployeeRequest request = new GetEmployeeRequest();

                request.EmployeeId=employeeId;

                emp = service.GetEmployee(request).Employee;

                return emp;

            }

        }

        public class TestingHumanResources : HumanResources

        {

            public Employee GetEmployeeByIdTestingEmployee { get; set; }

            protected override Employee GetEmployeeById(long employeeId)

            {

                return GetEmployeeByIdTestingEmployee;

            }

     

            public Employee SetTestingEmployee { get; set; }

            protected override void SetEmployee(Employee emp)

            {

                SetTestingEmployee = emp;

            }

        }

     

     

     

     

     

     

     

     

     

    Now i can actually write a test that validates

      public class HumanResources

        {

            public void FireThisGuy(long employeeId)

            {

                Employee emp = GetEmployeeById(employeeId);

                emp.TerminationDate = DateTime.Now;

                SetEmployee(emp);

            }

     

            protected virtual void SetEmployee(Employee emp)

            {

                HumanResourcesService service = new HumanResourcesService();

                SetEmployeeRequest setRequest = new SetEmployeeRequest();

                setRequest.Employee = emp;

                service.SetEmployee(setRequest);

            }

     

            protected virtual Employee GetEmployeeById(long employeeId)

            {

                Employee emp;

                HumanResourcesService service = new HumanResourcesService();

                GetEmployeeRequest request = new GetEmployeeRequest();

                request.EmployeeId=employeeId;

                emp = service.GetEmployee(request).Employee;

                return emp;

            }

        }

        public class TestingHumanResources : HumanResources

        {

            public Employee GetEmployeeByIdTestingEmployee { get; set; }

            protected override Employee GetEmployeeById(long employeeId)

            {

                return GetEmployeeByIdTestingEmployee;

            }

     

            public Employee SetTestingEmployee { get; set; }

            protected override void SetEmployee(Employee emp)

            {

                SetTestingEmployee = emp;

            }

        }

        [TestFixture]

        public class HumanResourcesTests

        {

            [Test]

            public void FireThisGuy_UserIdIn_FiredEmployeeSaved()

            {

                TestingHumanResources hr = new TestingHumanResources();

                hr.GetEmployeeByIdTestingEmployee = new Employee();

                hr.GetEmployeeByIdTestingEmployee.TerminationDate = null;

     

                hr.FireThisGuy(200);

                Assert.IsNotNull(hr.SetTestingEmployee.TerminationDate);

     

            }

        }

     

     

     

     

     

     

     

     

     

     

     

     

     

    This is why im a big fan of object oriented programming and using inheritance to break dependencies. It's a real fast solution to some of the unique dependency issues i fight every day and it is a lot easier to read and debug than tons of interfaces.  This and other examples of seaming and seperation can be found in Michael Feather's book "Working Effectively with Legacy Code"

     

     

     

     

    Grab the code here

    Full story

    Comments (10)