Posts tagged C#
FluentSitemap: Build Sitemaps for Asp.Net MVC
0Building your site is only half the battle. Getting people to know it exists is the other half. If you are creating a public facing site, or even an intranet that utilizes an in-house search server then I have created a library just for you. The library is FluentSitemap. This library is designed to help you easily build sitemaps to be utilized by major search engines. The great thing about this library is that utilizes all your existing routes and controllers to build a sitemap even for the most complex Asp.Net MVC sites.
The FluentSitemap library can be found at GitHub Here.
How to use you, Let me count the ways
There are several ways you can utilize this library. The first is to specify each node manually. Let’s look at how that looks.
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// create sitemap node and set
ISitemap sitemap = configurator.Create()
.WithLocation("http://localhost.com/")
.WithPriority(0.3)
.WithChangeFrequency(ChangeFrequencyType.Never)
.Set().Export();
The second is to use a controller/action pair.
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// Add From a controller and action
ISitemap sitemap = configurator.Add("Home", "Index")
.Add("Home", "About").Export();
The third is to use a route
// You can pass in a HttpContext from anywhere
// in you application
ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);
// Add From a controller and action
ISitemap sitemap = configurator
// Add From a Route
.AddFromRoute("Default", new {id = "2"}).Export();
The last is to use the ISitemetadata. This is specifically there for IoC.
public class HomeControllerSitemapMetadata : ISitemapMetadata
{
private const string Home = "Home";
#region ISitemapMetadata Members
public void Create(ISitemapConfigurator sitemap)
{
sitemap.Add(Home, "Index")
.Add(Home, "Scanner")
.Add(c => c.Metadata());
}
#endregion
}
public class OtherControllerSitemapMetadata : ISitemapMetadata
{
private const string Other = "Other";
#region ISitemapMetadata Members
public void Create(ISitemapConfigurator sitemap)
{
sitemap.Add(Other, "Index")
.Add(c => c.Test(1, "dude"));
}
#endregion
}
// An example, you'll probably use your favorite
// IoC container to resolve all the metadata classes
var metadata = new List
{new HomeControllerSitemapMetadata(), new OtherControllerSitemapMetadata()};
ISitemap sitemap = new SitemapConfigurator(HttpContext).FromMetaData(metadata).Export();
There is more API sugar, so go download it and give it a try.
C4MVC Presentation on Database Migrations
0Hello everybody. It has been about a week since I gave my C4MVC presentation on database migrations. The video is below, and the code is also downloadable below.
Asp.Net MVC 2 Quick and Simple Site – v1
0*Note: Asp.Net MVC 2 project in Visual Studio 2010
I sat down last night and was thinking about how I could get a simple starter site up and running for a client, until I could design something more tailored to their needs. There is nothing worse than having a “under construction” page or a “coming soon” page. It doesn’t really say much about what is happening or what might be coming. So I sat down and came up with the basics of what a client might want right from the start, here were my requirements.
- Set a Logo, Name, and Subtitle
- Be able to quickly edit a small about section (Content)
- Quickly add some of the more important social networks (Twitter, YouTube, FeedBurner, Delicious, MySpace, and Facebook).
- Be able to add Google Analytics (Optional)
- A dynamic image gallery (drop images in a directory and everything is done for you).
- Basic contact information. Email, Phone, and Website.
- No external libraries to install (this hurts but is helpful).
So I sat down and started writing. I wanted someone to be able to push this site without editing a lot of files or having to setup a database. I opted to put a lot of the client’s settings in configuration. Yes configuration sections are not the new hotness but they can still serve a powerful purpose.
My first iteration had me using controller actions for each part of the site, but I slowly realized it was overkill. I opted to have one controller action from my index, and then break sections up into partial views that would be all rendered at the same time. Then those sections would be hidden and made visible using JQuery. After a little design, I ended up with this.
Let’s look at how to set this up.
Step 1 – Setup the Configuration
There are some pretty simple configuration sections in the web.config included with this project. You will see two App settings: WorkImagesDirectory and GoogleAnalyticsCode. The WorkImagesDirectory is used to find all the images in your gallery. Thumbnails for all your images will be automatically created if they are missing. The GoogleAnalyticsCode setting should be set to your Google Analytics code UA-XX-XXXX (or something like that). If you leave out the Google Analytics code then the script won’t be output to the page.
Next you will see a ContactInformation section. In this section you can set the name, site subtitle, email, phone, and website.
Finally, you will see a SocialNetworks section. Only the social network usernames you set will show up on the page. You can set Twitter, Facebook, YouTube, Delicious, MySpace, and FeedBurner(a blog maybe).
Step 2 – Setup Content
Once the configuration is done, then you probably want to change some of the content to reflect some good information.
All tabs are separated into partial views: About, Contact, Work, Social. Just replace the HTML content in here with what you want, leaving the nested RenderPartials.
Step 3 – Modify Colors and Images
All the images and style sheets you need to modify are under the Content directory. If you like the color and just want to modify the avatar at the top, just overwrite the avatar.png under Content/img.
Step 4 – Deploy It
Just publish what is there to your hosting provider and you are ready to go.
Conclusion
This is a good little site to get up and running for your clients, but it isn’t anything ground breaking. The code is straight forward, so even a novice can get in there and change things. The point here was not to over complicate the solution with third party libraries. It is to get a site up with in minutes, while still giving some great functionality to the people that need it.
Main Site Now iPhone Enabled
0Have I pronounced my love for ASP.NET MVC yet? Well if I haven’t then let me do it now. I love you ASP.NET MVC! With very minimal effort, about 3 hours, I was able to create an iPhone version of the main site of Aqua Bird Consulting. I used JQTouch for the iPhone functionality, and used a new view engine to determine whether your coming in through an iPhone. Check out the pictures below. I’ll be pushing this nice feature out pretty soon. I still need to delve deeper into JQTouch, but I am confident that most ASP.NET MVC applications can be converted to an iPhone version with no effort at all.
Attack of the Bots! – Stop Them With ReCAPTCHA in ASP.NET MVC
4As developers sometimes we forget that there are bad people out there. Nefarious people waiting for you to mess up, just so they can exploit your weaknesses. One of the biggest problems with the internet
today is the use of bots. If you have ever run a publicly open site like a blog, forum, or contact form then you know what I mean. You get flooded with junk that you didn’t even know existed. This can be a huge problem, because it essentially makes the data coming in hard if not impossible to sort. So how do you stop these advanced monsters from reeking havoc on your public facing site?
We first have to understand how they exploit your site. You probably have some kind of form on your site. It is there for anyone and everyone to use, just like you intended. You spent hours meticulously crafting this form with valid HTML and readable labels. There is your first problem. Bots traverse your page looking for FORM tags. Then they proceed to look for INPUT tags which match their criteria. If you use a popular CMS or Blogging engine then you are already at a disadvantage. These systems are known by bots and there are no surprises on how your system works. Then the bots proceeds to submit the form. All this occurs in a matter of nanoseconds. Remember computers are fast, even when they are evil. Now the bots have a choice, leave your defenseless site in search of another or proceed to submit your form mercilessly until your site collapses and your inbox is filled with worthless junk.
The popular solution to combating bots has been CAPTCHA systems. CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart.” It usually involves a challenge-response test. The most popular kind is to show scrambled words in an image, which can be seen below. Some CAPTCHA systems can also get very strange. I have seen one that shows you screenshots of cute fuzzy animals and asks you to pick the kitten. This really is a interesting subject and I suggest you read the Wikipedia page on CAPTCHA.

Let’s get started in developing a solution. You might be thinking to yourself, “I don’t want to write a crazy CAPTCHA system.” Well you are in luck, there are several services on the internet that let you utilize their system. My favorite service is ReCAPTCHA. It offers both image based CAPTCHA tests along with audio tests for better accessibility. Let me show you what the final product will be like. I will be using the ASP.NET MVC sample project and modifying the registration page to add CAPTCHA checking. Dilled Fresno!?!? What the heck is that?

Step 1 – Getting Your ReCAPTCHA account.
Go to the ReCAPTCHA site and sign up for your keys. You will get a private key and and a public key. Copy these to notepad, you will need them.
Step 2 – Download the .Net Library for ReCAPTCHA
You will need to download the ReCAPTCHA .NET Library. Technically you don’t need this, you could write your own wrapper, but this makes it much easier. Go ahead and add this to your ASP.NET MVC project as a reference.
Step 3 – Implement the Client-Side
You want the ReCAPTCHA red box to show up on your site. So we are going to have to put some code in your view. ReCAPTCHA has already provided this code for for you. I have placed it below for faster access. Place this code within your Form tag, it is critical that you do so. Ok you are done. I also placed a ValidationMessage underneath the ReCAPTCHA code so that I could see my message.
<script type="text/javascript"
src="http://api.recaptcha.net/challenge?k=<YOUR PUBLIC KEY>">
</script>
<noscript>
<iframe src="http://api.recaptcha.net/noscript?k=<YOUR PUBLIC KEY>"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
<%= Html.ValidationMessage("ReCaptcha") %>
Step 4 – Implement the Server-Side
When the form is submitted, there will be two extra inputs submitted to your controller action. The “recaptcha_response_field” value and the “recaptcha_challenge_field” value. We will be using these to verify that the user is really human. So for the code that performs the CAPTCHA.
private bool PerformRecaptcha()
{
var validator = new RecaptchaValidator
{
PrivateKey = "<YOUR PRIVATE KEY>",
RemoteIP = Request.UserHostAddress,
Response = Request.Form["recaptcha_response_field"],
Challenge = Request.Form["recaptcha_challenge_field"]
};
try
{
var validationResult = validator.Validate();
if (validationResult.ErrorCode == "incorrect-captcha-sol")
ModelState.AddModelError("ReCaptcha", string.Format("Please retry the ReCaptcha portion again."));
return validationResult.IsValid;
}
catch (Exception e)
{
ModelState.AddModelError("ReCaptcha", "an error occured with ReCaptcha please consult documentation.");
return false;
}
}
RecaptchaValidator is from the assembly you referenced. Notice that we need to set the private key, and that we are getting the user’s I.P. address. We also set the fields that we got from the form. Now we just need to ask the service if everything is ok. The rest is trivial ASP.NET MVC code.
Conclusion
You can get ReCAPTCHA into your site in about 5 minutes, but it might take some time to perfect how you want it to integrate with you current scheme. For me, I don’t make a call to ReCAPTCHA if my model is not valid (see code below), this saves me an expensive and unnecessary internet call. I am also considering placing similar code in an ActionFilter, in the same fashion as ValidateAntiForgeryTokenAttribute. It should be pretty simple to do that.
if (ModelState.IsValid && PerformRecaptcha())
{
...
}
So now you have the power to stop those evil bots and take bake your site. Hope this helps.
So You Want To Build A Plug-in Enabled Application?
0Like the title of this post asks, so you want to build a plug-in enabled application? As a developer I’ve run across this scenario at different times during my career and every time it pops up, I always seem to know a little more than I did the last time I approached this problem. This post is about helping you think about a plug-in application of your own. First, let’s look at scenarios where you would want to have a plug-in architecture.
It’s Plug-in Time!
Ok before you use this hammer, you first have to know what you’re swinging at. Below are common usages for a plug-in application, but certainly not all the scenarios.
- Job Scheduler
- Content Management System or Blog Engine
- Integrated Development Environment (IDE)
- Highly Customizable Software Products
- And Much More!!
So those are a few ideas of where a plug-in architecture could be helpful, now lets look at what you should keep in mind when developing a plug-in based application.
Shells Aren’t Just For Turtles
For any good plug-in architecture to work it will need a solid shell. A shell is that part of the architecture that orchestrates and manages all those plug-ins you want to work together. Below are some
features to keep in mind when creating a shell. They are in no particular order of importance.
- Service Location : The shell should be capable of finding services, and giving a plug-in the ability to find a service as well.
- Strong Exception Handling: The shell shouldn’t trust any plug-in to do its job. If the plug-in is bad, that doesn’t mean the shell has to freak out.
- Logging: The shell should let you know what it’s doing, and what it hopes to do if all goes well.
- Instrumentation: The shell should let you enable and disable a plug-in. This could be as simple as deleting a configuration or building an admin tool.
- Abstract: The more abstract your shell is, the more the responsibility of functionality falls on your plug-in. This is a good thing.
- Orchestration Theme: The shell has a theme to its orchestration i.e. executing a scheduled job, displaying web pages, etc.
- Event Aggregation: Things happen in plug-ins, but how are you going to let other plug-ins know or the shell for that matter.
Keeping some of the things mentioned above in mind will help keep you on the right path when building the shell, but what about those plug-ins? That’s the next step.
It’s in the Contract
There are usually two approaches to allowing developers to create a plug-in. The one way is through inheritance. The developer inherits from “PluginBase” that has methods he needs to override. From my experience having a “PluginBase” has always lead to more headache than it is worth. I found that functionality would be inherited into a plug-in that I didn’t necessarily want. Any functionality I wanted in all and every plug-in usually ended up finding a better home in the shell.
The second way to allow developers to create a plug-in is through interfaces/contracts. Interfaces give developers a better understanding of what they need to implement, and with interfaces there is more room for composition. Remember .Net does not support multiple inheritance but it does allow for multiple interfaces. This allows a developer to build very specific plug-ins by only implementing the interfaces that make sense. i.e. a plug-in that has a UI might implement a UIPlugin contract, where as a plug-in that doesn’t have a UI would just neglect implementing that interface.
The Right Technology Stack
The success of your architecture depends on the technology you choose. As like any other development project, you have to choose the right tools for the job. If your plug-in architecture needs to span across networks and live on multiple machines, storing your configuration in files might not be a good idea. If your plug-in architecture exists on one machine, then you probably don’t need WCF or any other kind of remoting. That being said, you should build your architecture so that you can change major parts of your architecture without major effort or overhaul of the entire architecture. Using patterns like IoC can help make this less earth shattering.
Conclusion
Plug-in Architectures are very powerful. They can be the solution to a lot of problems, but I would not advise going down this route if you just want to flex your development muscles. A good exercise to do is to whiteboard the different aspects of your architecture. Draw a large circle in the middle of the board and label it “Shell,” then draw little circles connected to the larger circle for each plug-in. This will help you visualize what your plug-ins are, and what your shell needs to accomplish for these things to work together. Once you realize what the shell is and more importantly is not, you will find your plug-in architecture will fall right into place.
Good Luck,
I know these kind of projects can be really fun
My First Week with Behavior Driven Development
0
I sat down last week to start a new project with ASP.NET MVC 2. The project was something simple in theory, but I knew the details would get me. I have been a long time advocate of Test Driven Development or TDD, but wanted to give this thing called Behavior Driven Development (BDD) a chance (again). A long time ago I explored BDD frameworks but I was always too busy to really give it the chance to sink in to my brain. This time I decided to buckle down and give it an honest go. Below are the things I’ve noticed with my first serious week experience with BDD.
Tests Take Longer To Think Up
This might sound like a bad thing, but it isn’t. Before with TDD, I would pick a service and then write a test for a particular method within that service. My tests would come together pretty fast, but there was always a disconnect. Why did I choose to write the test first and that way? The answer to these questions would be in my head, but other developers can’t see into my head. Think of it this way; if TDD helped me figure out the WHAT, BDD helped me clear up the WHY. My BDD tests are a lot more specific about their intention and the context the test exists in. If another developer would come along and read my specifications, they can read them and know what the WHY behind my code is.
All My Knowledge Still Applies
Although I am taking a different approach to developing an application, I still use all the knowledge I have accumulated up to the point I turned to BDD. I am still using NUnit, IoC, Moq, Domain Driven Design, and all my other conventions. With BDD, you are simply just reframing your existing tools and skills and not changing them. When I first started, I felt like I was entering a new arena, but it soon became comfortable when I noticed it is not a lot is different.
I Totally Need A Context
A BDD test is called a Story, and each story has scenarios. Scenarios follows the form of “Given X When Y Then Z”. With most frameworks I’ve looked at, each part of the scenario is an independent method that is executed. So to link the scenario up you need a context that is passed to each step of the scenario. Without a context you’ll find it really hard to link each aspect of the scenario.
Lambdas Are My Friends
BDD thrives in the new .NET 3.5 and 4 frameworks. If it wasn’t for lambda expressions my tests would be a lot less readable and a lot longer (my fingers would fall off).
People Might Think I’m Crazy
I find myself talking out loud, trying to find the best phrasing for scenarios. People might look at you weird if you do this in an office environment, but the more you talk to yourself the more fluid scenario creation will be.
It All Comes Together
I’m amazed at how stuff just works the first time when it’s all wired up. I know that’s the point of writing specs and passing them, but it really is amazing. If something fails in my application it is usually because I forgot to register a type in my IoC container or I mistyped something in the View. That saves me tons of frustration, and I like it.
Conclusion
Is BDD better than TDD? I feel that both TDD and BDD are two sides of the same coin. My main goal should be to test functionality and both approaches do that. That being said, I feel that BDD has made my development process a lot more thoughtful. Is BDD the silver bullet? Not even close, at the end of the day you, the developer, are responsible for the quality of your code. Using a process like BDD or TDD challenges my discipline, and if I don’t have it then any approach to software development will be filled with frustration and hurt. On the bright side, I feel it is never to late to learn something new and improve my skills, so give something new a chance and happy coding.
Dictionary of U.S. States
1This post is not exactly ground breaking but can be very useful when you have objects that have a State property. It is this kind of stuff that can kill your development mojo and slow you down. That is why I posted it on here, so you can move on to the more important stuff.
public static class USStates
{
public static readonly Dictionary States = new Dictionary
{
{"AL"," Alabama"},
{"AK"," Alaska"},
{"AZ"," Arizona"},
{"AR"," Arkansas"},
{"CA"," California"},
{"CO"," Colorado"},
{"CT"," Connecticut"},
{"DE"," Delaware"},
{"FL"," Florida"},
{"GA"," Georgia"},
{"HI"," Hawaii"},
{"ID"," Idaho"},
{"IL"," Illinois"},
{"IN"," Indiana"},
{"IA"," Iowa"},
{"KS"," Kansas"},
{"KY"," Kentucky"},
{"LA"," Louisiana"},
{"ME"," Maine"},
{"MD"," Maryland"},
{"MA"," Massachusetts"},
{"MI"," Michigan"},
{"MN"," Minnesota"},
{"MS"," Mississippi"},
{"MO"," Missouri"},
{"MT"," Montana"},
{"NE"," Nebraska"},
{"NV"," Nevada"},
{"NH"," New Hampshire"},
{"NJ"," New Jersey"},
{"NM"," New Mexico"},
{"NY"," New York"},
{"NC"," North Carolina"},
{"ND"," North Dakota"},
{"OH"," Ohio"},
{"OK"," Oklahoma"},
{"OR"," Oregon"},
{"PA"," Pennsylvania"},
{"RI"," Rhode Island"},
{"SC"," South Carolina"},
{"SD"," South Dakota"},
{"TN"," Tennessee"},
{"TX"," Texas"},
{"UT"," Utah"},
{"VT"," Vermont"},
{"VA"," Virginia"},
{"WA"," Washington"},
{"WV"," West Virginia"},
{"WI"," Wisconsin"},
{"WY"," Wyoming"},
{"AS"," American Samoa"},
{"DC"," District of Columbia"},
{"FM"," Federated States of Micronesia"},
{"MH"," Marshall Islands"},
{"MP"," Northern Mariana Islands"},
{"PW"," Palau"},
{"PR"," Puerto Rico"},
{"VI"," Virgin Islands"},
{"GU"," Guam"}
};
public static IList GetAbbreviations()
{
return States.Keys.ToList();
}
}
I have also included Commonwealths and Territories. I have excluded Military states like “Armed Forces Africa”. The list I used can be seen at 50States.com. This list should be good for a long time.
Picking Your Constructor With Unity
0I use Enterprise Library’s Unity for my Inversion of Control container. I also use constructor based injection when writing my own services, repositories, and objects; this is the cleanest form of injection IMHO. All my classes usually have one constructor, so I rarely run into a problem with overloaded constructors, but other libraries don’t usually follow this convention (rightfully so, not everyone does IoC). I am currently working on a project using Rob Conery’s awesome SubSonic 3, but I ran into a little speed bump.

oh jeez! So I have a class that has more than one constructor and I need Unity to pick the right constructor. If you are familiar with Unity then the bottom code will look familiar.
container.RegisterType<IUsersService, UsersService>()
.RegisterType<IUsersRepository, SubSonicUsersRepository>()
.RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
.RegisterType<IRepository, SimpleRepository>();
So how do you pick the constructor you want. Well it’s simple, you just have to let Unity know by configuring your container.
container.RegisterType<IUsersService, UsersService>()
.RegisterType<IUsersRepository, SubSonicUsersRepository>()
.RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
.RegisterType<IRepository, SimpleRepository>()
.Configure<InjectedMembers>()
.ConfigureInjectionFor<SimpleRepository>(new InjectionConstructor(SimpleRepositoryOptions.Default));
You’ll notice we have to say what we are configuring. In this instance we want to configure an injected member. The next step is to pick the target, the concrete target, which is SubSonic’s SimpleRepository. Finally, we create a InjectionConstructor class which will hold all of our parameters for the constructor. Again, I rarely use this feature within my own code so I forget it and have to go looking for it in old code. Hopefully blogging about it will keep it fresh in my mind or at the very least I know where to look now.
Hopefully this helps.
DataContract Serialization Extension Methods
0This is a classic that I have pulled from my last blog’s archives, but I thought I would post it here because I find myself going back time and time again. It really is a great set of extension methods, especially if you need an instant object dump or you are creating a simple XML repository. These methods allow you to serialize to a string/XML and deserialize from a string to the type you specify.
public static class DataContractSerializationExtensions
{
#region Serialize
public static string Serialize<T>(this T target)
{
return Serialize(target, null);
}
public static string Serialize<T>(this T target, IEnumerable<Type> knownTypes)
{
using (var writer = new StringWriter())
{
using (XmlWriter xmlWriter = new XmlTextWriter(writer))
{
var ser = new DataContractSerializer(typeof(T), knownTypes);
ser.WriteObject(xmlWriter, target);
return writer.ToString();
}
}
}
#endregion
#region Deserialize
public static T Deserialize<T>(this string targetString)
{
return Deserialize<T>(targetString, null);
}
public static T Deserialize<T>(this string targetString, IEnumerable<Type> knownTypes)
{
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(targetString)))
{
using (var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas()))
{
var ser = new DataContractSerializer(typeof(T), knownTypes);
// Deserialize the data and read it from the instance.
return (T)ser.ReadObject(reader);
}
}
}
#endregion
}
Have fun serializing and deserializing.
