Friday, December 26, 2014

A good ORM framework is already Repository + Unit of Work

A common implementation of Repository and Unit of Work pattern based on Entity Framework is like this (code copied from here with small change for demonstration purpose)

A generic repository
public interface IGenericRepository<TEntity> where TEntity : class
{
    IEnumerable<TEntity> GetAll();
    void Add(TEntity entity);
    // Any other CRUD methods
    ...
    void Dispose();
}
public class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity>
where TContext : IUnitOfWork
where TEntity : class
{
    public IEnumerable<TEntity> GetAll()
   {
        return _context.Set().AsEnumerable();
   }

    public void Add(TEntity entity)
    {
        if (entity == null)
            throw new ArgumentException("Cannot add a null entity");

        _context.Set<TEntity>().Add(entity);
    }
   // Other implementations
}

A DbContext implements Unit of Work interface:
public interface IUnitOfWork : IDisposable
{
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges();
}
public interface ISampleContext : IUnitOfWork
{
    DbSet Items { get; set; }
    // And all the other DbSets
}
public class SampleContext : System.Data.Entity.DbContext, ISampleContext
{
  public CustomerContext() { }
  public CustomerContext(string connectionString) : base(connectionString) { }
}


People claim this pattern gives us three major benefits
  • Separate the domain models from persistence concern
  • Easy for dependency injection and unit testing
  • Can be easier if it needs to swap to another ORM framework or database
First domain models do not hold any reference to ORM anyway. I do not see how adding another abstraction layer between them makes it more separate. Also from the code above, only IGenericRepsitory<TEntity> does not bind to any ORM framework type, everything else binds to EF types and it becomes just a wrapper to EF and I fail to see any business value there.

Secondly for dependency injection and unit testing. Well, if I use ORM directly there is no need to inject anything here. For the UoW on a typical OLTP MVC project I simply use Ayede's awesome implementation on the infrastructure level. EntityFrameWork 6 makes it easy to mock the DbContext so unit testing is not a problem as well. And using integration test with in-memory database such as SqLite and RavenDB is even better.

For the third benefit, can you tell me when was your last time and why you needed to change ORM framework or database in a deployed commercial project?

I used to be a fan (with pains) of repository + UoW pattern, until I saw some good thoughts and different ways. Most of the implementations I saw are just a wrapper of the ORM framework without adding any true value, not to mention those powerful and flexible features provided by those ORMs hidden by this layer of abstraction. The mutual ORM frameworks like EF, NHibernate, RavenDB Client are already a repository + UoW, why do we need to implement our own which is only an wrapper and an unnecessary abstraction on top of it, which are implemented by awesome people and tested with time?

Do not implement the repository + UoW pattern just for the sack of implementing it, especially when there are already great ORMs, unless there is a business scenario that justifies your own implementation. A good ORM framework is already Repository + Unit of Work. Work with it, not against it.

Thursday, September 4, 2014

It is a good chance to provide good customer service when your product does not work

Recently I happened to discover Ayende Rahien's Open letter to XHEO: That is not a good way to do business published in 2009, which is about a bad customer experience with XHEO. 5 years later when I searched the word 'XHEO' on Google it came back with this




Note that the second result is the letter. Sign... I wonder how many potential customers they have lost in the past 5 years because of this, and how many potential customers they are still going to lose in the future because of this.

First I believe what Ayende presented in the post were the facts for two reasons. Firstly after 5 years this post is still there while the links of the responses letter from XHEO are unavailable as the time of this post. Secondly if that post was not true or simple exaggerated I think Ayende can be easily sued by XHEO and the post has to be removed, which did not happen in the past 5 years.

It is not usual to be treated like this when dealing with technical people without any proper training or guidance. What surprises me is when dealing with a person such as Ayende with so much influence in the industry how come the business owner did not take over it and put it into damage control when there were so many chances. Seems like the owner himself is from technical background without proper customer service training. Just for a couple of thousand dollars, how much have they lost?!

The key point in that case is not the product itself. It is the service. Ayende bought a service. It is not a too bad situation if the product does not work. And it sometime can be even a good thing, because it means you have the chance to provide a good customer service that can impress the customer and others.

But XHEO chose the worst option and got the worst result. They refunded the money. They lost reputation. And the post is still in the second record on the first page in the Google search result, which is huge damage to the business.

It is another thing beyond my understanding is that it seems they did not care to remove it from the Google search result.


Thursday, March 20, 2014

Windows Phone 8 development - setup https with self-signed certificate in virtual machine

It is common to use https communication between the phone application and the services for a secured data transportation. In order to setup https it needs a certificate. For production environment it can be purchased from a trusted CA provider such as GoDaddy. For development environment it can be generated locally by using the Microsoft Certification Creation tool makecert.exe.

Before we start doing it the environment needs to be ready. Please see my previous post Setup Windows Phone 8 Dev environment in virtual machine for this.

Let’s go through it step by step.



The self-signed certificate

Since the certificate subject name and key file name must match the website name, and the Emulator knows the development machine’s IP address, so we need to use the development machine’s IP address as the certificate subject name and key file name.

Find the development machine’s IP address for the Emulator

Fire up Visual Studio command prompt as administrator, type ipconfig then enter, two adapters should appear in the results. Pick the IP address under the Windows Phone Emulator one. In my example it is 169.254.80.80.




First we need to create a certificate to act as the root certificate authority. Still in command line windows execute the following line:

makecert -n "CN=169.254.80.80" -r -sv 169.254.80.80.pvk 169.254.80.80.cer

Input the password for the private key then press OK.


Input the password again then press OK.




Go to the folder we should be able to see two files just created, one is the certificate file the other is the private key file.




Then we need to install the root certificate authority on the development machine.

Go to the management console for certificates for local machine. Right click the Certificates folder under Trusted Root Certification Authorities, choose All Tasks -> Import...




Import the certificate file just created. After the import it should appear in the Trusted Root Certification Authorities/Certificates folder.




Then we need to create and install the temporary certificate on the development machine from the signed root CA just imported.

In command prompt execute this line

makecert -sk testcert -iv 169.254.80.80.pvk -n "CN=169.254.80.80" -ic 169.254.80.80.cer -sr localmachine -ss my -sky exchange -pe

Input the private key password then press OK and it should succeed.




Now the testcert is available for binding in IIS.



Setup a https website in IIS

In IIS add a website with the binding type https. In the SSL certificate dropdown list choose the one with the development machine IP address as the name, which was created previously.




Select the website added just now, click the Browse *.443 (https) link in the right side panel.




It should show a warning message which is expected.




Change the URL address from localhost to the IP address then it should be fine.




Now let’s create a simple WCF service and deploy it to the https website we just added.

Add a WCF Service Application project in Visual Studio.




When it is created it contains a sample service Service1.svc. We will use it for demonstration purpose.

Before publishing it to the website we added in IIS, we need to do some configurations in web.config.

In the solution explorer right click the web.config file then choose Edit WCF Configuration.

In the Configuration Editor click Create a new service for the Service1.svc and follow the wizard. Remember to choose the http and leave the endpoint address empty.




Once it is created then click Host under the new service, add a base address which is the https IP address.




Click the (Empty Name) under Endpoints, in the General tab on the right side, choose the binding type to basicHttpsBinding.




In Identity tab choose FindBySubjectName for X509FindType, then input the IP address for the FindValue.




Make sure the value for HttpsGetEnabled in ServiceMetadata settings under Service Behaviors is set to True.




Save the configuration changes then publish the WCF service to the folder was setup for the website.

Once the website is published, open the service from a browser, it should tell that the service is up and running.




Launch WCF Service Test Client. It should be located at \Microsoft Visual Studio 11.0\Common7\IDE\.

In the tool add the https service. It should be able to find the two methods defined in the service interface. Double click the GetData() method, input a value in the right side then click the button Invoke, it should receive a response with the expected value.




By now we are sure that the https service is working as expected.

Windows Phone 8 project

Let’s create a Windows Phone 8 application which invokes this https service just deployed.

Create a Windows Phone 8 project. Add a service reference to the https service.




In the MainPage.xaml add a button which points to a click method like this




Set the Windows Phone 8 project as the startup one if there are other projects in the solution.

Choose one of the Emulator from the dropdown list then press F5.


The phone application should be running in the emulator. Click the button just created and it should throw a CommunicationException. The reason is that self-signed certificate is not a trusted one in the emulator so we need to install it in the emulator manually. If the certificate is from a trusted CA then this step is not needed.

Locate the certificate added under Trusted Root Certification Authorities, right click it then choose All Tasks -> Export.




During the export wizard choose the .P7B type. Export it with a proper file name and location.




Copy the exported file to the service folder. In the browser type the url which points to the certificate file,  make sure it can be downloaded successfully.




In the emulator launch IE and type the certificate file url then press enter. Tip: pressing the Pause key in your keyboard enables you to type from your keyboard in the emulator.

It should show you a warning message. Click ‘Continue to website’.




Install the certificate.



After the certificate is installed successfully, go back to IE and type the service url, it should not show any warning message again, which means the certificate is not a trusted one.



Run the phone application again and click the button, it should connect to the https service correctly this time.




As long as the emulator is not closed then the certificate stays in the emulator. When the emulator is opened next time, you need to repeat the installation process in it.

Monday, March 17, 2014

Equals and "==" operator in C#

Came across an interesting blog here:

http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx

In summary:

Equals and '==' operator in C# is an interesting topic. It is Polymorphism behind this.

Reference type: by default (which means no Equals overriding or '==' operator overloading) both of them do reference comparison.

Value type: by default it doesn't support '==' operator. If you define a struct and use '==' operator to compare its two instances, it can't pass the compilation. You need to overload '==' operator in the struct. Equals checks the values equality.

Equals is overriding and '==' operator is overloading. Remember this will be helpful for you to understand it.

A Windows Phone 8 Application Project Summary



Overview

Recently I did a Windows Phone 8 application project for the state government. It has an existing system for tracking and monitoring the tagged sharks in the oceans for research and alerting purposes. It has an internal administration website for maintaining the business data. The goal of this project is to implement a Windows Phone 8 application that can give the staff the ability to maintain the data by using mobile devices either online or offline when they are on boats doing the job, with some nice features such as giving the current location’s longitude and latitude.

Requirements

The main requirements include:


  • The user needs to input a six-digit number in order to use the functionalities
  • The user needs to be able to retrieve the data from the server if there is a connection
  • The user needs to be able to filter the data on the phone
  • The user needs to be able to create and update the data on the phone
  • The user needs to be able to push the changes back to server. If there is no connection the changes need to be saved on the phone
  • When there is a connection the user needs to be able to push the changes saved on the phone to the server
  • The phone needs to provide the location service to get the current location’s longitude and latitude
  • The communication between the phone and server needs to be secured
  • Only authorized phone devices can exchange data with the server
  • The data stored on the phone needs to be encrypted
  • The user interface needs to be user friendly

Technologies

The project used the following technologies


  • Windows 8 64-bit
  • Windows Phone 8
  • Visual Studio 2012
  • SQL Server Compact
  • Resharper 8.0
  • MVVM Light
  • Windows Phone Toolkit
  • Moq
  • Microsoft Windows Phone Unit Testing
  • Https WCF services

Security

The security is implemented from the following aspects:

  • Windows phone lock screen
  • Mobile application pin number screen  
  • Local data encryption
  • Data transportation security
  • Device authorization process

Windows phone lock screen


The user’s Windows phone devices are required to setup a lock screen with a pin number. The phone should be auto-locked if it is not attended for some time (recommend 5 to 10 minutes).

Mobile application pin number screen


When the mobile app is launched, it displays a pin number screen. The user needs to input a correct six-digit pin number by tapping the numbers on the screen before the user can access any of the application functionalities.

Local data encryption


The mobile application uses a SQL Server Compact database to store the data on the phone. The database is encrypted by using the algorithm provided by .Net Framework 4.5 that the database is encrypted by using AES-128 and the password is hashed by using SHA-256.

Data transportation security


The data exchanged between the Windows Phone and the services is encrypted by using https, which is a secured communication over a computer network. This makes sure all the data is transferred between the phone device and the trusted services in a secure way that the data is encrypted by using a valid certificate from a trusted CA authority.

Device authorization process
Since Windows Phone 8 operation system does not support client certificate, the mobile application embeds its device unique ID in the message head in every request sent to the service. The service validates the device unique ID against a list of authorized device ID in every request before it processes to any actual data. This makes sure that only authorized devices are allowed to consume the business data.

Windows Phone App Policies

In order to be able to be published on the Windows Phone App Store, there are a list of App Policies need to be implemented by the phone application. The policies can be found at

http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184841(v=vs.105).aspx


SMN Mobile application implemented two policies:


  • clause 2.7 which is related to location service
  • clause 2.8 which is related to acquiring phone device information