Hi, welcome to my canvas for development, design, and pure randomness. Chances are that you stumbled onto this fancy shpancy blog looking for information. Hope you found it! If not, did you know that I tend to post free templates, logo designs, and code here? Take a look, and enjoy your day.

Thoughts on Adobe’s and Apple’s thoughts.

June 5, 2010

CS5 and Apple

Apple, Adobe, large innovative brand names, both lacking and exceeding our expectations. I believe that both companies are completely full of themselves. As, someone who spends most of his time developing in the Microsoft world, and designing in the Apple world, I have some strong opinions on all these recent strong opinions by the big boys.

Flash and HTML5

First of all as a technology user, I like flash, it’s just flipping cool, I do want it on my phone, gaming system, and laptop. It provides a great experience. I also love HTML5 and where it’s going. It will be really amazing when it will be fully adopted across all the major browsers. Developing in it already is really great.

It’s the developers’ job to make these products interact correctly with your hardware and software. We love doing it, its fun. When someone tells us it can’t be done, we jump over mountains to prove that it can, it’s in our very nature. Adobe and Apple developers are no exception.

However, consumers are used to believing what they are told. Steve Job’s says no, Kevin Lynch says yes. Who’s Kevin Lynch? I’ll just listen to Steve, he’s never been wrong before, right?

Apple

The truth is, Apple isn’t giving us a choice. Steve Job’s uses the word “Open” a lot in his “Thoughts on Flash” but he fails to mention why so many users utilizing Apple products resort to hacking and jailbreaking Apple’s software. The truth is the consumers haven’t really told Apple they don’t like being babied; they want to make their own decisions. Apple, is going to keep using this to their advantage, because it just simply works. If I had one thing to say to Jobs, I would say without Adobe’s products the Mac would not have survived as long as it has.

Adobe

Adobe is also no exception, to the blame game. First of all, if Adobe thinks it can demonstrate flash working well on mobile devices like the iphone, they should have shown it to the consumers. Consumers love products and services, they will fight for Adobe if they see a fight worth fighting. Second, if Adobe wants flash to survive, its time to fully open up the source to all of your versions of flash, it’s going to be hard, a lot of people are going to scream, but flash will improve drastically. I wish I could say Adobe wouldn’t have survived with Apple, but its been doing fine on the PC.

Conclusion

I want both Apple and Adobe to grow into strong companies, that not only think of their consumers as targets, but as people who can take their products and make them better. This involves a lot of sharing and finger pointing, but it also allows for a lot of growing and happier people.

What do you think?

Starting NHibernate | Mapping Tables to Objects

April 21, 2010

Part one: Starting NHibernate – Adding DLLs

As promised from the previous post, let’s start with setting up a domain object and mapping it to your database with NHibernate.

We left off with a project, configured with NHibernate and are ready to roll! Let’s grab a table and map it. Let’s pretend we are working on a banking system, and we have a Person Table and that person is linked to several different Bank Accounts. It would look something like this, for starters:

personTable
Person [(PK, FK)personId, firstName, lastName]

Ok, I have a really simple table what’s next? Let’s create a “Domain Object”, what’s so special about a domain object? The answer is nothing, it’s just a plain old POCO (plain old CLR object) that represents your Database Table. In our case, the Person Table:

namespace MyProject.Domain.Models
{

	public class Person
	{
		public virtual int Id { get; set; }
		public virtual string FirstName { get; set; }
		public virtual string LastName { get; set; }
		public virtual IList<BankAccount> BankAccounts { get; set; }

	}
}

Now, you are looking at Person.cs, in your Domain project under the Models folder/namespace. You have two questions: Why is everything virtual? Why do we have a list of BankAccount Objects?

The dumb answer to the first question is because Nhibernate will throw a “NHibernate.InvalidProxyTypeException“. This goes for anything that is exposed outside of your Object. The fastest answer I can give you is, in order to lazily load your objects. Many blogs already cover why, I recommend reading Davy Brion’s Blog post: Must everything be virtual with nhibernate?.

The second question, what’s up with the List on BankAccounts, can be answered quite quickly. In this case we have a one to many relationship, we have one Person, and many Bank Accounts with that person on them. Let’s make our person a bit more robust before starting our first mapping file.

namespace MyProject.Domain.Models
{

	public class Person
	{
		private readonly IList<BankAccount> _bankAccounts;
		public Person()
		{
			_bankAccounts = new List<BankAccount>();
		}

		public virtual int Id { get; set; }
		public virtual string FirstName { get; set; }
		public virtual string LastName { get; set; }
		public virtual IList<BankAccount> BankAccounts
		{
			get { return _bankAccounts;}
		}

		public virtual void AddBankAccount(BankAccount bankAccount)
		{
			_bankAccounts.Add(bankAccount);
		}

	}
}

What we have done here is interesting; we made the BankAccounts Property readonly, instantiated it in the constructor, and added a method called AddBankAccount (so you could still add BankAccounts to your Person). Notice the method is virtual. But then, how does NHibernate set the BankAccounts? For this we need to Map our Object to the Database.

To start out I prefer to make a folder specifically for my mapping files, our Person is in: MyProject.Domain.Models, so I will place my mappings in MyProject.Domain.Mappings. A mapping file again is just an xml file with a fancy file extension (*.hbm.xml). So let’s create Person.hbm.xml, in Domain/Mappings.




Ok, we are ready now, notice the namespace is where your Domain Objects are, and the assembly is the same as your nhibernate.config, assembly name.




  
  


Notice we set the Domain Object and the Database Table to which this object maps to, via the class tag, using name and table attributes.




  
        
            
        
  

In our class tag we now want to setup the unique identifier, the above sample shows the id tag. Notice the name attribute matches the Id property on the Class, and column attribute, the column in the database. Take note that, by default NHibernate assumes you are using in32 for your Id, if you are using something like a GUID you must specify a type attribute. The generator tag specifies that it will use the native generation of the database to create the id.




  
        
            
        


  

Now, we told it to map our two properties FirstName and LastName in our Object, to our two columns firstName, lastName in the database. Now, onto our BankAccounts.




  
        
            
        




            
            
        
  

Now, this needs some dissecting. A bag is a collection, in our case our IList of BankAccount. The name, again our properties name. Now remember asking, “How does NHibernate set the BankAccounts?” Well, we tell it via the access attribute, in this case our property is backed by a camel case with underscore Class level variable, hence field.camelcase-underscore. Next, we tell it the foreign key, in this case this is our personId column, which we have already mapped via Id. Finally, the relationship, a one to many, which is specified by a one-to-many tag and completed by specifying which class to map too.

Learning Exercise:

I’m going to leave it up to you to create your own BankAccount Class, Table and Mapping. I will help you with a bit of the mapping. BankAccount will contain a property for a Person object, call it Person. In other words the foreign key back to Person [ (FK) personId].

Under your class tag in the BankAccount.hbm.xml. You will need to reference the Person Property back to your Person object.


That’s, it for the mapping section, coming up next starting your session, pulling a person and ending your session.

PS: I wrote this in a lunch hour, please don’t hesitate to point out any errors, typos, or things you feel should be added to this section.

What do you think?

Starting NHibernate | Adding DLLs

March 30, 2010

I am now going to spend a little time discussing the core DLL structure that you will need to start your project and the NHibernate configuration file. Let’s get you started!

First, you will need to create your Solution (then you can add a “Domain” Project to it), you will need to reference the NHibernate DLLs listed below in your main project. What I like to do with my DLLs, is create a lib folder in the solution root folder (not included into the project), and place all my DLLs and their resources there. This keeps me organized and organization is keen, when your creating a large solution.

Download: http://sourceforge.net/projects/nhibernate/files

In reality “NHibernate” exists in the NHibernate.dll and nothing more. However, there are many components to it for example for example, lazy loading for NHibernate references the Castle project DLLs and therefor we add those DLLs to our solution. Don’t get bogged down by the amount of files, keeping code separate for reuse is what OOP is all about. For now lets add:

- NHibernate.dll

- NHibernate.ByteCode.Castle.dll

- log4net.dll

- Iesi.Collections.dll

- Antlr3.Runtime.dll

- Castle.Core.dll

- Castle.DynamicProxy2.dll

You will also need to include the following files, with the DLLS:

- log4net.license

- log4net.xml

- Nhibernate.xml

And I recommend adding “NHibernate.Linq.dll” a separate download for Linq support.

When you have all of these files referenced, we can go onto setting up the connection, information. NHibernate provides you with two files named: “nhibernate-mapping.xsd” and “nhibernate-configuration.xsd” along side with their DLLs. These are mapping files, you don’t need them but they are very helpful for writing a lot of nhibernate xml based files which we will go into later on. We will need to create an “nhibernate.config” file now though, so lets do this first:




  

    NHibernate.Dialect.MsSql2005Dialect

    NHibernate.Connection.DriverConnectionProvider

    NHibernate.Driver.SqlClientDriver
16
web

    NHibernate.ByteCode.Castle.ProxyFactoryFactory,
    NHibernate.ByteCode.Castle

    [CONNECTIONSTRINGNAME]

  


Notice: [APPSESSIONNAME], [CONNECTIONSTRINGNAME], and [MAPPINGASSEMBLYNAME].

You will need to replace [APPSESSIONNAME] with the name of your session factory (a manager for your session), usually developers will use the Project/Solution name since the session factory is for the particular solution and since their is usually one session factory per solution you don’t reference the name of the session factory much. Note: it is possible to have multiple session factories but that’s another whole can of worms we will not go into for now.

The [CONNECTIONSTRINGNAME] should be the name of your connection string in either App.config or Web.config which looks similar to this:



  


Finally, the [MAPPINGASSEMBLYNAME] should be your Domain project, which I talked about earlier. Now this can be the same project but usually it is where your Domain objects live.

PART TWO: Starting NHibernate – Mapping Tables to Objects

What do you think?

ASP.NET MVC Email Template Solution

November 25, 2009

If you are like me then you have probably ran into a wall with using ASP.NET MVC View Engine to render your awesome Dynamic HTML Email Templates. At least you put up a fight using a lot of fake data. It is actually possible to get around it!


        var oldContext = HttpContext.Current;
        HttpContext.Current = new HttpContext(HttpContext.Current.Request,
        fakeResponse);

        var html = new HtmlHelper(new ViewContext(fakeControllerContext,
        new FakeView(), fakeViewDataDictionary, new TempDataDictionary()),
        new ViewPage());

        html.RenderPartial(viewName, viewData, viewDataDictionary);
        HttpContext.Current = oldContext; //yay 

Though, because you’re reading this you’re like me and you never give up! So how, how do you get around all of this? The answer is Spark. Eeek, another DLL? Yes, Spark is its own View Engine which is an entire different framework. Yes, you have to go to their website download the DLLS, put it in your Lib folder and reference it in your code. Let me tell you now, it is well worth it. Let’s dive in!

Let’s write the code to render our email using the Spark. We want our code to take in the template name, something like: “ForgotUsernameEmail.spark” and we also want it to reuse our current ViewData Object which is of type ViewDataDictionary and contains Person data, we will need to add this into our own implementation of AbstractSparkView. See samples bellow:

Render Email Method:


public string RenderEmail(string sparkViewName, ViewDataDictionary
viewData)
{
     var email = new StringWriter();
     var view = (EmailTemplateBase) _engine.CreateInstance(new
     SparkViewDescriptor().AddTemplate(sparkViewName));
     view.ViewData = viewData;

     try
     {
         view.RenderView(email);
     }
     finally
     {
         _engine.ReleaseInstance(view);
     }
     return email.ToString();
}

Oops thanks Arnis, forgot to mention EmailTemplateBase is just an extended version of AbstractSparkView that includes the ASP.NET MVC ViewDataDictionary.

Custom Spark AbstractSparkView with ViewData implementation:


    public abstract class EmailTemplateBase : AbstractSparkView
    {
        public ViewDataDictionary ViewData { get; set; }

        public object Eval(string expression)
        {
            return ViewData.Eval(expression);
        }

        public string Eval(string expression, string format)
        {
            return ViewData.Eval(expression, format);
        }

    }

So that’s done, let’s make the template… In my MVC Web Project I am going to add into my Views folder or maybe even Views/Email :) a file called “ForgotUsernameEmail.spark”.


Dear ${#name}:


Your username is ${#userName}.


Thank You.

I also put in a use tag to pull down a Signature file, since this is the same in everyone of my emails. Now let’s actually write the code to call it:


string email = RenderEmail("ForgotUsernameEmail.spark",ViewData);

And that’s all you need to do, well besides read up on spark syntax: http://www.sparkviewengine.com/documentation/configuring

What do you think?

Moq Testing Tutorial

April 21, 2009

If your reading this I assume you are either looking for or have an interest in a mocking framework for testing your .NET Applications.

In this tutorial I will take you through a framework called Moq for (.NET 3.5) released under the New BSD License. However, I will not be discussing what Mocking is for that is outside the scope of this tutorial. What is mocking/mock object?

Before we jump in to code, here are some important links:

Get Moq.

Moq API.

So lets dive in, assuming you already added a reference to the Moq DLL in your project. Let’s start out by creating a new Abstract class to your project. During this session I am going to call this class: UnitBaseAbstractClass for readability.

Creating A Base Test Class

UnitBaseAbstractClass: In charge of setting up Moq environment per TestClass.

1. First let’s add the Moq namespace to our newly created class.


using Moq;

2. Add the [TestClass] attribute to the top of the class, for anything extending this class will need to be a test.

using Moq;

namespace MyUnitTests
{
    [TestClass]
    public abstract class UnitBaseAbstractClass
    {
    }
}

3. We are now going to add two public members to UnitBaseAbstractClass these are of type MockFactory and AutoMockContainer.

MockFactory: A utility factory used to manage a mocks lifecycle.

AutoMockContainer: A container used to automatically inject mocks into desired objects.

using Moq;

namespace MyUnitTests
{
    [TestClass]
    public abstract class UnitBaseAbstractClass
    {

            public MockFactory _factory;
            public AutoMockContainer _container;

    }
}

4. To setup our Moq base class we will create a method called Setup which will take in a MockBehavior. In this tutorial we will only go into using, MockBehavior.Default.

MockBehavior: Tells the MockFactory how to behave. Strict behavior throws an exception whenever a mock isn’t setup
exactly as its mocked object. Loose will never throw an exception and Default is setup to use Loose.

(If you don’t understand what this means it’s alright to move on, as it will not affect you yet.)

5. After creating Setup we are going to instantiate both MockFactory and and AutoMockContainer the factory will need the behavior passed into Setup and the automock will need the factory.

using Moq;

namespace MyUnitTests
{
    [TestClass]
    public abstract class UnitBaseAbstractClass
    {

    public MockFactory _factory;
    public AutoMockContainer _container;

        public void Setup(MockBehavior behavior)
        {
            _factory = new MockFactory(behavior);
            _container = new AutoMockContainer(_factory);
        }

    }
}

6. Last but not least we want to implement our [TestCleanup]. We will call this method VerifyAll, all it will do is verify that all our mocks were used and that they were used correctly. Making the final code look something like this:

using Moq;

namespace MyUnitTests
{
    [TestClass]
    public abstract class UnitBaseAbstractClass
    {

    public MockFactory _factory;
    public AutoMockContainer _container;

        public void Setup(MockBehavior behavior)
        {
            _factory = new MockFactory(behavior);
            _container = new AutoMockContainer(_factory);
        }

        [TestCleanup]
        public void VerifyAll()
        {
            _factory.VerifyAll();
        }

    }
}

A Test Class using our Base Class

1. Let’s start by writing some tests against this pseudo PersonService class:

namespace MyRear
{

    public class PersonService
    {
        private readonly ISaveStuff _saveStuff;

        public bool SavePerson(Person person)
        {
		try{
		   return _saveStuff.Save(person);
		}
		catch (Exception ex){
		   throw new CustomException(ex);
		}
        }
    }
}

2. Create our test class using the base class. Our[TestInitialize] will be using the base Setup method and we will use the AutoMockContainer to create a new instance of typePersonService. We will also create a new person.

namespace MyRearTests
{
    [TestClass]
    public class PersonServiceTests
    {
        private readonly PersonService _service;
	    private Person _person;

        [TestInitialize]
        public void Setup()
        {
            Setup(MockBehavior.Default);
            _service = _container.Create<PersonService>();
	        _person = new Person();
	    }

    }
}

2.5. Ok, it is time now to write our tests! However, before this I want to show you how to mock up _saveStuff.Save because this code calls Database Code, which we do not want to access in our testing envoirnment!


return _saveStuff.Save(person);

3. First we want to get a mock object for ISaveStuff because this is how we are going to call Save. We do this with this line of code:


 _container.GetMock<ISaveStuff>()

4. We then want to make sure that we mock Save and are able to put in our own person object. We expand by using some simple Linq within the Expect method:


 _container.GetMock<ISaveStuff>()
	    .Expect(s => s.Save(_person))

5. We then need to tell the object what to return (in this case a bool of value true) and after it returns make sure to verify that this mock was implemented correctly.

 _container.GetMock<ISaveStuff>()
	    .Expect(s => s.Save(_person))
	    .Returns(true)
	    .Verifiable();

6. Lets make it a test now!

namespace MyRearTests
{
    [TestClass]
    public class PersonServiceTests
    {
        private readonly PersonService _service;
	    private Person _person;

        [TestInitialize]
        public void Setup()
        {
            Setup(MockBehavior.Default);
            _service = _container.Create<PersonService>();
	        _person = new Person();
	    }

        [TestMethod]
        public void SavePersonSuccess()
        {
 	        var result =
        	        _container.GetMock<ISaveStuff>()
		            .Expect(s => s.Save(_person))
	            	    .Returns(true)
		            .Verifiable();

            Assert.IsTrue(result, "Person should save.");
        }

    }
}

6.5. Lets add another test for returning false, a failed save.

namespace MyRearTests
{
    [TestClass]
    public class PersonServiceTests
    {
        private readonly PersonService _service;
	    private Person _person;

        [TestInitialize]
        public void Setup()
        {
            Setup(MockBehavior.Default);
            _service = _container.Create<PersonService>();
	        _person = new Person();
	    }

        [TestMethod]
        public void SavePersonSuccess()
        {
 	        var result =
        	    _container.GetMock<ISaveStuff>()
		            .Expect(s => s.Save(_person))
		            .Returns(true)
		            .Verifiable();

            Assert.IsTrue(result, "Person should save.");
        }

        [TestMethod]
        public void SavePersonFail()
        {
 	        var result =
        	        _container.GetMock<ISaveStuff>()
		            .Expect(s => s.Save(_person))
		            .Returns(true)
		            .Verifiable();

            Assert.IsFalse(result, "Person should not save.");
        }

    }
}

7. The last test is a bit tricky and it is also the reason why we caught the base exception and threw our own custom exception. First lets jump back to:


 _container.GetMock<ISaveStuff>()
	    .Expect(s => s.Save(_person))

8. Handling exceptions is different then normal asserts throwing them is different too. In order to throw an exception we need to call the Throws method instead of returns.

 _container.GetMock<ISaveStuff>()
	    .Expect(s => s.Save(_person))
	    .Throws(new Exception("Save Threw Up"))
	    .Verifiable();

9. Now lets make sure we handle the code. We do this with the [ExpectedException] attribute on our test methods.

        [TestMethod]
        [ExpectedException(typeof(CustomException))]
        public void SavePersonException()
        {
		        _container.GetMock<ISaveStuff>()
		        .Expect(s => s.Save(_person))
		        .Throws(new Exception("Save Threw Up"))
		        .Verifiable();
	        }

10. The Final Test looks like this:

namespace MyRearTests
{
    [TestClass]
    public class PersonServiceTests
    {
        private readonly PersonService _service;
	    private Person _person;

        [TestInitialize]
        public void Setup()
        {
            Setup(MockBehavior.Default);
            _service = _container.Create<PersonService>();
	        _person = new Person();
	    }

        [TestMethod]
        public void SavePersonSuccess()
        {
 	        var result =
        	    _container.GetMock<ISaveStuff>()
		    .Expect(s => s.Save(_person))
		    .Returns(true)
		    .Verifiable();

            Assert.IsTrue(result, "Person should save.");
        }

        [TestMethod]
        public void SavePersonFail()
        {
 	        var result =
        	    _container.GetMock<ISaveStuff>()
		    .Expect(s => s.Save(_person))
		    .Returns(true)
		    .Verifiable();

            Assert.IsFalse(result, "Person should not save.");
        }

        [TestMethod]
        [ExpectedException(typeof(CustomException))]
        public void SavePersonException()
        {
		    _container.GetMock<ISaveStuff>()
		     .Expect(s => s.Save(_person))
		     .Throws(new Exception("Save Threw Up"))
		     .Verifiable();
	    }
    }
}

I hope this helped you out a bit more in understand Moq. Good Luck!

What do you think?

« Newer PostsOlder Posts »