I spent a lot of time late last week trying to figure out exactly how to set up dependency injection for a WCF service I was developing on Windows Azure; there’s some documentation out there on how to do it, but it’s not nearly as helpful as I would like it. Thus I decided to document how I made WCF and Ninject play nice with each other, and I even provide a sample template you can use yourself.
Step 1 – Install Ninject.Extensions.WCF via NuGet
The developers who maintain Ninject were kind enough to put together a set of extensions for working with WCF applications specifically, and we can install this via NuGet (install it from CodePlex.)
Simply type this into the “package manager console” in Visual Studio: install-package Ninject.Extensions.Wcf

This will automatically grab the appropriate version of Ninject and the other binaries you’ll need to get the WCF ServiceHost to play nice with your service.
Step 2 – Write Your Own Ninject Module
The next step is to set up your dependency injections by writing your own NinjectModule like this:
using Ninject.Modules;
namespace wcf_ninject.DI
{
public class WCFNinjectModule : NinjectModule
{
public override void Load()
{
//Injects the constructors of all DI-ed objects
//with a LinqToSQL implementation of IRepository
Bind<IRepository>().To<LinqToSQLRepository>();
}
}
}
Step 3 – Add the “Factory” Attribute to Service1.svc
The next thing you need to do is tell the service host to use the Ninject Factory to instantiate the WCF service by way of a custom ServiceHostFactory included in the Ninject WCF Extensions.
To do this, right click on the “Service1.svc” file (or whatever you name your service) and select the “View Markup” option:

Once there, simply add this line:
Before
<%@ ServiceHost
Language="C#"
Debug="true"
Service="wcf_ninject.Service1"
CodeBehind="Service1.svc.cs" %>
After
<%@ ServiceHost
Language="C#"
Debug="true"
Service="wcf_ninject.Service1"
CodeBehind="Service1.svc.cs"
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %>
Step 4 – Add Global.asax Make It Inherit from NinjectWcfApplication
The final step is to add a Global.asax file to your WCF project and make it inherit from the NinjectWcfApplication class, like this:
public class Global : NinjectWcfApplication
In order for this code to compile, you’ll need to add a “CreateKernel” method to Global.asax – this method is what utilizes your Ninject module and uses it to inject dependencies into your WCF service. Here’s what that code looks like for this example:
protected override IKernel CreateKernel()
{
return new StandardKernel(new WCFNinjectModule());
}
Now there’s just one last step…
Step 5 – Remove the Default Constructor from Your WCF Service; Have Dependency-Accepting Constructor Instead
Your final constructor in this example should look something like this:
public Service1(IRepository repository)
{
_repo = repository;
}
Get rid of any default constructors (ones that don’t accept arguments) – Ninject will raise an error if it finds one in the signature of your class as of writing this.
Grab the WCF + Ninject Visual Studio 2010 Project off of Github
You can download the Visual Studio 2010 project that contains this WCF + Ninject sample off of Github if you want to use it as a starting point.
If you enjoyed this post, make sure you subscribe to my RSS feed!
b6a5f08d-f909-49d7-b4ae-fe9b696474e9|3|5.0
One of the more interesting things I had to do as part of building XAPFest was handle bulk image uploads for screenshots for applications and user / app icons. Most of the challenges here are UI-centric ones (which I resolved using jQuery File-Upload) but the one security challenge that remains outstanding is ensuring that the content uploaded to your servers is safe for your users to consume.
Fortunately this problem isn't too hard to solve and doesn't require much code in C#.
Flawed Approaches to Verifying Image Uploads
Here's what I usually see when developers try to allow only web-friendly image uploads:
- File extension validation (i.e. only allow images with .png, .jp[e]g, and .gif to be uploaded) and
- MIME type validation.
So what's wrong with these techniques? The issue is that both the file extension and MIME type can be spoofed, so there's no guarantee that a determined hacker might not take a js. file, slap an extra .png extension somewhere in the mix and spoof the MIME type.
Stronger Approach to Verifying Image Uploads: GDI+ Format Checking
Every file format has to follow a particular codec / byte order convention in order to be read and executed by software. This is as true for proprietary formats like .pptx as it is for .png and .gif.
You can use these codecs to your advantage and quickly tell if a file is really what it says it is - you quickly check the contents of the file against the supported formats' codecs to see if the content fits into any of those specifications.
Luckily GDI+ (System.Drawing.Imaging), the graphics engine which powers Windows, has some super-simple functions we can use to perform this validation. Here's a bit of source you can use to validate a file against PNG, JPEG, and GIF formats:
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;
namespace XAPFest.Providers.Security
{
///
/// Utility class used to validate the contents of uploaded files
///
public static class FileUploadValidator
{
public static bool FileIsWebFriendlyImage(Stream stream)
{
try
{
//Read an image from the stream...
var i = Image.FromStream(stream);
//Move the pointer back to the beginning of the stream
stream.Seek(0, SeekOrigin.Begin);
if (ImageFormat.Jpeg.Equals(i.RawFormat))
return true;
return ImageFormat.Png.Equals(i.RawFormat)
|| ImageFormat.Gif.Equals(i.RawFormat);
}
catch
{
return false;
}
}
}
}
All this code does is read the Stream object returned for each posted file into an Image object, and then verifies that the Image supports one of three supported codecs.
This source code has not been tested by security experts, so use it at your own risk.
If you have any questions about how this code works or want to learn more, please drop me a line in the comments below or on Twitter.
Bonus: How Do I Make Sure Files Are below [X] Filesize?
Since I had this source code lying around anyway, I thought I would share it:
public static bool FileIsWebFriendlyImage(Stream stream, long size)
{
return stream.Length <= size && FileIsWebFriendlyImage(stream);
}
}
Super-simple, like I said, but it gets the job done. Express the maximum allowable size as a long and compare it against the length of the stream
If you enjoyed this post, make sure you subscribe to my RSS feed!
a5aa4319-f9f3-486b-979a-bfade79a591a|2|5.0
I made a tiny splash on Hacker News a month ago when I asked for feedback on my newest side project, CaptainObvio.us – a simple portal for sharing ideas and soliciting feedback from a community of peers. The idea was popular and I’ve received a ton of feedback – I’ve implemented most of the Hacker News community’s suggestions but haven’t had the chance to do another round of customer development.
What I wanted to share in this blog post was some of the secret sauce I used for creating CaptainObvio.us – I originally created it mostly to learn MongoDB, and learned way more than that along the way.
Webstack: ASP.NET MVC3 on AppHarbor
I used ASP.NET MVC3 as my webstack of choice with AppHarbor as my hosting platform. ASP.NET MVC3 is a massive improvement over MVC2, and I took advantage of Razor syntax, the built-in support for DI (dependency injection) on controllers, and wrote a number of customized helpers to do things like create an action filter for Twitter @Anywhere.
AppHarbor has been a great experience to work with - I use Git for souce control for most of my personal projects like this one so deployments are a breeze on AppHarbor, but the other major reason I picked AppHarbor is that it shares the same Amazon AWS datacenter as MongoHQ - another [Thing]-as-a-Service that I used for hosting my MongoDB instance.
Data: MongoDB on MongoHQ
The original purpose of CaptainObvio.us was for me to learn MongoDB, a schemaless (NoSQL) document database written in C++ that is becoming all the rage in the Ruby on Rails universe. CaptainObvio.us is a good fit for Mongo given that the vast majority of its content consists of simple documents with a small amount of relational data for tying authors to ideas / comments and so forth.
I could not have gotten very far with MongoDB in C# were it not for the NoRM Project MongoDB drivers for C# - NoRM's drivers are much better than the default MongoDB drivers for C# and work similarly to LINQ-to-SQL (although not exactly.) It was a matter of hours for me to go from installing Mongo to having a functional site running with NoRM and ASP.NET MVC3.
Authentication: Originally Twitter @Anywhere; Sign-in-with-Twitter and Hammock Later
Twitter @Anywhere is a fairly new JavaScript-only framework for integrating Twitter into existing websites quickly and effortlessly - it automates all of the OAuth workflow, comes with tons of useful built-in widgets, and eliminates the need to write much (if any) plumbing needed to support Twitter integration.
This is all nice in theory but if you're building a site like CaptainObvious where your users use Twitter to sign-in and leave behind persistent data in your own data store, then this framework can really cause problems. I had to gut Twitter @Anywhere eventually because the post-authentication event hook would misfire on occasion due to issues on the client and thus I would have an "authorized" user running around adding comments and voting despite no record of them existing in the database.
In order to resolve the issue, I dumped Twitter @Anywhere and went with traditional Sign-in-with-Twitter powered by Hammock, which works fine.
Final Thoughts
I'm going to continue working on CaptainObvio.us, although I put it off largely due to all of the work I had to do engineering XAPFest's online presence on Windows Azure. If the project taught me anything, it's the value of continuous integration environments like AppHarbor and the ease with which you can get something up and running quickly with MongoDB.
I'd highly recommend checking out AppHarbor, MongoHQ, and the NoRM drivers if you're a .NET developer who's new to Mongo and wants to learn how to use it. I guarantee you that you'll appreciate traditional .NET databases like SQL Server 2008 and SQL Azure a lot better after you've worked with Mongo, as it'll help you learn the strengths and weakness of each respesctive platform.
If you enjoyed this post, make sure you subscribe to my RSS feed!
1051969b-a91b-4497-8f4e-d8ca590bdd8b|0|.0
My newest project, Captain Obvious, got a fair amount of attention this week when it landed on the front page of Hacker News – one of the key features that makes the first version of Captain Obvious tick is Twitter @Anywhere integration.
Twitter @Anywhere is brand new and there isn’t much developer documentation for it – the way to think about Twitter @Anywhere is as a Javascript platform that allows you to outsource user authentication and registration to Twitter’s servers, and in exchange you get less hassle but also less intimate access to your user’s accounts.
One of the key features to integrating Twitter @Anywhere users with your ASP.NET MVC site is reading the cookie that Twitter sets after users have authenticated – this cookie contains two parts:
- The Twitter user’s unique ID, an integer representing their unique account (because remember – Twitter users can change their handles!)
- A SHA1 hash of the Twitter user’s unique ID + your application’s consumer secret – you use this to verify that the cookie was set by Twitter, since they’re the only ones who know your consumer secret other than you.
Naturally, if you are going to use this cookie as your authentication mechanism, then you are going to need to write your own Authorize attribute that allows you to validate the content’s of the Twitter @Anywhere cookie. Here’s the source code I use for doing that:
ValidTwitterAnywhereAttribute
/// <summary>
/// Controller Action Filter Attribute which requires that
/// </summary>
public class ValidTwitterAnywhereAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var twitterCookieValue = httpContext.Request.Cookies["twitter_anywhere_identity"];
var consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];
return TwitterAuthHelper.ValidateTwitterCookie(twitterCookieValue, consumerSecret);
}
}
Here’s the relevant source code from the TwitterAuthHelper that I use to actually validate the hash in the cookie:
TwitterAuthHelper
public static bool VerifyTwitterUser(string twitterCookieValue, string ConsumerSecret)
{
var results = twitterCookieValue.Split(':');
var sha1 = new SHA1CryptoServiceProvider();
var hash = BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(results[0] + ConsumerSecret)))
.ToLower().Replace("-", "");
if (hash.Equals(results[1]))
return true;
return false;
}
I’m using this code in production and it works great – all you have to do to use it is decorate your controller methods with the [ValidTwitterAnywhere] attribute and it will behave just like Forms authentication if you have that enabled in your ASP.NET MVC app.
If you enjoyed this post, make sure you subscribe to my RSS feed!
ece5dc08-d417-4469-9b71-61b5a787803f|2|5.0
I’m in the middle of writing some updates to Quick and Dirty Feed Parser for use in a new personal project of mine; namely, I need to make QD Feed Parser work asynchronously so I can use it in conjunction with asynchronous controllers in ASP.NET MVC3, and eventually Silverlight + Windows Phone 7.
Asynchronous network IO is a breeze in every version of .NET since 1.1 – WebRequest and many others have supported asynchronous methods for as long as I’ve been using them. However, asynchronous disk IO, which I need to support in QD Feed Parser, is not something that comes so easily in .NET 4.0 and below.
StreamReader is the most user-friendly tool for reading files off of local disk because you don’t have to manage any buffers or do any of the sort of accounting that a class like FileStream requires. Here’s how nice and easy life is using StreamReader, using actual code from QD Feed Parser as an example:
protected static FeedTuple DownloadXmlFromUri(Uri feeduri)
{
string xmlContent;
using (var reader = new StreamReader(feeduri.LocalPath))
{
xmlContent = reader.ReadToEnd();
}
return new FeedTuple{FeedContent = xmlContent, FeedUri = feeduri};
}
Given that StreamReader doesn’t have any built-in methods for making this asynchronous, what’s the best way to do this, given that the async and await keywords coming down the pipe in .NET 5.0 aren’t fully available yet? The answer is: we’re going to wrap our disc IO operations using delegates.
Out of the box delegates have both a BeginInvoke and EndInvoke methods, which behave like any other standard asynchronous method call and you, the developer get to decide what functions are invoked on the background thread.
Here are the steps:
1. Create a delegate and a static worker method
protected delegate FeedTuple BackGroundWorker(Uri feeduri);
protected static FeedTuple DownloadXmlFromUri(Uri feeduri)
{
string xmlContent;
using (var reader = new StreamReader(feeduri.LocalPath))
{
xmlContent = reader.ReadToEnd();
}
return new FeedTuple { FeedContent = xmlContent, FeedUri = feeduri };
}
The delegate and the static worker method need to have the same signatures.
2. Define your own Begin[Operation] and End[Operation] methods
For Quick and Dirty Feed Parser, here is what I created, minus some integrity checks in order to make the code more readable:
public override IAsyncResult BeginDownloadXml(Uri feeduri, AsyncCallback callback)
{
return FeedWorkerDelegate.BeginInvoke(feeduri, callback,
new FeedTuple());
}
public override FeedTuple EndDownloadXml(IAsyncResult asyncResult)
{
var result = FeedWorkerDelegate.EndInvoke(asyncResult);
return result;
}
Your begin method should return the IAsyncResult from your delegate – this way your caller can pass the asynchronous result back to the End[Operation] method and return your result. You can also use the IAsyncResult’s WaitHandle to put a block a calling thread if you wanted.
When dealing with delegates you have to be careful with your accounting – for every BeginInvoke there should be exactly one EndInvoke.
3. Calling the asynchronous methods
Here’s a quick unit test I wrote for testing this method in Quick and Dirty Feed Parser.
[Test, TestCaseSource("TestCases")]
public void CanDownloadXmlStreamAsync(string rsslocation)
{
var feeduri = new Uri(rsslocation);
var result = Factory.BeginDownloadXml(feeduri, null);
var resultantTuple = Factory.EndDownloadXml(result);
Assert.IsNotNull(resultantTuple);
Assert.That(resultantTuple.FeedContent != String.Empty);
Assert.AreEqual(feeduri, resultantTuple.FeedUri);
}
You should note that I’m effectively blocking the calling thread until the asynchronous worker thread returns a result in this method, and that’s because it’s easier to write unit tests this way.
The best practice for taking advantage of asynchronous method calls is to utilize a callback function, which you can do like so:
public void DownloadXmlStreamAsync(string rsslocation)
{
var feeduri = new Uri(rsslocation);
var result = Factory.BeginDownloadXml(feeduri, async =>
{
var callbackTuple = Factory.EndDownloadXml(async);
Dispatcher.BeginInvoke(() => {
//... Do some client-side stuff with the data...
});
});
}
And that’s it!
If you enjoyed this post, make sure you subscribe to my RSS feed!
280eda38-df4f-4ec1-871f-e9ef50eb5982|0|.0
ASP.NET MVC3 has been a major boon to my productivity as a web developer since I started using it at the beginning of November – the new Razor view engine has been attracting most of the attention with this iteration of MVC, but one extremely sexy feature has gone unnoticed thus far: Remote validation.
Remote validation was one of the new features added in the November Release Candidate (RC) for MVC3 – I had a chance to demo it in front of the LA .NET User Group last night and it was a monster hit.
Example:
You’ve all seen remote validation before – ever see one of these when you’re signing up for a service like Twitter?

That’s remote validation at work. Twitter, Facebook et al make an AJAX call to a remote service hook that checks the database to see if the username is available as the user types it. It’s a major user experience improvement as they get that feedback instantly instead of having to wait until after they fill out the rest of the form and submit it.
In the past with ASP.NET MVC you had to write your own custom jQuery scripts on top of the jQuery validation engine to achieve this end-result; in ASP.NET MVC3 this is taken care of for you automatically!
Let me show you how it works:
1. Decorate a model class with the Remote attribute
Take the class you want to validate and decorate the attributes you need to remotely validate with the Remote attribute.
public class NewUser
{
[Remote("UserNameExists", "Account", "Username is already taken.")]
public string UserName { get; set; }
[Remote("EmailExists", "Account", "An account with this email address already exists.")]
public string EmailAddress { get; set; }
public string Password { get; set; }
}
In both of these instances of the Remote attribute, I’ve passed the following arguments:
- The name of an action method;
- The name of the controller where the action method lives; and
- A default error message should user input fail this validation challenge.
2. Implement an action method to support your Remote attribute
You will need to implement an action method that supports your Remote attribute. Add an action method which returns a JsonResult to the controller you named in your Remote attribute arguments. In this example I’ll need to add these action methods to the “Account” controller:
public JsonResult UserNameExists(string username)
{
var user = _repository.GetUserByName(username.Trim());
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", username),
JsonRequestBehavior.AllowGet);
}
public JsonResult EmailExists(string emailaddress)
{
var user = _repository.GetUserByEmail(emailaddress.Trim());
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(
string.Format("an account for address {0} already exists.",
emailaddress), JsonRequestBehavior.AllowGet);
}
If the repository returns null, meaning that a user account with this particular user name or email address doesn’t already exist, then we simply return a JsonResult with a value of true and go off on our merry way. This will suppress the jQuery validation library from raising a validation error.
If the action method returns false, then jQuery will raise a validation error and display the default error message provided in the Remote attribute arguments – if you didn’t provide a default error message yourself then the system will use an ambiguous default one.
If the action method returns a string, jQuery will raise a validation error and display the contents of the string, which is what I’m doing here in this example.
Small Gotcha – Naming Action Method Parameters
There’s one small gotcha that can be easy to miss – the name of the argument on your action method must match the name of your property on your model. If I changed the EmailExists body to look like this:
public JsonResult EmailExists(string email);
Then ASP.NET would pass a null value to this method.
Case 1: parameter name matches the name of the model’s property

Case 2: parameter name does not match the name of the model’s property

This is because the jQuery parameter takes the name of the property on the model and passes it as a querystring argument to your action method – here’s what your validation request looks like in Firebug:
[host]/account/emailexists?area=an%20account%20with%20this%20email%20address%20already%20exists.&EmailAddress=test%40test.com
The ASP.NET MVC model-binder isn’t all-knowing – it’s not going to be able to tell that EmailAddress and email are the same thing, thus it ultimately won’t bind an argument to your action method, hence why the null value is passed.
If you follow the convention of using a common name for your Remote validator action method arguments and your model properties, you won’t run into this issue.
UPDATE: Thanks to Rick Anderson for directing me to the much more extensive MSDN documentation on how to implement custom Remote validaiton in ASP.NET MVC3.
If you enjoyed this post, make sure you subscribe to my RSS feed!
2a3d0f98-6c44-40b5-a3e5-c806f0282688|5|5.0
I gave a talk at Code Camp Los Angeles a couple of weekends ago on how to consume REST APIs in .NET – the emphasis was really on understanding RESTful principles and on the OAuth workflows + implementing them in Windows Phone 7.
It was meant to be a 100-200 level introduction to the REST in .NET – if you’ve implemented OAuth before in .NET then this is old news for you :p
Enjoy!
If you enjoyed this post, make sure you subscribe to my RSS feed!
dfc74717-3d94-4ea0-8c53-07abe8eed92b|0|.0
One of the other things I took away from Code Camp was a bit of .NET culture shock. As you can tell by glimpsing around on this blog, I am somewhat enamored with the idea of starting my own business. I’m a natural entrepreneur and it is my wont to think about startups constantly.
That being said, I’ve always wondered why a platform as widely adopted and supported as .NET isn’t more visible in startup culture. Many major open source platforms and languages have very visible and vocal presences in the startup community, everything from mainstays like Python and PHP to even the more obscure and specialized ones like Clojure and Hadoop.
.NET on the other hand is conspicuously absent from the startup conversation despite the fact that it is a singularly larger platform than any of the others.
It’s like there’s a silent majority among the development community that just tinkers away on its own projects without even occasionally raising its hands and saying “here’s something clever and unique we did with this platform that no one else has done before.”
It’s somewhat tragic for the .NET community too – because the perceived lack of sex-appeal on the surface doesn’t match the reality of what the platform is capable of.
Just take a brief moment to peruse through CodePlex for more than a couple minutes and you’ll find thousands upon thousands of examples creative open source projects all built in .NET.
And in the startup space there actually are a number of .NET-based startups making it big, including this week’s Hacker News / Social Media darling Woot. But why oh why isn’t there a louder .NET voice in the startup community? Why aren’t there developers from Woot working with developers from StackOverFlow (also implemented in .NET) to encourage more startups to use the extensive .NET stack to create new and exciting products and services?
And most importantly, why aren’t there more startups adopting .NET?
It’s All about the Enterprise
I’ve heard all sorts of lame answers to this question before: “platform lock-in,” “no open standards,” “licensing costs,” and none of them pass the test of objective reality – yes, those are issues that might prevent some developers from adopting .NET in the startup space, but not enough to bar virtually all of them from using .NET, arguably the most comprehensive and versatile platform with the best tools and the best support.
At Code Camp I think I finally figured out why this is: it’s the culture of the .NET community itself, not anything specific to the platform or the architecture which supports it.
.NET culture is centered around the concerns of the enterprise – the large already-established businesses in the economy, not plucky up-and-coming startups.
And when I say “culture,” I’m not talking about the development tools – I’m talking about where the hearts and minds of the developers who use the .NET platform are. I’m talking about the blogs and media sources .NET developers read. I’m talking about the networks where .NET developers contribute and the substance of their conversations.
Most of the developers I met developed portals for giant healthcare providers with thousands of employees, worked on legacy code whose lifespan could be measured in decades, worked in teams with hundreds and even thousands of programmers, and lived in ecosystems ruled by large bureaucracies. These are problems to which few if any developers for startups can relate.
That’s why so many of the talks at Code Camp were staked around RAD methodologies for developing internal projects, coding standards, enterprise architecture, and other things that matter to developers who work in giant ecosystems.
And who can blame Microsoft for catering to the enterprise market – that’s where the money is! No one ever became rich selling high-end development tools to a handful of capital-starved, small companies.
However, the consequences of the .NET community’s enterprise-centric culture is that the startup community and the .NET community don’t overlap as much as they do for other technologies.
As a result, developers working for startups and even the startup founders themselves don’t get much exposure to .NET and don’t think of it as an applicable tool for their purposes.
The flipside is that many .NET developers who want to work for hot startups don’t have as many opportunities to do so unless they abandon the platform for a more “startup-friendly” one or start a company themselves.
So what do the members of the .NET community fuss over? They worry about supporting legacy systems, building enterprise architectures which can service multiple departments, they worry about large systems for supporting in-house business processes, and they worry about satisfying the needs of stakeholders throughout their companies.
.NET developers in general, worry about architecture in order to support systems.
Members of the startup community fuss over a very different set of issues – they’re their own stakeholders, they worry about concurrency, they worry about scalability, they worry about user experience design, they worry about supporting multiple clients and browsers, and they worry about how their designs will impact their bottom line.
Startup developers in general, worry about architecture in order to support products.
See the difference? .NET is perfectly capable of fulfilling the needs of product designers and startups, but comparatively little of the .NET culture, literature, and conversation is product-centric – instead the majority of it is structured around using .NET to support the needs of the business, not building the business’ products itself!
But It Doesn’t Have to Be
One thing that should be clear here is that any platform, not just .NET, can be used as a platform for building enterprise technology and for building new products. The platforms don’t often dictate their use – that’s the work of the people who develop on them.
If Microsoft wants to make a splash in the startup scene with .NET, and I have every reason to believe they do, then they need to do a better job evangelizing .NET’s capacity from a holistic new service / new product / new business perspective and not just for the enterprise.
Enterprise and startups aren’t mutually exclusive – they’re just different stages in the evolution of software, and there’s no reason why the startup community shouldn’t look at .NET as an attractive starting point for a new business.
The next article I’m going to write on this subject will cover why it’s a good idea for Microsoft to have .NET adopted more readily by the startup community.
If you enjoyed this post, make sure you subscribe to my RSS feed!
a40bd42f-2842-4443-a8c7-d5ee72626819|24|3.5
Alternate headline: "never see XML again."
Ok, that may be a bit of a stretch. Regardless, I'm quite pleased to announce the launch of Quick and Dirty Feed Parser, a library for people who want a seamless way to use Atom and RSS feeds in their .NET 2.0+ applications without having to deal with the XML.
"Does the world really need another RSS/Atom parser," you ask? I'll let my source code speak for itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QDFeedParser;
namespace QDFeedParserCMD
{
class Program
{
private static readonly string DefaultFeedUri = "http://www.aaronstannard.com/syndication.axd";
static void Main(string[] args)
{
try
{
string strFeedUri = args.Length == 0 ? DefaultFeedUri
: args[0];
Uri feeduri = new Uri(strFeedUri);
IFeedFactory factory = new HttpFeedFactory();
IFeed feed = factory.CreateFeed(feeduri);
foreach(var feedItem in feed.Items)
{
Console.WriteLine("{0} {1}", feedItem.DatePublished,
feedItem.Title);
Console.WriteLine(feedItem.Link);
}
//Just to prevent the window from instantly bailing out.
Console.ReadKey();
}
catch(Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
}
}
}
That's about as complicated as it gets, folks. And feel free to download this QDFeedParser example from CodePlex.
I wrote Quick and Dirty Feed Parser largely because I wanted to incorporate a really straightforward RSS/Atom parsing tool into a number of BlogEngine.NET modifications I have in mind in the near future, and I wanted a standard interface for dealing with RSS/Atom feeds that was available to me in .NET 2.0.
Quick and Dirty Feed Parser is my first OSS project so I would love your feedback, contributions, and most awesomely - examples of it actually being used! Check out the QDFeedParser project on CodePlex if you want to get involved!
QD Feed Parser in Action - The Great Wall of Geeks
No project worth it's salt would be complete without some sort of frivolous example, right? Well that's exactly why I created The Great Wall of Geeks.
Feel like your geeky blog belongs on the wall? Leave a comment below!
If you enjoyed this post, make sure you subscribe to my RSS feed!
ca2b7324-b05c-4ece-b7ae-084b3256b58f|1|5.0
I've been meaning to give RestSharp a go since I first started using Hammock in my startup project's codebase, just because I had heard some good things about RestSharp's auto-parsing capabilities.
This weekend I cobbled together a small example using del.icio.us' RSS feeds (not to be confused with its draconian REST API) for users and RestSharp performed magnificently, although its POCO -> XML Element mapping process requires a lot of experimentation before you get it just right.
Here's an example RSS feed for my personal del.icio.us account:
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/">
<channel>
<title>Delicious/Aaronontheweb</title>
<link>http://delicious.com/Aaronontheweb</link>
<description>bookmarks posted by Aaronontheweb</description>
<atom:link rel="self" type="application/rss+xml" href="http://feeds.delicious.com/v2/rss/Aaronontheweb?count=2"/>
<item>
<title>Windows Presentation Foundation (WPF) Dialog Boxes Overview</title>
<pubDate>Fri, 04 Jun 2010 23:48:12 +0000</pubDate>
<guid isPermaLink="false">[REMOVED]</guid>
<link>http://msdn.microsoft.com/en-us/library/aa969773.aspx</link>
<dc:creator><![CDATA[Aaronontheweb]]></dc:creator>
<comments>[REMOVED]</comments>
<wfw:commentRss>[REMOVED]</wfw:commentRss>
<source url="http://feeds.delicious.com/v2/rss/Aaronontheweb">Aaronontheweb's bookmarks</source>
<description>How to use dialog boxes in WPF (for WPF noobs like myself.)</description>
<category domain="http://delicious.com/Aaronontheweb/">.net</category>
<category domain="http://delicious.com/Aaronontheweb/">wpf</category>
<category domain="http://delicious.com/Aaronontheweb/">dialogs</category>
<category domain="http://delicious.com/Aaronontheweb/">tutorial</category>
<category domain="http://delicious.com/Aaronontheweb/">nullable</category>
<category domain="http://delicious.com/Aaronontheweb/">c#</category>
</item>
<item>
<title>Developer's Guide: Data API Protocol - YouTube APIs and Tools - Google Code</title>
<pubDate>Mon, 31 May 2010 22:43:47 +0000</pubDate>
<guid isPermaLink="false">[REMOVED]</guid>
<link>[REMOVED]</link>
<dc:creator><![CDATA[Aaronontheweb]]></dc:creator>
<comments>[REMOVED]</comments>
<wfw:commentRss>[REMOVED]</wfw:commentRss>
<source url="http://feeds.delicious.com/v2/rss/Aaronontheweb">Aaronontheweb's bookmarks</source>
<description>Finally figured it out - how to sign all requests with my API key using a querystring. So simple, yet so difficult.</description>
<category domain="http://delicious.com/Aaronontheweb/">youtube</category>
<category domain="http://delicious.com/Aaronontheweb/">API</category>
<category domain="http://delicious.com/Aaronontheweb/">key</category>
<category domain="http://delicious.com/Aaronontheweb/">Google</category>
<category domain="http://delicious.com/Aaronontheweb/">gdata</category>
</item>
</channel>
</rss>
The best way to utilize RestSharp to parse any sort of API response, whether it's custom REST XML, JSON, Atom, or RSS, is to first take a look at the raw response format and then to try to model a set of Data Transfer Objects (DTOs) which contain the response format elements you want to actually use in your application. Your DTOs just need to be simple POCO objects for this to work, but there are a set of POCO-XML Element matching rules you need to observe if you're using RestSharp's default deserializer - you can read them here.
Here are the classes that I modeled for this RSS format:
public class RssFeed
{
public string Version { get; set; }
public RssChannel Channel { get;set; }
}
public class RssChannel
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public RssItems Item { get; set; }
}
public class RssItems : List<item>{}
public class item
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public string Author { get; set; }
public string Comments { get; set; }
public string PubDate { get; set; }
}
This diagram explains how these DTO classes map to the del.icio.us RSS format:

ProTip: Handling Lists of XML Elements with POCO Classes
One thing that's a bit tricky is handling lists of XML elements, such as the <item> elements in this case. In order for RestSharp to deserialize them, you need create a List<T> object where the name of class T matches the name of the listed element, which is why my class name is item in this case.
Once you have your POCO classes in order, then you need to actually make requests against the del.icio.us feed for a particular user. Here's my code for doing that:
public class DeliciousRequest
{
public const string DeliciousFeedBase = @"http://feeds.delicious.com/v2/rss/";
private RestSharp.RestClient _client;
public DeliciousRequest()
{
this._client = new RestClient
{
BaseUrl = DeliciousFeedBase
};
}
public RssFeed GetBookMarksForUser(string username)
{
var request = new RestRequest {RequestFormat = DataFormat.Xml, Resource = username};
var response = this._client.Execute<RssFeed>(request);
return response.Data;
}
}
All RSS feeds for del.icio.us users can be found using http://feeds.delicious.com/v2/rss/{USERNAME}, therefore you can understand why the RestClient's BaseURL and the RestRequest's Resource arguments are defined as they are. Once you have your RestRequest defined, you simply call the client's Execute<T> method where T is the type of your POCO DTO class.
And that's it - RestSharp is easy, and I look forward to creating some more examples with it down the road.
More RestSharp Examples:
If you enjoyed this post, make sure you subscribe to my RSS feed!
65c351cf-dfd5-4508-a2b9-6f9c2a5c1251|2|5.0