Creating the Family Page – Part 2, Getting started

Last time I described what I want to do.

This time I will:

  • Create the basic web site from a template.
  • Install the necessary frameworks
  • Remove the parts of the template that I don’t want.
  • Publish web site to Windows Azure

So, this time will be pretty simple stuff, but the point of this is to take baby steps, and let every post in the series focus on a specific topic.

Creating the web site from a template

I open Visual Studio 2013 and select “New Project…”

image

I give the project the name “TheFamilyPage” and I place it place it in a folder of my choice. For this project I have already created a GitHub repository, so I will be able to share the code. I choose the folder for my repository.

The project type I have chosen is “ASP.NET Web Application” which in Visual Studio 2013 is the entry point for all types of web pages. Press “OK” to get to the next page:

image

Here I choose the MVC project and I don’t add anything else. But if you wanted to include Web API or Web Forms this is the place to do it.  Next I click “Change Authentication”

image

This gives me different options for handling user accounts. I want my users to be able to login, and I am not running an intranet site or anything like that, so I keep the option for “Individual User Accounts”. This will create code to keep user account data in a database. The default is to use a database of type “LocalDb” which has the database in a simple file in the project. This is fine so we press OK and OK.

Now Visual Studio creates the project for us. After a little while we have project looking like this:

image

Install the necessary frameworks

Bootstrap and Entity Framework is part of the project along with a bunch of other stuff. Before I do anything else I go to the menu Tools –> NuGet Package Manager –> Manage NuGet Packages for solution…

Her I choose to “Update All” – this is the only time I recommend doing this. Normally I would only update the packages, that I need to update. This is because a lot of references in your code might get screwed up, so it is better to change on thing at a time.

Next I go to the menu Tools –> Nuget Package Manager –> Package Manager Console.

In the console window that pops up, type “Install-Package angularjs”

image

Remove the parts of the template I don’t want

At this point if I run the site locally, I will see something like this:

image

At this point I want to keep “Home”, “Register” and “Log in”. The about and contact pages are not need by this site.

I will removed the unwated stuff in the project:

– Under Views/Home/ remove About.cshtml and Contact.cshtml

In the HomeControlle.cs remove the About and Contact methods:

image

In View/Shared/_Layout.cshtml remove the navigation code for contact and about:

image

I also change “The Application” to “The Family Page”.

In Views/Home/Index.cshtml I remove all the boilerplate text and put in my own placeholders.

image

Now the page looks like this:

image

This is the basic site, that we are going to build on. Now we only have one thing left.

Publishing the site to Windows Azure

NOTE: This part requires you to have a Windows Azure account. If you don’t have one, you can get a trial by going to windowsazure.com.

Right-click on the project in Solution Explorer and select Publish.

If you are asked to log in to your Microsoft account then do so.

image

Select “Import…”

image

Select “New…”

image

Fill out infomration about site name and the databse server you want to use. We need the database for later. Then press “Create”

image

Press “OK”

Press “Next”

image

Choose the connection string to use.

The press “Publish”

After a little while the site will be published and available on the URL you chose. In my case that will be: http://thefamilypage.azurewebsites.net/

image

Conclusion

We now have a totally bare bone web site published to Windows Azure, and we have installed and updated the frameworks we are going to use.

Next time we will look at the user accounts and we will start to use Entity Framework code first migrations.

Advertisements
Posted in C#, HTML5, Web | Tagged , , , , | Leave a comment

Creating the Family Page – Part 1, Setting the Scene

This is the first post in a series where I will create a new website for my family. While doing it I will blog about my progress. Normally I do backend stuff or LOB applications with WPF or Windows Forms. HTML, JavaScript, CSS is not unknown to me, but I am inexperienced in that area. In each post I will be making baby-steps toward a finished web site.

My current family site is used for the family members wish-lists and pictures, but it is based on a very old Umbraco version. This time I will try to create everything myself.

The (initial) target:

A web site that contains

  • A nice front page.
  • Wish-lists for each family member. Every member of the family must be able to log in and update their wish-list.
  • Pictures. It shall be possible to upload pictures (when logged in), and group them and show them by category.

The tools:

I have decided to use the following tools and frameworks:

  • BootStrap 3
  • AngularJS
  • Entity Framework 6 – Code First.
  • Hosting in Windows Azure.
  • Pictures stored in Azure Blob Storage.

Conclusion

This end the first part, which probably will be the only part without any code. In part 2 I will be creating the basic web site.

The course it set, but I am open to input regarding features or possible use of tools.

Posted in C#, CSS3, HTML5, HTML5, Ikke kategoriseret, javascript, Web, Windows Azure | Tagged , , , , | Leave a comment

Review of “Making Sense of NoSQL” by Dan McCreary and Ann Kelly

This is a book for manager and developers who wants the broad understanding of what NoSQL is and isn’t. As a developer that knows nothing about NoSQL, you will not be able to read this book and begin implementing a NoSQL solution. For the details of how to program against these databases you will have to look elsewhere (and the book never promises that you will be able to). You will however know and understand the different kinds of NoSQL databases and when to use which type. This is explained really good – Both with technical details and examplified with case studies.

 

The book is split into four parts:

The first part is an introduction to NoSQL concepts and the benefits of NoSQL. This part is a bit annoying, because it is repeatetly said that NoSQL is better and scales bettder than relational databases, but I don’t feel the author gives an explanation as to why this is true – it feels a little like the author is preaching NoSQL, and at least there is no doubt he is a fan. This is rectified plenty in the later sections, so if you are like me, just push through, and you will get to the good stuff.

The Second part is a walkthrough of the different kind of databases, bot the relational and NoSQL databases. This gives a good understanding of what each type does well and not so well.

The third part is about NoSQL solutions with discussions about scaling, search and performance of different systems with references to real world solutions.

The fourht and last part is about the use of functional programming and utilizing the parallelism of NoSQL systems, which typically have many thousand CPUs.

 

This is a great book to get an overview of what NoSQL is and when to apply it.

Posted in Ikke kategoriseret | Leave a comment

Event delegates and exception handling

Delegates

This blog post will focus on handling exceptions thrown by event delegates.

But first we will briefly discuss what a delegate is. If you know C or C++ it is natural to think of delegates as function pointers. Why is this handy? Let’s say that I have an API that will read a list of car objects from a database and return that list to the user. Something like this:

    public IEnumerable GetCars()
    {
      var cars = new List<Car>();
      //Get all cars from database
      return cars;
    }

    public class Car
    {
      //define car properties like color, weight, brand etc.
    }

Nothing fancy here. Now lets say we want to let the users of our API to be able to filter the cars – for instance only return red cars. We could make a new API method to return a specific color of cars, but we really can’t guess what the user would like to filter on – it would be much nicer if the user could provide us with at filter method to use.  First we define what the filter shall look like, and then we use it in out API:

   public delegate bool Filter(Car car);

    public IEnumerable GetCars(Filter filter)
    {
      var cars = new List<Car>();
      //Get all cars from database and the apply filter
      return cars.Where(car => filter(car));
    }

Now we can define and use a filter that returns red cars:

    public bool CarIsRed(Car car)
    {
      return car.Color == ConsoleColor.Red;
    }

    public void useGetCars()
    {
      var filteredCars = GetCars(CarIsRed);
      //do sutff with cars
    }

But the user could supply any kind of filter he desired.

So that was delegates – what is an events?
And how is it different from a delegate?

A C# event is collection of delegates that can be called by the event. So the event itself is not a delegate but you can add delegates to it using the += operator and remove them again using the –= operator.

In the following example a timer is startet, and every second the timer calls the DoTick method. The DoTick method fires the Tick event if there are any subscribers. In our case there are two subscribers Tick and Tick2 – that will write to the console.

  public class Program
  {
    private static void Main(string[] args)
    {
      var t = new Ticker();
      t.Tick += t_Tick;
      t.Tick += t_Tick2;

      Console.ReadKey();
    }

    private static void t_Tick2(object sender, EventArgs e)
    {
      Console.WriteLine("Tick2");
    }

    private static void t_Tick(object sender, EventArgs e)
    {
      //throw new Exception("boom!!");
      Console.WriteLine("Tick1");
    }
  }

  public class Ticker
  {
    private Timer timer;
    public event EventHandler<EventArgs> Tick;

    public Ticker()
    {
      timer = new System.Threading.Timer(DoTick, null, 1000, 1000);
    }

    private void DoTick(object state)
    {
      if (Tick != null)
        Tick(this, new EventArgs());
    }
  }

This works fine – but in the t_Tick method I have hinted at a problem. What if one of the event handlers (subscribers) throws an exception? That is the topic of the next section.

What happens if one of the event handlers throws an exception.

As the code in DoTick is written now the application will be terminated – not so nice. If you are in complete control of your application you should have normal exception handling in each event handler, so execptions aren’t propagated back to the place where the event was fired from.

What if I’m not in complete control of the application?

Maybe your application has support for third party plugins and the event handlers could belong to two different plugins provided by different manufactures. One of the plugins throws an exception, and we are not interested in our application going boom! The first thing you try is to rewrite DoTick like this:

    private void DoTick(object state)
    {
      try
      {
      if (Tick != null)
        Tick(this, new EventArgs());
      }
      catch (Exception)
      {
        //do exception handling, log the error etc.
      }
    }

Now our application doesn’t crash anymore, but what happens is that the  event handlers are called one at a time, and then an event handler throws an exception, it is caught, but the rest of the event handlers will not be called, meaning that one defect event handler will ruin it for everybody else.

Instead we can use the fact that an event contains a collection of delegates and that each delegate can be invoked by calling DynamicInvoke on it:

    private void DoTick(object state)
    {
      if (Tick != null)
      {
        foreach (var @delegate in Tick.GetInvocationList())
        {
          try
          {
            @delegate.DynamicInvoke(this, new EventArgs());
          }
          catch (Exception)
          {
            //do exception handling, log the error etc.
          }
        }
      }
    }

Now only the defect event handler will fail and every body else will be able to do their job.

I don’t want to write that ugly code every time I fire an event.

Yes the code is somewhat ugly and it is quite a lot to write just so we can fire an event. I already think that having to check for null is kind of stupid, since that is what you do every time – and this is event worse. Therefore I suggest to create an extensiuo method, that works for events that use the EventHandler signature. (which is what is generally recommende, so of corse you use that for all your event handlers).

  public static class Utils
  {
    public static void FireEvent<T>(this EventHandler evt, object sender, T eventArgs)
    {
      if (evt != null)
      {
        foreach (var @delegate in evt.GetInvocationList())
        {
          try
          {
            @delegate.DynamicInvoke(sender, new EventArgs());
          }
          catch (Exception)
          {
            //do the exception handling
          }
        }
      }      
    }
  }

Now that we have written this code once and for all, and we can fire events like this:

private void DoTick(object state)
{
  Tick.FireEvent(this, new EventArgs());
}

Wow, that’s really nice

Yes it is – you should of corse still make sure that the error handling in the try-catch in the extension method do something appropriate like logging the error, disble the offending plug-in or whatever makes sense in your situation.

Posted in C# | Leave a comment

Trying out Windows Azure Storage

I am part of the team behind a set of web pages at Myvoices.com where you can search for voice talents (people speaking in commercials, narrating documentaries etc.)

One of the features of these sites, is that you get to listen to some of the work, these people have done before. This means we have a lot of mp3-files stored online at a web-hotel, and in the foreseeable future we will exceed the amount of space available. Therefore I have started to look at some alternatives – one of which is Windows Azure Storage.

I found this guide to get me started: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/ (from now on: The Guide)

I had some problems however (the reason for this blog post). And I deviated from the guide in that I did not create a Windows Azure account – I simply used the built-in development test account, since I wanted to check out the programming model first. Also, you should note that in regard to The Guide mentioned above, I use .Net configuration, not Cloud Service.

NuGet or SDK? NuGet first…

The Guide says that I can get the relevant assemblies with NuGet, so I didn’t bother to get the SDK. I could write some code and get it to compile without too much trouble. When I wanted to test it I ran into problems.

Connection string for DevelopmentStore

First there was the connection string for azure. I use the following code to connect:

var connectionString = ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString;
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
blobClient = storageAccount.CreateCloudBlobClient();

The default string looks like this:

connectionString="DefaultEndpointsProtocol=https;AccountName=[AccountName];AccountKey=[AccountKey]"

When using the test account you can drop AccountName and AccountKey, and simply set UseDevelopmentStorage=true. I tried this:

connectionString="DefaultEndpointsProtocol=https;UseDevelopmentStorage=true"

This connection string does not parse. It turns out that the only thing in the connection string shall be UseDevelopmentStorage = true. (It is possible to add proxy-information as described in The Guide.)

connectionString="UseDevelopmentStorage=true"

NuGet or SDK? On second thought: SDK

Next I wanted to set up a container for our media files. I chose to call it “Media”:

container = blobClient.GetContainerReference("Media");
if (container.CreateIfNotExists())
{
   container.SetPermissions(
                           new BlobContainerPermissions
                             {
                               PublicAccess = BlobContainerPublicAccessType.Blob
                             });
}

I could not connect to the server. When you are using the development test account you are supposed to connect to a storage emulator – and you don’t get the emulator with NuGet. So I also downloaded and installed the Windows Azure SDK. Then I had the Storage Emulator – you have to start it yourself from the start menu. Restarting my program, I could now connect to the server.

Container name

I immediately ran into the next problem. I received this error: “The remote server returned an error: (400) Bad Request”. It turns out that container names can only contain lowercase letters. So after changing “Media” to “media” it worked – I now have a container. The rest seems to be as described in The Guide – uploading, download, listing container contents and so on.

The structure of Azure Blob Storage:

Account

When you use Azure Storage for real, you will make a named account, that will determine the URL where your files can be found:

http://<storage account>.blob.core.windows.net/<container>/<blob>

Container

The container is somewhat like the root of a hard drive. You connect to the container before you do any blob manipulation,

Blob

The blob is simply data – like a file. The name of a blob can contain almost all characters, but should not end with . or / or a combination of these. The URI for the file is created using the .Net URI class and this will strip off these characters. But in general / is allowed as part of the blobs name (the filename).

This is because there is no directories in the containers data structure. So the answer to one of my first questions: How do you create a directory in Azure Storage, is: You don’t. There is no such thing as a directory. But to create structure you can name your blobs like this “MySimulatedDir/MyBlob”.

This section of The Guide http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/#header-8 show how to list all the files in the container like they are in a directory structure, by using virtual folders.

Posted in C#, Cloud Computing, Windows Azure | Tagged , , , , | Leave a comment

The #DevReach .Net conference in Sofia, Bulgaria

This is the second year in a row, I attended the DevReach conference. Last year I got an invite from Telerik, because I used some Telerik Silverlight components – this made me eligible for a discount. This year I simply joined the early bird programme. The early bird price was below 160 EUR for two days with 6 tracks including an amazing after party, where you could meet all the speakers and the other attendees that also chose to buy a VIP pass. The nearby five-star hotel was 80 EUR a night and the flight to Sofia is also quite affordable if you live in Europe. This year they also added a pre-conference day with four half-day workshop.

Does these prices mean it is a discount conference?

Granted: This is all very affordable, but I assure you there is nothing discount about this. It is a great conference with international speakers of a very high class. At the time of this writing the speaker list is still available at www.devreach.com.

Topics covered include agile, testing, architecture, mobile developement, Windows 8  development, HTML5, cloud, web – also how to make cross-platform apps, with as much shared code as possible.

I can only recommend that you follow @devreach on twitter or on Facebook, so you get notified when the registration for next years conference opens. And when it does, tell your friends! You will not regret it.

Posted in Conference | Tagged , , , | Leave a comment

LINQ – the order of elements when using Where()

Last week I was asked if the order of elements found using a where clause was guaranteed to be the same as the order of the original collection. That question is hard to answer.

In the normal case (where nobody has overwritten any framework methods or any such thing) the answer in practise is yes, the order will be the same, because Where(), simply enumerates over the collection one element at a time, and if the elements parses the condition it is returned. This small test program demonstrates it – I have used a SortedDictionary, because it makes it easy to see the order.

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
 class Program
 {
  static void Main(string[] args)
  {
   var sd = new SortedDictionary<string, string="">() { { "b", "test1" }, { "a", "test2" }, { "c", "test3" } };
   Console.WriteLine("The dictionay");
   foreach (var kv in sd)
   {
    Console.WriteLine(kv.Key + " - " + kv.Value);
   }
   Console.WriteLine("the dictionary where Key != b");
   foreach (var kv in sd.Where(x => x.Key != "b"))
   {
    Console.WriteLine(kv.Key + " - " + kv.Value);
   }
   Console.ReadKey();
  }
 }
}

And the output is as expected:

The dictionay
a – test2
b – test1
c – test3
the dictionary where Key != b
a – test2
c – test3

Does that mean that we can conclude that the order of elements returned from Where() will be the same as in the original collection? In the current version of the framework it will. In the general case the Where method is implemented like this:

public static IEnumerable Where(this IEnumerable source, Func<tsource, bool=""> predicate) {
 return new WhereEnumerableIterator(source, predicate);
}

In the real code there are special implementations for List<T>, arrays Iterator<T>. But here we look at the general case. In the WhereEnumerableIterator the main part of the MoveNext method is implemented like this:

while (enumerator.MoveNext()) {
 TSource item = enumerator.Current;
 if (predicate(item)) {
  current = item;
  return true;
 }
}

(enumerator is initialized with source.GetEnumerator())

So we see the order of the original collection must be preserved.

It should be noted, however, that nowhere in the documentation for Where() is it guaranteed to preserve the order. It is only stated that Where() will return an IEnumerable<T> containing the elements that satisfies the condition.

This means it probably isn’t safe to rely on the ordering in the future.

Further somebody might come by and try to make your foreach loop faster by adding an AsParallel() – and that will certainly ruin the order, so if order is important it might be better to add an OrderBy() – that will make it clear that order is important. (or insert a comment to the same effect).

A funny side note: In the documentation for Parallel LINQ it is stated that: Therefore, by default, PLINQ does not preserve the order of the source sequence. In this regard, PLINQ resembles LINQ to SQL, but is unlike LINQ to Objects, which does preserve ordering. See http://msdn.microsoft.com/en-us/library/dd460677.aspx – so it is sort of documented that order is preserved – just not in the LINQ Where() documentation. The question is if this is good enough to guarantee that order is really preserved in the future also. (maybe I just haven’t found the place in the documentation for LINQ where it says order is preserved…)

Posted in C#, Linq | Tagged , , , , , , | Leave a comment