Hi all, I said I’d post this because I didn’t manage to find a suitable blog post or documentation indicating how to do this with the HttpClient (beta). (bleeding edge again ey).
This post outlines how to create a simple test server that has a Json Logon endpoint.
Then it shows how to login with the .net 4.5 HttpClient class. Lots of other post I saw were trying to set Channels on this HttpClient, I’ll have to assume this was from the developer preview or the Wcf predecessor. It appears now the solution comes in the form of a HttpClientHandler!
It’s been a long day, up at 4am for a flight and then a long day at work, so lets cut to the chase…
Server
For setup, create a new MVC4 internet application

Why? because it gives me a AccountController with a JsonLogin action

Add a new ApiController


Add the Authorize attribute

Now we have a simple server setup for testing (no https etc, but lets not overcomplicate this just now).
Client
I just created a WPF client and called the following function on a button click.
private async void Login()
{
var handler = new HttpClientHandler();
CookieContainer cookieContainer = new CookieContainer();
handler.CookieContainer = cookieContainer;
var client = new System.Net.Http.HttpClient(handler);
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"UserName", "brianbruff1"},
{"Password", "password"}
});
var response = await client.PostAsync("http://localhost:2122/account/jsonlogin", content);
response.EnsureSuccessStatusCode();
var msg = await response.Content.ReadAsStringAsync();
// just get the default value from the starter project
response = await client.GetAsync("http://localhost:2122/api/values");
response.EnsureSuccessStatusCode();
var list = await response.Content.ReadAsAsync<List<string>>();
}
That’s it, next steps to clean up this code are all yours, but hopefully I’ve helped someone out.
Remember to register the user the first time your run your MVC app, or your msg variable will indicate you couldn’t be logged on.
Remember to include Http.Formatters for the ReadAsAsync extension.
Brian.
Credit to @tomasmcguinness for pointing me in the right direciton (my other approach was to use PKI).
Credit to Microsoft for releasing the source so I could figure this out!
With this post I’m back to my lovely OneNote screen clippings, my last few postings were done on Windows8 and I’d no OneNote installed.
So you want to Deserialize Json in .NET! (C#)
How do you go about it?
There are a few approaches, many poeple are familiar with JSon.NET and using it like this

or

Some people may have done it the hard way

But if you add assembly System.Net.Http.Formatting.dll you’ll get a nice little extension ReadAsAsync<T>
http://msdn.microsoft.com/en-us/library/hh836073(v=vs.108).aspx

Enjoy!
What’s wrong with this?
1: public class UsersController : RavenController
2: {
3: public User Get(int userId)
4: {
5: this.AutoSave = false;
6: var user = RavenSession.Load<User>(userId);
7: if (user == null)
8: throw new HttpResponseException("Unable to find user for it " + userId);
9: return user;
10: }
11:
12: // GET /api/values
13: public IQueryable<User> GetAll()
14: {
15: this.AutoSave = false;
16: return RavenSession.Query<User>();
17: }
18: }
The problem is the variable name used for getting a single user the function would never be called.
E.g. if we put http://localhost:65487/api/users/1 into our browser what will happen is the GetAll gets called!
What we need to call is
1: public class UsersController : RavenController
2: {
3: public User Get(int id)
4: {
5: this.AutoSave = false;
6: var user = RavenSession.Load<User>(id);
7: if (user == null)
8: throw new HttpResponseException("Unable to find user for it " + id);
9: return user;
10: }
11:
12: // GET /api/values
13: public IQueryable<User> GetAll()
14: {
15: this.AutoSave = false;
16: return RavenSession.Query<User>();
17: }
18: }
Now you see that the Get takes a variable name of “id” this is key to getting this work.
Note: I’m using IQuerable as this allows me to add some query parameters to my request, e.g.
$filter
A Boolean expression for whether a particular entry should be included in the feed, e.g. Categories?$filter=CategoryName eq 'Produce'. The Query Expression section describes OData expressions.
$orderby
One or more comma-separated expressions with an optional “asc” (the default) or “desc” depending on the order you’d like the values sorted, e.g. Categories?$orderby=CategoryName desc.
$select
Limit the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description.
$skip
How many entries you’d like to skip, e.g. Categories?$skip=4.
$top-
Return entries from the top of the feed, e.g. Categories?$top=4
See MSDN for more options.
-- Updated Post --
Thanks to James Hancock for pointing this one out for me. This post is a little misleading in that the $select is currently not supported. Please see http://forums.asp.net/t/1771116.aspx/1?OData%20Support for more information on this. The other query string parameters listed above are supported.
I’m starting this post with a disclaimer. I’m not a RavenDb expect, actually far from it, in fact I’ve only started working with it this evening!
I’m working on a pet project and getting the initial building blocks in place. I read about RavenDB in a recent edition of CODE magazine. The same magazine dealt with some other NoSql databases, e.g. Mongo Db, I’ve had a passing interest in NoSql in the last while so I wanted to get me a piece of the pie, and RavenDB jumped out at me for a few reasons.
- Written in .NET
- Scalability over RDBMS
- RestAPI (although i won’t be using it, my app will have its own REST API using RavenDb managed api underneath)
- .NET API with Linq querying
- Automatic indexing
- Scalability
Create project
Fire up visual studio and create an new MVC4 project
Add the RavenDb package,
Global.asax.cs
Do the very same that is indicated on the Raven website, We need a single Document Store in our application.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
InitRaven();
}
private void InitRaven()
{
Store = new DocumentStore { ConnectionStringName = "RavenDB" };
Store.Initialize();
IndexCreation.CreateIndexes(Assembly.GetCallingAssembly(), Store);
}
public static DocumentStore Store;
Create RavenController
public abstract class RavenController : ApiController
{
public RavenController()
{
this.AutoSave = true;
RavenSession = TickTockBaby.Mvc.WebApiApplication.Store.OpenSession();
}
public bool AutoSave { get; set; }
public IDocumentSession RavenSession { get; protected set; }
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (RavenSession != null)
{
using (RavenSession)
{
if (this.AutoSave)
RavenSession.SaveChanges();
RavenSession.Dispose();
RavenSession = null;
}
}
}
base.Dispose(disposing);
}
}
Let me explain what I’ve done here…
I’ve initialized the session in the constructor, and cleaned it up in dispose, I also SaveChanges by default unless it gets switched off in a derived class.
Derive from RavenController
public class UsersController : RavenController
{
// GET /api/values
public IEnumerable<string> Get()
{
this.AutoSave = false;
return RavenSession.Query<User>().Select(u => u.Name);
}
}
That’s my initial attempt, hope it helps someone out a little.
I’ll post my final solution possibly using Ninject DI after I’ve used RavenDb for a while and get a better feel for it.
Raven Studio
Check results in browser
I’m working with an XML document all morning, and for the hell of it I decided to open in VS11.
Guess what I found, some pretty cool xml/xsd/xslt support

but the biggest feature I found is the following…
Paste XML as classes! BOOM!!


Loving VS11…