The Rain and The Shade

September 27, 2011

Topics, Subscriptions and Receivers in Windows Azure App Fabric Service Bus

Filed under: AppFabric,Windows Azure — ovaisakhter @ 12:25 am

 

I believe the most complex thing I found when looking into the Azure AppFabic Service bus is the pricing model. After spending quite a few precious minutes of my life I now think understood it but I am still not sure if I am correct. So this matter has to wait until my next statement arrives and I got yelled by my support department. At which time I may come back with a blog on that. Meanwhile you can go ahead and have a look at the pricing FAQ at

http://www.microsoft.com/windowsazure/faq/#pricing

good luck with that Smile

So now back to simpler things, Usually Udi Dahan starts his NServiceBus presentation with this “Where is the bus, There is no bus”. Well in the case of AppFabric Service Bus there is a Bus. You can have a look at it at the Azure management portal.

Now I will use this bus to create a simple chat application and while I am using it I will try explain some of its concepts. Please make sure to install the relevant SDK installed from the following link

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27421

Our chat application is a WPF application containing only one screen. The application allow any number of users to join in and every one will see every one’s messages. For simplicity the user names are given in the configuration file. So the main screen only has a list of messages, a message textbox and a send button. Application uses MVVM so most of our functionality resides in the ViewModel. I am using Galasoft’s MVVM light framework here which is a treat to use in it self but more on that later.

Long story short the button is bound to a command and we are mostly concerned from that point onwards.

image

I have encapsulated all the logic related to the service bus functionality into a separate class let us call it service bus manager in its constructor the class connects to the service bus and tries to create the initial structure required for the communication. Have a look at the following code

var tokenProvider =
           TokenProvider.CreateSharedSecretTokenProvider(IssuerName, IssuerKey);
           var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty);

           _namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

The bold variables actually signify some steps that should be done before starting the code i.e. You should create a Service Name space. The service name space is actually the unique identity of your service using which your service bus will be located. Here is a link on how you can do it otherwise you can log into the Azure Management portal and find your way to do that,

http://debugmode.net/2011/04/05/getting-started-with-azure-appfabric-service-bus-creating-namespace/

Once your namespace is created and selected you will be able to see Default Key property on the Properties section click the button and you will be able to see the IssuerName and IssuerKey.

NamespaceManager is the main class in the API once you have created an instance of this you can go on and manipulate things. Next thing we would like to do is to create a topic, Following code checks if there is a topic already created for the Chat if not then it creates it.

_myTopic = !_namespaceManager.TopicExists(ChatTopic) ? _namespaceManager.CreateTopic(ChatTopic) : _namespaceManager.GetTopic(ChatTopic);

all good except I have not explained what a topic is, “A topic is a durable message log with multiple subscription taps separately feeding subscribers” So topic is a central entity against which all the messages are published, and as many as 2000 subscribers can subscribe to it. Once a message is posted to a topic a copy of this message is sent to each of the subscribers. 

Speaking of subscriptions here is the code which will create the subscriptions to our newly created topic.

if (_namespaceManager.SubscriptionExists(_myTopic.Path, clientName))
            {
                _namespaceManager.DeleteSubscription(_myTopic.Path, clientName);
            }

            _namespaceManager.CreateSubscription(_myTopic.Path, clientName,
                                                 new SqlFilter(string.Format("From <>'{0}’", clientName)));

For the chat application we are creating one subscription for each client, we are checking if there is a subscription already I am deleting and creating a new one. This code also shows another aspects of the subscriptions that they can be selective i.e. you can tell what type of messages posted on the topic you are interested in. Here I am specifying that I am not interested in the messages sent by myself, which kind of makes sense for a chat application. Here “From” is a property of the message which contains the user name of the user who sent the message. In our application a chat message is represented by a ChatMessage Class

public class ChatMessage
    {
        public string Message { get; set; }
        public DateTime ReceivedTime { get; set; }
        public string From { get; set; }
        public string Id { get; set; }

    }

but we do not send this message as it is. More on this later let us carry on with the constructor code

              var factory = MessagingFactory.Create(serviceUri, tokenProvider);
            _myTopicClient = factory.CreateTopicClient(_myTopic.Path);
            _mySubscriptionClient = factory.CreateSubscriptionClient(_myTopic.Path, clientName, ReceiveMode.ReceiveAndDelete);

As all good chat applications our application will send and receive messages _myTopicClient will be used to send the messages and _mySubscriptionClient will be used to receive the messages.

Let us talk about sending first,

public void SendMessage(ChatMessage chatMessage)
        {
            using (var message = new BrokeredMessage())
            {
                message.CorrelationId = chatMessage.From;
                message.Properties.Add("Message", chatMessage.Message);
                message.Properties.Add("From", chatMessage.From);
                message.Properties.Add("Id", chatMessage.Id);

                _myTopicClient.Send(message);
            }

        }

simple enough I guess. Just keep in mind that

“Maximum message size: 256KBMaximum header size: 64KBMaximum number of header properties in property bag: MaxValue Maximum size of property in property bag: No explicit limit. Limited by maximum header size.”

Now let us talk about receiving the message. Service bus messages are received by polling on the service bus “kaachhaaan” I can hear the sound of breaking heart but well this is true no events guys not for now at least. Here is the code that does “the magic”.

var task = new Task(ReceiveMessageTask);
            task.Start();

Started a task to start a separate thread for polling, may not be the best way to do it but it works we are good to go here.

private void ReceiveMessageTask()
       {
           while (true)
           {
               var message = _mySubscriptionClient.Receive(TimeSpan.FromSeconds(2));

               if (message == null) continue;

               var chatMessage = new ChatMessage
                                     {
                                         From = (string)message.Properties["From"],
                                         Id = (string)message.Properties["Id"],
                                         Message = (string)message.Properties["Message"],
                                         ReceivedTime = DateTime.Now
                                     };

               FireMessageReceived(chatMessage);

          }

       }

so we poll for message after every 2 seconds and if we receive a message we fire an event which is handled by the ViewModel which get the message and updates the UI.

Here is where I am chatting to myself

image

(ignore the “Not Connected” label on the left)

You can open as many applications as you want about (2000) to be precise give them different names and they will work.

Do try this at home. I have given the example of a chat application to explain some of the concepts in azure appfabric service bus. Of course I do not believe it to be a rightful use of this technology. Service bus is used to enable applications to talk to each other. If you would like to dig deep into how and where the service bus should be used I recommend looking into sessions of Udi Dahan. They are not related to AppFabric service bus but give you a great insight to the scenarios where it can be used.

You can download the full application code from this link

http://ge.tt/92ik9B8?c

Please do not mind the strange namespace name “DropBoxChatApp” as this is a story of another time.

Have fun guys

Advertisements

September 4, 2011

What to inject and what not to inject is the question..

Filed under: Unit Testing — ovaisakhter @ 6:51 pm

Some days back I was having a chat with a friend of mine regarding unit test and DI, we were going though his code and we started discussion on some of the service locators in his services code which I thought should also have been injected(DI or IoC), but he disagreed as he thought these locators are generic enough so they do not need to be injected or wrapped or abstracted. In the similar lines one my team members created a static configuration class in the core and was using it to access the configuration for the application, which started the discussion on how far your should go when it comes to dependency injection.

To answer this question I tried to look into an extreme example in my code and how it paid off in the end.

Recently in a project I wrote some services which were saving certain statistics about a website. An Asp.Net MVC application was calling my application controller service to store the  statistics. These statistics are saved in the context of a Date. In this scenario I can easily use a DateTime.UtcNow.Date inside my service for the Date and be done with it. The challenge comes when you have to write unit tests for this situation. We need to generate some sample data to test the system properly. Considering this situation I created an interface to inject the Date.

public interface IClock
    {
        DateTime Get();
    }

In my unit test project I created an implementation of this such that I can set the Date externally.

Now I created a method in my unit test project

internal class DateProvider : IClock
    {
        public DateTime CurrentDate;

        public DateProvider()
        {
        }

        public DateTime Get()
        {
            return CurrentDate;
        }
    }

I wrote a some code to generate random statistics and recorded the data created in the memory so that I can test it later on. Here is how the code looks like

           var daysToGoBack = random.Next(400, 1000);

           var dateTimeProvider = new DateProvider();
           var externallyControlledActionNotifier = new ExternallyControlledActionNotifier();
           var memorybasedStatisticsLogger = new MemorybasedStatisticsLogger(new IPBasedServerIdentityProvider(),
                                                                             new SiteStatisticsRepository(),
                                                                             externallyControlledActionNotifier, dateTimeProvider);

           for (var i = 0; i < 1000; i++)
           {
               dateTimeProvider.CurrentDate = DateTime.UtcNow.Date.Subtract(TimeSpan.FromDays(random.Next(0, daysToGoBack)));

               memorybasedStatisticsLogger.LogSiteView(surveyConfiguration.RowKey);
               testStatistics.Add(new Statistics { Day = dateTimeProvider.CurrentDate, PageViewed = true })
;

 

so now I am able to generate a random date in the past and I am able  to record in memory the data created so that I can test that correct data was created by my services or not.

As you can see that in this situation injecting a trivial thing like date has saved the day in terms of unit testing. So I believe that you should to inject every possible dependency as a convention, it may come handy at some time….

September 2, 2011

AppHarbor: Azure done Right(Simple)

Filed under: Cloud Computing — ovaisakhter @ 4:42 pm

Recently my boss heard something about a new cloud solution for Microsoft .Net applications. His description was “these guys I know have shifted from Azure to this new platform AppHarbor, they say it is much better and cheaper also, I think we should look into it”.

So I looked for the name and found the website www.appHarbor.com and the first thing that caught my attention was the slogan “Azure done right”, a pretty hefty claim I must say.

Development & Deployment

When you start looking into the platform the first thing you will observe is that the platform is very developer centric (which kind of makes sense). Startup time or learning curve to host your first application can be from little to almost none. Small if you have not used git(www.github.com), and none if you have used it.

So the idea is that you create an application on appharbor website, create a solution in visual studio, map these two things with git commands, push your code using Git , appharbor compiles it and executes the unit tests and deploys it. You can read more on

http://support.appharbor.com/kb/getting-started/deploying-your-first-application

and yes there is not additional requirements like you have in Azure. No special Apis, no special project types.

Scalability

By default you have one instance of an application and you can simply scale by providing the number of instances you want to run. The traffic will be routed between these instances by a load balancer.

Storage

appharbor provides an option to have SQL server or MySql database, database is free till 20 MB.  You can use the file storage on the servers but this storage is considered temporary and can be reset at anytime so do not get comfy Smile. appharbor recommends to you use some service like Amazon S3 for durable file storage.

Add-Ons

AppHarbor integrates with some service providers to provide you with an option to get additional services in your application, these services are called Add-Ons. These services mainly include NoSQL databases and caching solutions. You can get details from the following link

https://appharbor.com/addon

Mind you that these applications are not hosted at AppHarbor (That’s what I assume at least) which means they are not inside the same network, so Add-Ons like caching solutions seems to loose purpose for me.

Pricing 

AppHarbor provides extremely simple pricing model and enough free offers to help you to play to your hearts desire. You can have multiple applications  and pay nothing if you are using only one instance per application. You start paying 0.05 USD per hour for every additional instance of an application. Database is free till 20MB and you pay 10 USD for 10 GB SQL Server, and everything else is included in the price. More information at

https://appharbor.com/page/pricing 

Conclusion

I think that appharbor is a great offering for the very basic reason that it is good to have a choice. I believe this offering will be more exciting for startups, individuals and small organizations. I can almost say that this is a poor man’s (or a developers Smile) cloud.

As a software developer the working experience with appharbor is much better than Azure and in this sense they really are right in saying that “Azure made right” Smile

August 17, 2011

Unit Testing Database driven functionality with ADO.Net Entity Framework Code First

Filed under: ADO.Net Entity Framework,Unit Testing — ovaisakhter @ 5:39 am

The basic principal of writing a unit tests is that when you do a transaction you know the “expected” result and then you compare with the actual result that was generated, and if these results match you have a passed unit test. 

It is always interesting to write unit tests for Database services. Usually the problem that comes to mind is how to exactly predict the state of the database at the time when unit tests are running, so that the unit tests know what to expect. Some people may argue that you can mock out all the database functionality (mock the repositories), this idea may be very applicable in some scenarios but I usually do not go this way because of two reasons, 

  • It seems like to much work
  • Our applications are mostly data driven applications so there is not much to test anyway other than database transactions.

One way of knowing the exact state of the database can be to initialize(create) the database every time the unit tests are run. Once the database is created we might want to insert some initial data which is required for the unit tests.

I have been using Entity Framework Code first in my recent projects. Entity Framework provides you a very good way of achieving the two objectives I have mentioned in the previous paragraph.

EF provides a concept of Database initializers, these are implementations which define the strategy of how (rather when) the database will be created using our model (if you are a bit lost then I recommend to watch Code First Development with Entity Framework). These implementations implement an Interface called IDatabaseInitializer. There are some pre-backed strategies for database creation are provided with the EF. The one we are interested here is DropCreateDatabaseAlways. The name says it all, when using this strategy a database will be created every time code is executed(unit tests are run). To use the Initializers all you need to do is to write the following code before your unit tests are executed

System.Data.Entity.Database.SetInitializer<MyDbContext>(new DropCreateDatabaseAlways<MyDbContext>());

(Make sure you are using a local database server(SQL Express), things can really stressed if you are using a shared development server Smile.)

So now our database is created every time unit tests are run, now we need to create some data each time the database is created. For this you can inherit the  DropCreateDatabaseAlways class and override a method called Seed. using this method you add the initial records you want to create every time database is created.

Here is how the code will look like

public class MyUnitTestDatabaseInitializer : DropCreateDatabaseAlways<MyDbContext>
   {
       protected override void Seed(WilkeDbContext context)
       {
  //you can add any data using the context objected provided in the parameter

           context.SaveChanges();
           base.Seed(context);
       }
   }
The seed method is called just after the database is created by the the framework. Now all you need to do it to tell the framework to use your Database Initializer, and that you will do by modifying the code I wrote above.

System.Data.Entity.Database.SetInitializer<MyDbContext>(new MyUnitTestDatabaseInitializer <MyDbContext>());

so here you have it, now you can write the unit tests which are totally predictable and can run on any environment, be it your local machine or your Build Server. 

August 11, 2011

My name is Ovais and ICodeInCSharp , IDoPhotography,IWriteBlogs

Filed under: C# Coding,General Software Archiecture,Modeling — ovaisakhter @ 2:11 pm

 

I am a big fan of interfaces in a object oriented language like C#. I have been using dependency injection (IoC) in most of my previous projects and using DI your model contains many interfaces. I always try to spend some time in naming my model elements be it the name of interfaces, classes, methods or even the variables. When I look at code by other people one thing I usually notice is how they are naming their model elements.

Some days back I was looking into NServiceBus the things I noticed while doing that other than shear brilliance was the way different interfaces were named. for example IHandleMessages or IContainSagaData. This was a bit different way of naming then what I usually use as normally I would use something like IMessageHandler. I thought this is an interesting way of naming something like a class is saving my Name is MessageHandler and I Handle Messages. Sounds more natural more understandable.

I thought I should give this way of naming a try. In one of my projects, I tried to use similar naming.

The first place I need to create Interfaces are the repositories. So I started with names like IStoreData (instead of IRepository sounds boring doesn’t it?), IStoreDataInSql and went on and making names like IStoreStatistics.

Next place was the application controller where normally the interfaces for the services are named as IStatisticsService or IConfigurationService etc the names now became a bit different i.e. ILogStatistics, IManageSiteSurveryConfiguration, INotifyToExecuteAction INotifyWhenSiteSurveyConfigurationChanges.

Thought it was fun way of naming interfaces in some cases it become as stagnant as the old approach like IProvideThis and IHandleThat but in some cases the names become very interesting like INotifyWhenSiteSurveyConfigurationChanges and INotifyToExecuteAction.

August 10, 2011

JIT implementation for PivotViewer featuring Flickr.Net

Filed under: Silverlight — ovaisakhter @ 2:01 pm

I saw a my first demo of PivotViewer by a friend of mine some months back I was very impressed at that time, but then I forgot all about it. Then I saw it again some days back and thought to explore it a bit. As a developer I was not interested in the Excel tools provided by Microsoft. Having interest in photography the first thought that came to my mind was that a Flickr implementation of the PivotViewer could be very exciting. I went on tried googling a Flickr implantation for PivotViewer so that I can download the code run it and call it a day. But to my surprise I was not able to find one. So I thought to try to make one for myself. 

So the question was where to start I knew that there is a very nice library available for accessing Flickr service. The Library can be found here

http://flickrnet.codeplex.com/

and now the part was how can I provide the information to PivotViewer at run time. After a little search I was able to get this information from the following location

http://www.silverlight.net/learn/data-networking/pivot-viewer/just-in-time-sample-code

The sample code comes with prebuilt providers, I really loved the one for Twitter it let you visualize your own twitter feed in a way that you have never imagined, that was the point I became more interested in PivotViewer.

image

so you can filter your twitter feed using the @Mentions that you have done in your tweets and the #hashtags you have used. It kind of gives you a full overview of your thought pattern over a period of time in a very user friendly way.

When you open the solution in the Visual Studio you notice that there are projects in the solution.

PivotServer: This is the web application used to host the Pivot JIT implementation

PivotServerTools: As the name suggests contains all the important Data Objects and tools used in the implementation

SilverlightPivotViewer: The Silverlight project used to host the Pivot.

CollectionFactories: This is the Project we are most concerned with, in the project we have the implementations for different data sources. This is where we will add our very own Flickr implementation.

The Flickr Factory

To start the implementation of a JIT provider first thing you need to do it a bit of thinking. i.e. What are the different dimensions you will like to view your information. These are the dimensions using which you will be able to filter and sort your items. Flickr provides a concept of “Set” where each photo can belong to a set. So I chose the sets to be one of the Dimensions. The other two dimensions are I choose are Date Uploaded and Date Taken. I would have loved to use some of the the exif information as Dimensions but there was not way to get all the pictures and their exif information in one call.

Next thing you will need is an API key from Flickr you can get it from http://www.flickr.com/services/ after logging in.

So now the planning is done. We are ready to make our provider.

First Add a class to the CollectionFactories project and inherit it from CollectionFactoryBase

public class FlickrCollection : CollectionFactoryBase

public   FlickrCollection()
       {
           this.Name = "FlickrPhotos";

           this.SampleQueries = new string[]{
               "flickrUserEmail=ovaisbutt@yahoo.com",
               "flickrUserEmail=daredeagle@yahoo.com",
               "flickrUserEmail=ssatif@yahoo.com"
              
           };
       }

In the constructor you will set the name of your collection and also some of the sample queries that your application can handle. This information will be used to generate the UI by the framework which we will see later on.

To provide the Collection Information you need to override a method of this class i.e. MakeCollection

Now let us get some data from Flickr

First we need to get a Flickr user by the email provided.

FoundUser foundUser;
            var flickr = new Flickr(ApiKey);

            try
            {
                foundUser = flickr.PeopleFindByEmail(emailofUser);
            }
            catch(Exception exception)
            {
                return ErrorCollection.FromException(exception);
            }

flickrCollection.Name = string.Format("photos of {0}",foundUser.FullName);

then we get all the sets of the user

var allsets = flickr.PhotosetsGetList(foundUser.UserId);

now we can iterate through all the sets get picture information in them and start creating the Collection Items

var flickrCollection = new Collection();

foreach (var set in allsets)
            {

                var allPhotosInSet = flickr.PhotosetsGetPhotos(set.PhotosetId,PhotoSearchExtras.DateTaken | PhotoSearchExtras.DateUploaded );               

                foreach (var photo in allPhotosInSet)
                {
                    if (allPhotos.Contains(photo.PhotoId))
                    {
                        continue;
                    }

                    allPhotos.Add(photo.PhotoId);

                    var facetsForFlickr = new List<Facet>
                                              {
                                                  new Facet("Set", set.Title),
                                                  new Facet("Title",photo.Title),
                                                  new Facet("Photo Description",photo.Description),
                                                  new Facet("WebLink",new FacetHyperlink("Link",photo.WebUrl)),
                                                  new Facet("Date Taken", photo.DateTaken),
                                                  new Facet("Date Uploaded", photo.DateUploaded)
                                             };

                  

                    var url = photo.DoesLargeExist ? photo.LargeUrl : photo.SmallUrl;

                    flickrCollection.AddItem(photo.Title, null, photo.Description, new ItemImage(new Uri(url)), facetsForFlickr.ToArray());                    
                    
                }           

            }

the most important thing in this code is the List of Facets this the meta information you will provide about the picture. Once all the items are added to the collection now we need to tell how we want out meta information to be used and displayed.

            flickrCollection.SetFacetDisplay("Set", true, true, false);
            flickrCollection.SetFacetDisplay("Date Taken", true, true, false);
            flickrCollection.SetFacetDisplay("Date Uploaded", true, true, false);
            flickrCollection.SetFacetDisplay("Title", false, true, false);
            flickrCollection.SetFacetDisplay("Photo Description", false, true, false);

 

and finally return the collection.

Run the application and navigate to the following page silverlightPivotViewerTestPage.aspx page and you will see your collection shown in the dropdown

image

 

select one of the options and the Pivot will be rendered for that user (If you have many pictures it may take a while).

Here are some views from the result.

image

 

image

 

image

 

you can see this in action at www.wisdom.pk

August 5, 2011

Injecting Timer into Services

Filed under: Dependency Injection,Modeling — ovaisakhter @ 5:03 am

In the recent days while developing a project I had two services in my ApplicationController which were utilizing a Timer, i.e. they were instantiated with the Application and a timer was started when the services were instantiated and the services performed a certain action on the elapsed event.

I am using Dependency Injection in this project using Unity Container by Microsoft. I use Constructor Injection and define all dependencies in a BootStrapper class hosted present in my Application.

In my refactoring thoughts I came to a conclusion that the timer should be injected from the outside to the services as a Dependency. So I started modeling a Timer. Names like ITmer or ITimerService or even IKeepTime (recently I have been inspired by Udi Dahan’s way of naming interfaces like IDoThis and IHandleThat, fascinating stuff but more on that later). So ITimer was the winner in the end.

I started contemplating well it is merely a wrapper around the normal Timer class so it should just provide the features timer class provides. Then I thought but why should my service have the capability or even knowledge of the interval in which the Timer will elapse it only needs to know when to start the timer when to stop it and when it had elapsed. The Stop feature is only relevant so that the utilizing service can ask the timer to hold on while it is performing a action if it wants to Do one thing at a time (which is generally a good thing we should tell our Classes to do this also) Some may argue that why does Timer needs to know this it should just keep on banging on the door and our service should ignore any such notifications, I agree that this can be a way of thinking but read on I got it cleared for me later. Here is the final interface I came up with,

public  interface ITimer
  {
      void Start();
      void Stop();
      event EventHandler Elapsed;
  }

Now I am all happy made the implementation of the service all set for tomorrow when I will refactor my services to use my newly created model and called it a day. But then I started thinking about it again when I came home (Hope my wife doesn’t read my blog, but this blog is not about a new Chicken Biriayni  recipe so we are all set). I thought that for the services utilizing the Timer do not care that there is a timer running in the Timer service, for them this is a service that notifies them when the they should execute an action, and timer is just a concrete implementation of such a service they can even be a code listening to some event or even a UI sending a click of a button in which case being able to tell the service generating the notifications that the host Service is not entertaining any notifications at the moment may make sense. (may be disable a button during execution). Now let us call our newly thought of service INotifyToExecuteAction and let us change the names of the members to go with the new theme.

public  interface INotifyToExecuteAction
{
    void StartNotifications();
    void StopNotifications();
    event EventHandler Execute;
}

(by the way did I tell you that the renaming feature in Resharper is freaking awesome Ctrl R R on the method names of the interface rename them and it will change the method names in all the implementations also. How kool is that?)

so here we are then

August 3, 2011

Something beautiful while using AutoFixture

Filed under: Unit Testing — ovaisakhter @ 5:39 pm

In one of the projects I have the following class

public class SiteSurveyConfiguration : Entity
    {       
        public string CustomerName { get; set; }

        public string Website { get; set; }

        public string ShortDescriptionOnPopup { get; set; }

        public string HeadlineOnPopup { get; set; }

        public string LabelOfButtonOnPopup { get; set; }

        public int PercentOfUserWhoWillSeePopup { get; set; }

        public string CustomerLogoImageUrl { get; set; }

        public int ClicksByUserBeforePopShown { get; set; }

        public string ColorOfHeadline { get; set; }

        public string ColorOfShortText { get; set; }

        public string ColorOfButton { get; set; }

        public string FontOfPopup { get; set; }

        public int WidthOfPopup { get; set; }

        public int HeightOfPopup { get; set; }

        public bool ShowPopupInIFrame { get; set; }       
    }

While unit testing I needed to create a list containing 10 instances of this class along with different random data in each field.

var ListOfConfigurations = new List<SiteSurveyConfiguration>();
          var fixture = new Fixture();
          fixture.AddManyTo(ListOfConfigurations,10);

So this code created 10 instances of my class, added data to each field and added these instances to my list. I almost had tears of joy in my eyes Smile.

you can get more information about AutoFixture from http://autofixture.codeplex.com/

 

 

July 27, 2011

Why I like RavenDb as a .Net developer

Filed under: NoSQL Databases,RavenDb — ovaisakhter @ 1:00 pm

We often have discussion about amazing new NoSQL databases like CouchDB, Casendra and Redis.

Usually when I am asked about my choice for a NoSQL database I always say “I will use RavenDb”. I have used RavenDb in one of my projects and I am quite happy from the results, and in my experience if you do it right RavenDb performs amazingly well under extreme load scenarios (If not done right you can seriously screw up things but that’s a talk of another time).

As I mentioned I am generally very happy with the performance provided by RavenDb but I have an other reason for reason to use RavenDb,  that I am a .Net developer, and RavenDb is a Database build on top of .Net. So the learning curve for .Net developer to start using it is negligibly small.

Here I will describe the process of starting a new RavenDb endeavor

“Installing” RavenDb

To start using RavenDb download the binaries from http://ravendb.net/download unzip the file go to the server directory and hit the Raven.Server.exe and here you go you are up and running with a brand new Instance of RavenDb.

Try to navigate to http://localhost:8080/ in your browser and you will be able to see the All new Management Studio for RavenDb built in Silverlight. (The interface provides you can option to create sample data if you don’t want to get your hands dirty in code right now, neat idea I say?)

Using RavenDb

RavenDb server interacts with the client using RESTful web services and the response is in the form of JSON. For .Net developers a very extensive .Net client API is also available, which makes your life a lot easier. Using the client API it is extremely simple to get started.

Now you have you server up and running all you need to do is to write the following code in your application

    var documentStore1 = new DocumentStore { Url = “http://localhost:8080″ }.Initialize();

            using (var session1 = documentStore1.OpenSession())
{
session1.Store(new User { Id = “users/ayende”, Name = “Ayende” });
session1.SaveChanges();
}

and here you go you just saved your first record or document as it is called in this neck of wood into the database, and here is what you need to do to get it back.

using (var session1 = documentStore1.OpenSession())
{
var myUserBackFromRaven = session1.Load<User>(“users/ayende”);

                Console.WriteLine(myUserBackFromRaven.Name);
}

Simple ?

and if you need to query your documents all you need to know if how to write a LINQ statement.

var users = session1.Query<User>().Where(x => x.Name.StartsWith(“A”));

             foreach (var user in users)
{
Console.WriteLine(user.Name);
}

Ravendb provides you a possibility to be able to index your documents for faster retrieval of information. The best part is that all the RavenDb index definitions are written using LINQ which makes the learning curve extremely small.

Here is how you define an index on the User Name in side “Raven Management Studio” web interface.

image

or alternatively you can create an index from inside the code.

public class UsersNameIndex : AbstractIndexCreationTask<User>
{
public  UsersNameIndex()
{
Map = users => from user in users
select new { user.Name };
}

    }

and then query this index from the code like

var users = session1.Query<User>(“UsersNameIndex”).Where(x => x.Name.StartsWith(“A”));

                foreach (var user in users)
{
Console.WriteLine(user.Name);
}

Conclusion

The purpose of this blog is not to give you a tutorial of RavenDb rather it is to show you that how terribly simple it is for a .Net developer to start using RavenDb. I believe if you are a .Net developer you will be up and running with RavenDb in the matter of hours and that is why I like RavenDb as a .Net developer.

Links

www.Ravendb.net

July 14, 2011

Let Google do it

Filed under: General Software Archiecture — ovaisakhter @ 10:59 am

One question I always ask from my tech savvy friends “What is the best way to search MSDN(Microsoft Developers Network) website” and most of the time I get the answer I am looking for i.e. “Search it with Google” and this is true I have almost never been able to find any thing on MSDN using search provided on MSDN. I usually do it on Google for it.

Let say I am looking for something related to Microsoft development tools and Facebook, I will go to Google, will start writing “MSDN” and then “Facebook” and it will give me an option search suggestion like “MSDN facebook sdk” and if you search the first link will be the correct link life does not gets any better. Try doing this on MSDN (or on Bing for that matter Smile).

I think that if you do not have a special need to implement a Full-text search then don’t  even bother, Google will be doing a much better job then you anyway. You may want to spend the time saved from search implementation in making your site more Search Engine Friendly.

« Previous PageNext Page »

Blog at WordPress.com.