Breeze and knockout quick start.

An attempt at a bare minimum to get breeze and knockout going.


Create a new MVC4 web application web api project. This will bring in jQuery and knockout.
Nuget install-package Breeze.WebApi.
Add a dbcontext class in Models and a breeze api controller in Controllers.
Add an html page with a view model and a view.


using System.Linq;
using System.Web.Http;
using Breeze.WebApi;
using MvcApplication1.Models;
using Newtonsoft.Json.Linq;
namespace MvcApplication1.Controllers
{
[BreezeController]
public class FooController : ApiController
{
private readonly EFContextProvider<FooData> _ctx = new EFContextProvider<FooData>();
[HttpGet]
public string Metadata()
{
return _ctx.Metadata();
}
[HttpGet]
public IQueryable<Foo> Foos()
{
return _ctx.Context.Foo;
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _ctx.SaveChanges(saveBundle);
}
}
}


using System;
using System.Data.Entity;
namespace MvcApplication1.Models
{
public class Foo
{
public int Id { get; set; }
public String Name { get; set; }
}
public class FooData : DbContext
{
public DbSet<Foo> Foo { get; set; }
}
}

view raw

FooData.cs

hosted with ❤ by GitHub


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<title></title>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/knockout-2.2.0.js"></script>
<script src="Scripts/q.min.js"></script>
<script src="Scripts/breeze.min.js"></script>
<script type="text/javascript">
var mgr = new breeze.EntityManager("breeze/Foo");
var Vm = function () {
var items = ko.observableArray();
var item = ko.observable();
mgr.executeQuery(breeze.EntityQuery.from("Foos"))
.then(function (val) {
val.results.forEach(function (result) {
items.push(result);
});
});
function add() {
items.push(mgr.createEntity("Foo", { Name: item() }));
mgr.saveChanges();
item("");
}
function remove(data) {
data.entityAspect.setDeleted();
mgr.saveChanges();
items.remove(data);
}
return {
items: items,
item: item,
add: add,
remove: remove
};
};
$(function () {
ko.applyBindings(new Vm());
});
</script>
</head>
<body>
<form data-bind="submit: add">
<input type="text" data-bind="value: item" />
<input type="submit" value="add" />
</form>
<div data-bind="foreach: items">
<span data-bind="text: Name"></span>
<input type="button" value="delete" data-bind="click: $parent.remove" />
<br />
</div>
</body>
</html>

view raw

HtmlPage1.html

hosted with ❤ by GitHub


RE: Way to Lambda

One use of lambdas is to provide a method to a sub-routine that it can call if it needs something from the caller. I have implemented this pattern in a temporary caching class that I use sometimes but I think this example is more fun.

using System;
using System.Collections.Generic;
public class CowBell { }
public class BlueÖysterCult 
{
    public BlueÖysterCult()
    {
        var session = new JamSession<CowBell>();
        session.Jam(
            needs: () => session.TheCure.Count < 1000, 
            more: () => new CowBell());
    }
}
public class JamSession<T>
{
    public List<T> TheCure;
    public JamSession()
    {
        TheCure = new List<T>();
    }
    public void Jam(Func<Boolean> needs, Func<T> more)
    {
        while (needs())
        {
            TheCure.Add(more());
        }
    }
}

And if that is not a big enough of a yawn, here is a simple generic cache implementation.

    public class Cache<T> where T : class
    {
        private readonly Func<string, object> _get;
        private readonly Action<string, object> _set;
        private readonly Action<string> _clear;
        private readonly Func<string> _name;

        public Cache()
        {
            _get = (key) => HttpContext.Current.Cache[key];
            _set = (key, obj) => HttpContext.Current.Cache[key] = obj;
            _clear = (key) => HttpContext.Current.Cache.Remove(key);
            _name = () => typeof (T).FullName;
        }
        public T Item
        {
            get { return (T)_get(_name()); }
            private set
            {
                if (value == null) _clear(_name());
                else _set(_name(), value);    
            }
        }
        public T Get(Func<T> data)
        {
            return Item ?? (Item = data());
        }
        public void Clear()
        {
            Item = null;
        }
        public bool Exists()
        {
            return Item != null;
        }
    }

Generic DbContext with REST methods

Simple generic wrapper to put CRUD on top of a class to use for a Web API or for data binding.

using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
/// <summary>
/// Bit bucket class
/// </summary>
public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
/// <summary>
/// Generic RESTish dbcontext.
/// </summary>
public class ContactContext : codewarren.com.SimpleContext<Contact> { }
namespace codewarren.com
{
    /// <summary>
    /// Class that  puts generic REST type methods on top of a class.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SimpleContext<T> : DbContext where T : class
    {
        public DbSet<T> Items { get; set; }
        public List<T> Get()
        {
            return Items.ToList();
        }
        public T Get(int id)
        {
            return Items.Find(id);
        }
        public void Put(T item)
        {
            Items.Attach(item);
            Entry(item).State = EntityState.Modified;
            SaveChanges();
        }
        public void Post(T item)
        {
            Items.Add(item);
            SaveChanges();
        }
        public void Delete(int id)
        {
            Delete(Get(id));
        }
        public void Delete(T item)
        {
            Items.Attach(item);
            Entry(item).State = EntityState.Deleted;
            SaveChanges();
        }
    }
}

Here is a ApiController that makes use of it.

using System.Collections.Generic;
using System.Web.Http;

public class GenericController<T> :  ApiController where T: class 
{
    private readonly SimpleContext<T> _context = new SimpleContext<T>();

    public List<T> Get()
    {
        return _context.Get();
    }
    public T Get(int id)
    {
        return _context.Get(id);
    }
    public void Post([FromBody]T t)
    {
        _context.Post(t);
    }
    public void Put([FromBody]T t)
    {
        _context.Put(t);
    }
    public void Delete(int id)
    {
        _context.Delete(id);
    }
}
public class ContactController : GenericController<Contact> {}


AppHarbor Quick Start

AppHarbor is a cloud based an online continuous integration service. It takes a commit to source code version control repository, builds it and deploys it to a host.

What this provides is fast web application deployment that includes hosted change management and site hosting.

In this example we will use a GitHub repository and it’s Windows client so that needs to be installed first.

Login to AppHarbor and create a new application.
On the application page choose the option to Configure GitHub to deploy to AppHarbor. This will let you choose to create a new repository or use an existing one.

Login to GitHub and add the repository to the Windows client. Search for the repository by name in the form of AppHubUserName/GitHubRepositoryName. Click the button to Setup In Windows and it will launch the GitHub Windows client.

In the GitHub client you can open the repository in Windows explorer and add files using any tool including creating a new ASP.NET web site there in the existing location using Visual Studio.

After creating the files return to the GitHub client, and a comment, commit the changes then publish the changes to the server. In AppHarbor on the application page you will see the commit and from there you can click the link to Go to your application to see the site hosted on the web.

Note that repositories can be shared with other GitHub Windows users with a URL like:
github-windows://openRepo/https://github.com/userName/repoName