Thursday, December 13, 2012

RavenDb – Step by Step Tutorial


I’m starting a new project.
It’s going to be an ASP.net MVC4 website.
The content is secret;)
 
 
 
 




So today I was looking for the right DB for the site. Oracle and SQL Server were instinct choices. However as many of you I’m also subscribed to Ayende @ Rahien blog. And so as you I receive at least one raven db post a day. After reading a while I realized that RavenDb gives me the same abilities as a standard rational database and more (there too many articles about the efficiency of NoSql so I don’t want to add another one to the list).
That I do want is to guide you step by step in setting the RavenDb server and using the RavenDb Client in your application.

So let’s go! 







RavenDb has a client and a server side. The client enables you to connect to the RavenDb server. The server can run in several ways:
Win Service
IIS Service
Embeded in the application.

The embedded option is for really small projects or for demos as is in real application you would want to run the RavenDb on a different server and configure it to suite your needs.

I want to make this tutorial for real application’s scenario so we’d choose the Win Service option.
Download the last stable build of RavenDb. In the zip file you’ll find some samples and a server folder, copy it to a suitable location for a database (c:/temp).

In the server folder there’re two files that you are interested in: Raven.Server.exe and Raven.Server.exe.config. In the config file you can specify a custom port for the server to run and the location of the Data Directory where Raven writes the data. Yes, RavenDb is an in-memory database however it writes the data to a file for backup and restore purposes.
 <add key="Raven/Port" value="*"/>
 <add key="Raven/DataDir" value="~\Data"/>
By default the port will be 8080 and the data directory will be stored inside the server directory (perhaps c:/temp wasn’t such a good idea). 

Open the cmd and run the “…\Raven.Server.exe /install”. 

Check you services.msc and you will find RavenDb service running.





A really cool feature is the management studio which is located on localhost:8080 (or your custom port).

Here you can see all your documents, indexes and logs. The logs tab allows you to see all the queries and the commands that Raven executes.
To enable it you need to create NLog.config file in the server directory and paste the following code:

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.netfx35.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   <targets
      <target xsi:type="HttpEndpoint" Name="HttpEndpoint" /> 
   </targets
   <rules
      <logger name="Raven.*" writeTo="HttpEndpoint"/> 
   </rules
</nlog> 

Restart the process and now you have logs! 


Getting the client
After we have the RavenDb server running it’s time to add the client and start playing with Raven from the application.
For this tutorial we’ll need an Asp.Net MVC 4 project (if you don’t know how to open one read this).

In the package manager console type “Install-Package RavenDB.Client -Version 1.0.971”, the reason I do it from the console and not from the package manager is because the latest RavenDb.Client package has a Newtonsoft.Json.dll with a lower version when the version of the Newtonsoft.Json.dll that comes with the MVC project. By specifying this RavenDb.Client version we receive ravenDb.Client dlls compiled with the newest Newtonsoft.Json.dll.

Configurating Raven from the application
Similar to NHibernate, RavenDb has a DocumentStore (sort of SessionFactory) which only needs to receive the connection string name. Paste this code inside the Application_Start in the Global.asax:
Store = new DocumentStore { ConnectionStringName = "RavenDB" };
Store.Initialize();
IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store);
The third row adds custom created indexes from the assembly to the RavenDb Server (we’ll 
talk about it later).
Same as the Nhiberbate’s SessionFactory, the DocumentStore has to be singleton, making it static should work for now.
public static DocumentStore Store;
Add the connection string to the “connectionStrins tag in the web.config.
<add name="RavenDB" connectionString="Url=http://localhost:8080" />
 Session managment
Almost every controller will need an access to the RavenDb Session so lets create a RavenBaseController which will be responsible for opening and closing the session.
   1: public class RavenBaseController : Controller
   2: { 
   3:    public IDocumentSession RavenSession { get; protected set; }
   4:  
   5:    protected override void OnActionExecuting(ActionExecutingContext filterContext)
   6:    {
   7:       RavenSession = MvcApplication.Store.OpenSession();
   8:    }
   9:  
  10:    protected override void OnActionExecuted(ActionExecutedContext filterContext)
  11:    {
  12:       if (filterContext.IsChildAction)
  13:          return;
  14:  
  15:       using (RavenSession)
  16:       {
  17:          if (filterContext.Exception != null)
  18:              return;
  19:  
  20:          if (RavenSession != null)
  21:              RavenSession.SaveChanges();
  22:       }
  23:    }
OnActionExecuting will open the session per web request and OnActionExecuted will flush all the changes (similar to transaction.commit). If an exception was thrown then the session will rollback.

Basic Session Usages

var student = new Student {Name = "San Yang"};
RavenSession.Store(student); 

You can check how is the class converted to a Json document using the raven 
studio. 



Similar to NHibernate (Store = SaveOrUpdate) and if the class has an id property Raven will generate a unique id (numeric or string). However if you store an object with nested objects in it, Raven won’t generate ids for them.

Queries are same as in NHibernate:

var school = RavenSession.Query<School>()
                          .Where(x => x.Students.Any(y => y.Name == "jones"))
                          .ToList();
 
            var school = RavenSession.Query<School>()
                                     .Where(x => x.Name == "")
                                      .ToList(); 

Knock yourself out.

Indexes
RavenDb’s philosophy is “we shall never make you wait” and so far they haven’t disappointed me. Perhaps the dynamic index generation helps them there.
RavenDb analysis every query that is executed on the session and creates a temporary index for it. If the query is executed several (configurable) times then the index becomes permanent.

So that should give you a nice place to start from.
More posts about advanced RavenDb usages and options are coming soon.

Tuesday, December 11, 2012

INotifyPropertyChanged without explicitly using the property Name


public class MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string _message;
    public string Message
    {
        get { return _message; }
        set
        {
            if (_message != value)
            {
               _message = value;
               OnPropertyChanged("Message");
           }
        }
    }

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

All of you, Silverlight and WPF developers, recognize this code. You have dozen of those properties that call the “OnPropertyChanged” method with hardcoded property name.
Some of you perhaps solved this problem using lambda expressions or some other ways.
In this post I’d like to show you another cool way to avoid hardcoding your properties name every time you call “OnPropertyChanged”.

private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

You: Huh?
Me: Exactly!

Let me introduce you to the “CallerMemberName” attribute that allows you to obtain the method or property name of the caller to the method.
If the Message property calls the “OnPropertyChanged” method, the propertyName default parameter will be automatically set with the calling property name in compile time, meaning that the property name will be hardcoded inside the dll.
The only catch here is that in order to use this attribute the parameter has to be default.
    public string Message
    {
        get { return _message; }
        set
        {
            if (_message != value)
            {
               _message = value;
               OnPropertyChanged();
           }
        }
    }

FYI
There’re more attributes with abilities like CallerMemberName, such as:
CallerFilePath – gives you the source file path
CallerLineNumber – returns the line number of the calling method 

  
Type safe ;)

Tuesday, November 13, 2012

Entrepreneurship Week of Israel


This week is the "Entrepreneurship Week of Israel".
A variety of entrepreneurs lecture about their success, startup ideas and tips for your great startup. 
All the lectures are free and they take place in different bars, pubs and clubs in all the big cities of Israel (you can't talk about startups and ideas and not drink beer).

Here is a link to all the upcoming events.

Enjoy.

Saturday, November 3, 2012

System.Speech - Talk to Your Computer


.net 4 introduced a new namespace: System.Speech. Yes - that means that your computer can talk.
Why would you want it? First of all it's cool - with less than 10 lines of code your computer can say whatever you want. Secondly we are living in a new era - the physical keyboard and the mouse are being replaced by touch screens (even now you are probably reading this post from your Smartphone). The present brings touch screens and the not so far future will bring voice control and much more – "There is no such thing as Science Fiction any more".

So if you are building a new app and you want to give it some extra features you should start with some voice control. In order to make the computer listen and recognize that you're saying we'll use the SpeechRecognitionEngine class. 
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
recognizer.SetInputToDefaultAudioDevice();
recognizer.LoadGrammar(
new Grammar(new GrammarBuilder("hello computer")));
SetInputToDefaultAudioDevice method tells the recognizer to use the built in audio device in your computer, you can use the SetInputToAudioStream method to set a custom device.
The last method is the most interesting one: LoadGrammer receives the input that the user will say to the computer. The SpeechRecognitionEngine has two events:
recognizer.SpeechDetected()
recognizer.SpeechRecognized()
The SpeechDetected event fires whenever the computer detects any sound that can be converted to speech (you talking on the phone near the computer will raise this event). The SpeechRecognized will rise when the detected speech is matching to the loaded grammer. You can supply a single string to the LoadGrammer method or you can use the Choises class:
recognizer.LoadGrammar(new Grammar(new Choices(new []
                {
                   
"hello computer", "I am fine how are you", "goodbye"
                })));
Clear right?
The next thing we'll do is subscribe to "SpeechRecognized" event:
recognizer.SpeechRecognized += Speak;
recognizer.RecognizeAsync(RecognizeMode.Multiple);
RecognizeAsync(RecognizeMode.Multiple) means that the recognition won't stop after the engine detects a speech.

The last thing that's left to do is to make the computer respond to our input:
private void Speak(object sender, SpeechRecognizedEventArgs e)
{
    SpeechSynthesizer speechSynthesizer =
new SpeechSynthesizer();

   
switch (e.Result.Text)
    {
       
case "hello computer":
            {
                speechSynthesizer.Speak(
"hello Dennis, how are you?");
               
break;
            }
    }
}

Yes, the computer will say this :)

Earlier we talked about voice control. I want to tell my computer to open chrome browser, soliter or to start some complex calculation. To do so we'll need to add a new grammer and a matching action in the method that is subscribed to the SpeechRecognized event:
case "open chrome":
           {
              Process.Start(
"chrome");
              
break;
           }

The future is here.

Tuesday, October 23, 2012

Rhino Mocks vs Moq vs NSubstitute

I seriously believe in TDD. I think that the benefit you get when fully adopting it is un describable. Following it allows you not only to cover most of your code but write testable code from the beginning, which later can be easily modified. But this post is not about TDD (I use it – deal with it!). This post is about what mocking framework is the best from the optional frameworks out there.
I’ve used Rhino Mocks for the last 3 years. Everybody know this framework, most of you probably worked with it in the past (or still do). It gets the job done. But it has different types of mocks that frankly, I never remember when to use stub or mock,  the AssertWasCalled function is not trivial as you would expect.
The main consideration for a software developer who writes code, is choosing a simple mocking framework. I don’t want to “waste time” in writing my tests. I want my tests to be simple and clear without different mock types (Do you really know the difference between strict,  partial, dynamic and stub types of a mock object?). All I want is the ability to derive from a class or implement an interface and then set some custom behavior to fit my test’s needs. The test should be simple, clear and obvious not only to myself but to anyone else.
All the above and my constant quest of finding the most simple way to write code lead me to compare these three frameworks: Rhino Mocks, Moq and NSubstitute (Nuget them).
I’ll show their basic usages, their advantages and disadvantages and of course which one I prefer.
This is the class that I’m going to Test:
   1:   public class SchoolRegistrationServer
   2:   {
   3:       public SchoolDatabase SchoolDatabase { get; set; }
   4:  
   5:       public SchoolRegistrationServer(SchoolDatabase schoolDatabase)
   6:       {
   7:           SchoolDatabase = schoolDatabase;
   8:       }


I receive the Dal abstraction in the constructor so it could be easily mocked.



   1: public class SchoolDatabase
   2:     {
   3:         public virtual DB DB { get; set; }
   4:  
   5:         public virtual bool Add(Student student)
   6:         {
   7:             throw new NotImplementedException();
   8:         }
   9:         
  10:         public virtual bool DoesStudentExist(Student newStudent)
  11:         {
  12:             throw new NotImplementedException();
  13:         }
  14:  
  15:         public virtual string Connect()
  16:         {
  17:             throw new NotImplementedException();
  18:         }
  19:     }



This class is yet to be implemented – TDD or Not. For those of you who ask “why this class doesn’t have an interface” I answer: I don’t put an interface on every class. If it’s not an API contract or a replaceable feature then there is no point adding an interface (How often do you replace your DAL?).



Let’s begin the comparison:

The first thing I want to compare is the initialization of the mock objects:



   1: SchoolDatabase nsubstituteMock = Substitute.For<SchoolDatabase>();
   2: SchoolDatabase rhinoMock = MockRepository.GenerateMock<SchoolDatabase>();
   3: Mock<SchoolDatabase> moqMock = new Mock<SchoolDatabase>();



The main difference is that Moq framework separates the mock from the object that is injected to the tested class.



   1: SchoolDatabase schoolDatabase = moqMock.Object;



The separation is logical – you set custom behavior on the mock object and pass a “ real” object to the tested class. I don’t think that should be a separation since the object that is passed to the tested class is a proxy so there is no point separating them to a mock object and to a “real” class.



Rhino Mocks on the other hand creates a mock that is already a class but they let you choose between 4 different kinds of mocks that you can generate:



  • Partial mock – If there’s no stub for a method a partial mock will call the actual implementation method – not the mock.

  • Dynamic mock – If there’s no stub for a method a dynamic mock will return a default value (0 or null).

  • Strict mock - If there’s no stub for a method a strict mock will throw an exception.

  • Mock - Mocks record and verify action that was made on a class, plus they allow you to replace a method behavior with your own and if no stub was made a default value will return.

  • Stub– Same as mock but doesn’t record.



A lot of “nice to have options” but frankly when using GenerateMock (that exposes you almost all the meaningful functionalities) you don’t really need all the others.



NSubsitute introduces you a single method “For” and immediately  creates a mocked object of the object’s type:



  1: SchoolDatabase nsubstituteMock = Substitute.For<SchoolDatabase>();


Smooth.



Next topic is “behavior replacement”":




   1: public bool AddStudent(Student student)
   2: {
   3:     if (SchoolDatabase.Add(student))
   4:     {
   5:         return true;
   6:     }
   7:  
   8:     return false;
   9: }

This the super complex method that I want to test.




   1: [TestMethod]
   2:   public void AddStudent_StudentWasAdded_ReturnsTrue()
   3:   {
   4:       // Arrange
   5:       var studentToAdd = CreateStudent();
   6:      
   7:       // Mocking behavior setup
   8:  
   9:       // Act
  10:       var wasAdded = SchoolServer.AddStudent(studentToAdd);
  11:  
  12:       // Assert
  13:       wasAdded.Should().BeTrue();
  14:   }



This is the super complex test. Now let’s see how every mock allows us to replace the behavior of it’s method.



   1: // Moq
   2: SchoolDatabaseMoqMock.Setup(x => x.Add(studentToAdd)).Returns(true);
   3:  
   4: // Rhino Mocks
   5: SchoolDatabaseRhinoMock.Stub(x => x.Add(studentToAdd)).Return(true);
   6:  
   7: // NSubstitute
   8: SchoolDatabaseNSubtitueMock.Add(studentToAdd).Returns(true);



We can easily see that Rhino Mocks and Moq look almost the same. NSubstitute chooses not to go with the traditional lambda expression syntax, it’s mock exposes the mocked object methods to which we fluently add the return statement. It’s neat but can be a little confusing. Frankly I don’t know what I prefer (it’s a tie).



Next is “Multiple return values”:

In some tests the mocked object will be called several times and every time it should return a different value. My next method tries to connect to the school database, it has 3 attempts after which it fails.





   1: public string ConnectToDB()
   2: {
   3:     var connectionAttemps = 1;
   4:     var maximalConnectionAttemps = 3;

   6:     while (connectionAttemps <= connectionAttemps)
   7:     {
   8:         if (SchoolDatabase.Connect())
   9:         {
  10:             return string.Format("Connected to database after {0}", connectionAttemps);
  11:         }
  12:  
  13:         connectionAttemps++;
  14:     }
  15:  
  16:     return string.Format("Failed to connect to database after {0} attemps", maximalConnectionAttemps);
  17: }


I want to test that the method returns the right output after it managed to connect on the third attempt. I need to setup my mock to return twice “false” and on the third time return “true”:




   1: // Rhino Mocks
   2: SchoolDatabaseRhinoMock.Stub(x => x.Connect())
   3:     .Return(false).Repeat.Once()
   4:     .Return(false).Repeat.Once()
   5:     .Return(true);
   6:  
   7: // Another option
   8: SchoolDatabaseRhinoMock.Stub(x => x.Connect())
   9:     .Return(false).Repeat.Twice()
  10:     .Return(true);



Rhino Mocks allows us to define as many return options as we like, plus we can use it’s cool fluent API. Nice and easy.




   1: // NSubstitute
   2: SchoolDatabaseNSubtitueMock.Connect().Returns(false, false, true);


Next is NSub that allows to override the usual “Return” method and instead of returning just one object we can return as many as we need. The results will return by the order we set them in the mock.



Moq doesn’t allow you to return different values. You have to implement some sort of queue that will withdraw the results by order. This post explains it. Too complicated.



Next it “Recursive mock”:



   1: public string GetConnectionString()
   2: {
   3:     return SchoolDatabase.DB.GetDatabaseDetails();
   4: }



First of all it’s bad practice to allow your object expose methods of it’s properties. However in legacy applications it’s quite common. The problem here is that the “DB” property has no mock so we have no control of the “GetDatabaeDetails” output. Luckily all the three frameworks support the “Recursive mock” meaning that in case the mock has a property that hasn’t been mocked it will automatically mock it.




   1: // Moq
   2: SchoolDatabaseMoqMock.Setup(x => x.DB.GetDatabaseDetails).Returns(expectedConnectionString);
   3:  
   4: // Rhino Mocks
   5: SchoolDatabaseRhinoMock.Stub(x => x.DB.GetDatabaseDetails).Return(expectedConnectionString);
   6:  
   7: // NSubstitute
   8: SchoolDatabaseNSubtitueMock.DB.GetDatabaseDetails().Returns(expectedConnectionString);



The last comparison is method call verification:




   1: public void RegisterStudent(Student newStudent)
   2: {
   3:     var isAlreadyRegistered = SchoolDatabase.DoesStudentExist(newStudent);
   4:  
   5:     if (!isAlreadyRegistered)
   6:     {
   7:         SchoolDatabase.Add(newStudent);
   8:     }
   9: }



I want to test that in case the student doesn’t exist the “Add” method will be called (and on the contrary that it hasn’t called if the student does exist).



   1: // Rhino Mocks            
   2: SchoolDatabaseRhinoMock.AssertWasCalled(x => x.Add(studentToRegister));
   3: SchoolDatabaseRhinoMock.AssertWasNotCalled(x => x.Add(studentToRegister));
   4:  
   5: // Moq
   6: SchoolDatabaseMoqMock.Verify(x => x.Add(studentToRegister),
   7:                              "when student doesn't exist, it should be added to the db");
   8: SchoolDatabaseMoqMock.Verify(x => x.Add(studentToRegister), Times.Never(),
   9:                              "when student doesn't exist, it should be added to the db");
  10:  
  11: // NSubstitute
  12: SchoolDatabaseNSubtitueMock.Received().Add(studentToRegister)
  13: SchoolDatabaseNSubtitueMock.DidNotReceive().Add(studentToRegister);



Rhino Mocks and NSub are pretty straight forward how ever rhino mock’s error messages aren’t clear “...Expected #0, Actual #1. “. Moq on the other hand allows you to add a custom message that will appear if the test fails. NSub has a better error message:



“Expected to receive no calls matching:

    Add(Student)

Actually received 1 matching call:

    Add(Student)”

That’s not as good as the custom error message the Moq exposes but it’s good enough.

 

Conclusion:

So which is the best mocking framework? As all the answers in software development – it depends. It depends on what do you need: if you are going to use multi results return for one method then Moq is probably not a good option, however if you care about good error messages when your tests fail then Rhino Mocks isn’t that good.

I remind you why I started this comparison – I’m interested in a simple framework that allows me easily to mock objects and change their methods behavior, plus obvious error messages. My choice is: NSubstitute!

It is simple, easy to use and  it’s easy to explain to other developers how to use it. It has all the main functionalities and a really simple fluent interface.

I’ll say it again: NSub works for me. Your application may need other functionalities that NSub doesn’t have. That’s fine, just remember to open your eyes and look around. Technology evolves all the time – don’t stick to some framework just because you are used it. Don’t afraid to try.

Good Luck!