Building Laaalallaaa Share

My tally for Windows Phone 7 applications isn’t too high. Not compared to some of my friends at Three Red Cubes. In my defense though, I’ve been working on several MVC projects that are pure fun to work with. But to close the gap, I got down and dirty and wrote Laaalallaaa Share (♫share).

The application is really simple but it uses a very interesting .Net namespace Microsoft.Xna.Framework.Media and some classes from Microsoft.Phone.Tasks.

MediaPlayer

This static class exposes a number of methods and properties to access the media player (duh!) and the library.

For example I used the properties in MediaPlayer.Queue.ActiveSong to find the details of the current song being played. MediaPlayer.State holds the status of the media player, use it to find the state of the player.

This class also exposes a number of events such as ActiveSongChanged or MediaStateChanged that lets the application know if the current song has changed or if the song has stopped/started playing. Handy stuff.

MediaPlayerLauncher

Launchers and Choosers in the Windows Phone world give us developers access to a number of operating system and user functionalities.

The MediaPlayerLauncher is used to “start the media player and play the media file you specify.” But you don’t necessarily have to play a file, you can just take the user to the music player, like I did. Read more about this class.

ShareStatusTask

As of Windows Phone 7 Mango (Windows Phone OS 7.1), this class exists in the Microsoft.Phone.Tasks namespace. This class launches “a dialog that enables the user to share a status message on the social networks of their choice.”

By setting the Status property and calling Show you could get to the People Hub’s “Post a Message” page and let the user post away. Read more about how to use this task.

There you are, three nifty little classes that do really cool things that I hope you’ll use in your next application. Say… when you sign up for The Developer Movement and win a bunch of expensive cool gadets or Imagine Cup and win a lot of money!

Advertisements

Implementation of a Generic Repository Beauty, with Ninject the Beast

I really should be studying. But why study when I can blog right? Well, I have been meaning to write this post for a while now, and here it is.

The Repository Pattern is invaluable when working with the data, particularly in MVC. It encapsulates a lot of redundant and hopefully generic operations, I use it to encapsulate operations on the Entity Framework Code First ORM. My implementation doesn’t use Unit of Work which tracks changes and updates the database accordingly. Instead, I let myself decide. It’s not that bad.

The Context

Firstly, there is the context interface. It can expose methods, but I didn’t need to. Let’s imagine this context is for a shop.
This interface is important because it’ll be used by Ninject to wire everything up.

public interface IShopContext
{
}

The concrete implementation of the context might look like this.

public class CareContext: DbContext, IShopContext
{
    public DbSet<Fruit> Fruits { get; set; }

    public ShopContext()
    {
    }
}

The Entities

Fruit above is an entity and there can be many more. The entities derive from an abstract Identity class. What it is, is pretty obvious.

public abstract class Identity
{
    public Guid ID { get; set; }
}

Now let’s look at the example Fruit.

public class Fruit: Identity
{
    public string Name { get; set; }
    public int AmountInShop { get; set; }
}

The Repository

public interface IRepository<TEntity> where TEntity : Identity
{
    TEntity Add(TEntity model, bool persist = false);
    TEntity Get(Guid id);
    IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> predicate);
    IEnumerable<TEntity> GetAll();

    TEntity Update(TEntity model, bool persist = false);

    void Remove(Guid id, bool persist = false);
    void Remove(TEntity model, bool persist = false);

    void Save();
}

So these are some of the operations that the repository will perform. As you can see, I take care of the persistence using the optional parameter persist.

And now… the concrete implementation of the repository.

public class Repository<TEntity> : IRepository<TEntity> where TEntity : Identity
{
    private DbContext Context;
    private DbSet<TEntity> DBSet;

    public Repository(IShopContext context)
    {
        Context = context as DbContext;
        DBSet = Context.Set<TEntity>();
    }

    public TEntity Get(Guid id)
    {
        TEntity model = DBSet.Find(id);
        return model;
    }

    public IEnumerable<TEntity> Get(Expression<Func<TEntity, bool>> predicate)
    {
        return DBSet.Where(predicate).AsEnumerable();
    }

    public IEnumerable<TEntity> GetAll()
    {
        return DBSet.AsEnumerable<TEntity>();
    }

    public TEntity Add(TEntity model, bool persist = false)
    {
        model.ID = Guid.NewGuid();
        DBSet.Add(model);
        Save(persist);

        return model;
    }

    public TEntity Update(TEntity model, bool persist = false)
    {
        Context.Entry(model).State = EntityState.Modified;
        Save(persist);

        return model;
    }

    public void Remove(Guid id, bool persist = false)
    {
        TEntity model = DBSet.Find(id);
        Remove(model, persist);
    }

    public void Remove(TEntity model, bool persist = false)
    {
        if (model != null)
        {
            Context.Entry<TEntity>(model).State = EntityState.Deleted;
            Save(persist);
        }
    }

    public void Save()
    {
        Save(true);
    }

    private void Save(bool persist)
    {
        if (persist)
        {
            Context.SaveChanges();
        }
    }
}

There you have it. It’s very simple to read really. It just spells out the methods defined in the interface and also provides logic for persistence when you want it.

The Ninject

Now all of this is pretty useless without Ninject. You’ll have noticed I used Inversion of Control while implementing the repository. Ninject is available on Nuget.

While registering the services on Ninject, I can tell it to provide a ShopContext when a IShopContext is required. The repository is bound to an interface, this context can be a development or deployment context, depending. Also, since I want to use the same context always, I bind it using ToConstant.

As for when a repository operating on a certain entity is requested, Ninject finds its type and provides accordingly.

private static void RegisterServices(IKernel kernel)
{
    IShopContext shopContext = new ShopContext();
    kernel.Bind(typeof(IShopContext)).ToConstant(shopContext);
    kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>));
}

Hope that wasn’t too long a post, it probably is my longest so far. Till next time, then.


MVC3 Docking on AppHarbor and Entity Framework Code First

So, I spent last few hours figuring this out. AppHarbor is pretty nice. AppHarbor is free for one application, one database and it does work with SQL Server CE. I just deployed a stripped down version of one of my MVC projects there and it’s pretty smooth. So, here’s a run down of how it’s done, so that someone else might not need hours.

Stripping the project down was a breeze, you’ve got to love Object Oriented design, it’s beautiful. Deploying the project was a no-brainer too, if you’ve had some experience with Git. But testing, as ever brought out the issues.

I was using Entity Framework Code First (EFCF) as my ORM and it likes to drop databases. I didn’t realize it since it’s natural for EFCF to. And for good reason too, for when you change your models. On AppHarbor, you don’t get permissions to create databases. Thus the problem.

But no fear, NuGet to the rescue. Again. Actually, community to the rescue. There’s a workaround for EFCF’s DropCreateDatabases it’s DontDropDbJustCreateTables. You can find here on NuGet. It plugs in beautifully to your application and all you need to do is enter your context name. Also, you will have to get a new database from AppHarbor since already EFCF dropped it.

Also the connection string should include a providerName otherwise, exceptions!

<connectionStrings>
    <add name="connection string name"
         connectionString="Server=db003.appharbor.net;Database=dbXXXX;User ID=dbXXXX;Password=YourPassword;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

More DatePickers!

In continuation of my previous post on jQuery UI, I updated the project on CodePlex with a demo of how multiple date pickers can be included. It’s very simple, just requires a little bit of nifty JavaScript. In fact, it’s a one-liner.


$("*[id*=date]").datepicker();

Yep! That simple. This will activate the date picker on every element whose id has "date"-something in it. Like so:


@Html.TextBoxFor(model => model.DateTime1, new { id = "date1" })
@Html.TextBoxFor(model => model.DateTime2, new { id = "date2" })

Here’s a screenshot of how that looks:

Get the project from CodePlex and play around. I will be updating it soon again.


Blueprint CSS Framework in MVC3

Blueprint CSS Framework is a very simple and neat but oh-so-powerful CSS framework that I love to use in my MVC projects. It significantly reduces the time it takes to improve the aesthetics of a new eww-looking MVC project. Furthermore, it provides a very solid, 960px grid CSS system to build on. So, you won’t have wasted time working with it.

With the advent of the super amazingly sexy Razor view engine (read more about its super amazingly sexiness blogged about by Scott Gu and many others), using Blueprint feels even more intuitive.

So, without further ado, here are the steps to how it can be set up.

Step 1: Get it! Download the files.

Step 2: Stare at awe at the files. The files that should interest you are in the /blueprint/ directory. Of these, ie.css, print.css, screen.css are minified versions of files you will find in the /bluprint/src/ folder.

Step 3: Include ’em. Depending on your needs, you may or may not want to include print.css. Either way, include them in _Layout.cshtml that you can find in your /Views/Shared/ folder. Of course, remember to include the files of your interest to your project. If I put put them in my /Content/ folder, for example:

<link href="@Url.Content("~/Content/screen.css")" rel="stylesheet" type="text/css" />

Step 4: Style away!

<div class="container">
    <div class="span-24 prepend-top append-bottom last">
        <h1>Some Title</h1>
    </div>
    <div class="span-24 last">
        @RenderBody()
    </div>
</div>

You might have guessed that the CSS classes like container, prepend-top etc are being provided by Blueprint. What do they do? Exactly what they sound like. For example, the span-24 CSS class renders a column across the page 24 times span-1 which is 30px wide, by the by.

That should get you started with the framework. I’ll be writing a more extensive tutorial on Blueprint soon, so check back.


Serialization and Isolated Storage in WP7

Reading XML in and out from the provided Isolated Storage is important and quite simple, as the following code snippets illustrate. I have the methods constrained to a generic so that I can use this across all the WP7 applications that I am writing.

To write, the Isolated Storage allocated is called on by IsolatedStorageFile.GetUserStoreForApplication() where objects, XMLized by XmlSerializer serializer are written by the XmlWriter writer. The code is pretty telling, I think, so I’ll spare you the explanation.

public static void Write<T>(T obj, string fileName)
{
    XmlWriterSettings writerSettings =
            new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t"
            };

    try
    {
        var store = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Create);

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (XmlWriter xmlWriter = XmlWriter.Create(stream, writerSettings))
        {
            serializer.Serialize(xmlWriter, obj);
        }

        stream.Close();
    }
    catch (Exception emAll)
    {
        throw emAll;
    }
}

To read XMLized objects from storage, the following function is sufficient and pretty self explanatory. Again, the function is constrained to generic objects so that you can go crazy on what types you want to use it with.

public static T Read<T>(string fileName)
 {
     try
     {
         var store = IsolatedStorageFile.GetUserStoreForApplication();
         IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);

         XmlSerializer serializer = new XmlSerializer(typeof(T));
         return (T)serializer.Deserialize(stream);
    }
    catch (Exception emAll)
    {
        throw emAll;
    }
} 

Of course, you will have to modify Exception handling to suit your needs, these are only generalized samples. Also, the code can be improved, so write back with improvements that you might have come up with.


ASP.Net MVC2 and Full-Text Searching

Implementing searching on your site has never been easier. There are many tools out there such as Lucene.Net which is amazing, but if the scale of the project is not too large, it’s probably much easier to enable Full-Text Search on the tables and query results out of the catalog.

I am using ASP.Net MVC2, which provides much flexibility and is amazing fun to work with. Things can be set up to your taste as long as you follow the conventions laid out. Here’s how I have it set up.

Model
I used the following model to retrieve the search text and store the results once they were queried and parsed from the database using a searching service I am going to detail in a bit.

public class SearchEntry
    {
        [Required]
        [DisplayName("Search Keyword(s)")]
        public string QueryText { get; set; }

        public IList<Product> ResultProductsList { get; set; }
    }

The annotations [DisplayName("Search Keyword(s)")] and [Required] help display and validate the model. These can be found in System.ComponentModel and System.ComponentModel.DataAnnotations respectively.

Views
Again, how you want to set the views up is up to you. I have two views and a partial view. One view as a home page, for example. Another to display the results. The partial view is a form for searching which I can reuse as I need to.

The partial view is strongly typed to the SearchEntry model.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.SearchEntry>" %>

    <% using (Html.BeginForm("Submit", "Search", FormMethod.Get)) {%>
                Enter keywords to search:
                <%: Html.TextBoxFor(model => model.QueryText) %>
                <input type="submit" value="Search" />
                <%: Html.ValidationMessageFor(model => model.QueryText,
                                              "At least one search keyword is required") %>
    <% } %>

Pretty straight forward!
The two views are really straight forward too. The home page for example, just renders the form by calling an action called SearchForm defined in the Search controller. You can change that around for sure.
Instead of using Html.RenderAction which is found in System.Web.Mvc.Html you can also use Html.RenderPartial too, depending on how you like your coffee, and needs.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Home
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <% Html.RenderAction("SearchForm", "Search"); %>

</asp:Content>

The results view may look any way you would like it to be. Again, this view is strongly typed to SearchEntry.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Model.SearchEntry>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Results for "<%: Model.QueryText %>"
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <% Html.RenderPartial("SearchForm"); %>

    <table>
        <thead>
            <tr>
                 <th>Name</th>
                 <th>Price</th>
            </tr>
          </thead>
          <tbody>
          <% foreach (var record in Model.ResultProductsList) { %>
              <tr>
                  <td><%: record.Name %></td>
                  <td><%: record.Price %></td>
              </tr>
           <% } %>
           </tbody>
    </table>
</asp:Content>

Controller
The controller is quite elegant, I find, it does little but accomplishes a lot. It simply glues everything together.

ISearchEngine searchEngine;

//initializes the search engine
public SearchController(IContextRepository contextRepository)
{
    searchEngine = new SearchEngine(contextRepository);
}

//returns the partial view
public ActionResult SearchForm()
{
    return View();
}

//retrieves results and returns the results to view
public ActionResult Submit(SearchEntry searchEntry)
{
    searchEntry = searchEngine.Search(searchEntry);
    return View("Results", searchEntry);
}

I like to retrieve the connection string from what I call ContextRepository. It simplifies things, I find.
The Submit method takes in the model submitted by the search form above and retrieves the results from the search engine service shown below.

Service

public class SearchEngine : ISearchEngine
{
        private IContextRepository ContextRepository;

        public SearchEngine(IContextRepository contextRepository)
        {
            ContextRepository = contextRepository;
        }

        public SearchEntry Search(SearchEntry searchEntry)
        {
            searchEntry.ResultProductsList =
                ProductsFullTextSearch(searchEntry.QueryText, ContextRepository.MasterContext).ToList();

            return searchEntry;
        }

        private IEnumerable<Products> ProductsFullTextSearch(string text, DataContext context)
        {
            return (GenericFullTextSearch<Products>(text, context) as IEnumerable<Products>);
        }

        private IEnumerable<TSource> GenericFullTextSearch<TSource>(string text, DataContext context)
        {
            //Find LINQ Table attribute
            object[] info = typeof(TSource).GetCustomAttributes(typeof(System.Data.Linq.Mapping.TableAttribute), true);
            //Get table name
            String table = (info[0] as System.Data.Linq.Mapping.TableAttribute).Name;
            //Full text search on that table
            return context.ExecuteQuery<TSource>(String.Concat("SELECT * FROM ", table, " WHERE CONTAINS(*, {0})"), text);
        }
}

That’s all! I’m sure a lot can be improved on. On it now!