CSS Border Radius Generator

0

I just stumbled across this really handy CSS round corner tool. It isn’t magic, but it’s a simple tool that just works. Enjoy.

CSS Border Radius Generator

Are you Learning C#?

0

If you’re learning C# you won’t go much wrong with the C# Yellow book. Rob Miles has just released a new version. This year’s copy is a minor release, of a sort. It’s mostly a couple of corrections to last years content. If you’re starting out with programming or programming C# then you really should take a look: http://www.robmiles.com/journal/2011/10/13/c-yellow-book-2011.html

Dynamic Robots.txt in ASP MVC

0

I recently had the need to switch a robots.txt file dynamically, depending on whether a site was deployed to live or beta servers. The solution was very simple, ditch the real file and replace it with a controller action. This is a brief note on how I did this. I don’t pretend this is an ideal solution, it was something I knocked together before I went out for dinner.

The solution I went for was in three parts: a web.config transform, routing and the controller itself.

The web config transform for my live site looks like this:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <appSettings>
        <add key="SiteStatus" value="live" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
    </appSettings>
</configuration>

The route is equally simple:

routes.MapRoute(
    "Robots.txt",
    "Robots.txt",
    new
    {
        controller = "Robots",
        action = "RobotsText"
    }
);

view raw routing.cs This Gist brought to you by GitHub.

And finally the actual controller:

public class RobotsController : Controller
{
    public FileContentResult RobotsText()
    {
        var content = "User-agent: *" + Environment.NewLine;

        if (string.Equals(ConfigurationManager.AppSettings["SiteStatus"], "live", StringComparison.InvariantCultureIgnoreCase))
        {
            content += "Disallow: /elmah.axd" + Environment.NewLine;
            content += "Sitemap: http://www.jacquelinewhite.co.uk/sitemap.xml";
        }
        else
        {
            content += "Disallow: /" + Environment.NewLine;
        }

        return File(
                Encoding.UTF8.GetBytes(content),
                "text/plain");
    }
}

And there we have it, my robots.txt file now is customised on a per deployment basis.

A Better Guard Class

2

Recently I was working with some of the developers in a different office, I don’t normally see their code, so it was interesting to see how they are meeting various problems. Generally speaking, they are doing some nice looking work. The architecture that they are moving towards looks like it’s going a long way to solving a lot of problems, all good stuff.

One bit of code that I kept seeing really bothered me. It was a guard class that I kept seeing. I think it was a clone of a class from the here. The reason it bothered me was simply that it didn’t read well, I kept thinking that it was guarding against an exception. In reality it was guarding against an error condition and would throw an exception if the condition happened. For example:

Guard.Against<InvalidOperationException>(string.IsNullOrEmpty(serverName), "Server name must be provided")

I would much rather something that reads like this:

Throw<InvalidOperationException>
    .WithMessage("Server name must be provided")
    .When(string.IsNullOrEmpty(serverName));

Here’s my implementation of the class, thoughts?

public static class Throw<T> where T : Exception
{
    public static Thrower WithMessage(string message)
    {
        return new Thrower(message);
    }

    public class Thrower
    {
        private readonly string message;
        public Thrower(string message)
        {
            this.message = message;
        }

        public void When(Func<bool> predicate)
        {
            if (predicate())
            {
                throw (T)Activator.CreateInstance(typeof(T), message);
            }
        }

        public void When(bool condition)
        {
            if (condition)
            {
                throw (T)Activator.CreateInstance(typeof(T), message);
            }
        }
    }
}
view raw Throw.cs This Gist brought to you by GitHub.

Handling Google Instant in ASP MVC

0

I love google chrome, it’s how browsers should be, it just works. The one thing I really like about it is the instant setting. The problem is that most sites don’t really know the difference between a bad url and a url that is being typed.

Well, now you can and it’s really simple.

The following extension method will let your controller know if it’s a full request or simply a user busy typing:

public static class RequestExtensions
{
    public static bool IsPreview(this HttpRequestBase request)
    {
        var purpose = request.Headers["X-Purpose"] ?? string.Empty;
        return string.Equals(": preview", purpose, StringComparison.InvariantCultureIgnoreCase);
    }
}
view raw gistfile1.cs This Gist brought to you by GitHub.

A very simple use of it would be something like this:

public virtual ActionResult Error404()
{
    Response.StatusCode = (int)HttpStatusCode.NotFound;
    if (Request.IsPreview())
    {
        ViewBag.Message = "Nope, I've haven't go that, keep typing.";
    }
    else
    {
        ViewBag.Message = "Sorry, but the file you requested was not found on the server.";
    }

    return View();
}
view raw gistfile1.cs This Gist brought to you by GitHub.

Let me know if you use this is a more creative way.

Encrypt Connection Strings on Application Startup

0

Just so I don’t forget how I do this:

protected void Application_Start()
{
#if !DEBUG
    EncryptConnectionStrings();
#endif
}

private void EncryptConnectionStrings()
{
    var sectionName = "connectionStrings";
    var config = WebConfigurationManager.OpenWebConfiguration("~");

    ConfigurationSection section = config.GetSection(sectionName);

    if (section != null && !section.SectionInformation.IsProtected)
    {
        section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
        config.Save();
    }
}
view raw gistfile1.cs This Gist brought to you by GitHub.

FluentMigrator Code Templates

0

A little while back I created some migrator.net code templates. Since I’ve now moved over to using FluentMigrator it seemed only reasonable that I port the templates for the FluentMigrator project as well. To use them simply take the zip file from here and drop it into C:\Users\username\Documents\Visual Studio 2010\Templates\ItemTemplates\Visual C#\ Once you’ve done that restart Visual Studio and you’ll be able to do File > New File > New Fluent Migration. Give the file a name and you’ll get a code file a little like this:

Which I happen to think is rather nice.

PIXELS by Patrick Jean

0

This has been round the web for a while now, but it still makes me smile.

A Quick and Dirty Cache

0

Brownfield development on a tight deadline is never fun, it’s never elegant and it’s certainly not satisfying.

One problem I keep finding is code that repeatedly calls the backing stores with the same query. If I don’t have the time to refactor the code to work properly I sometimes cheat and use a cache that’s specific to the HttpContext. It’s not nice, but it does get me out of a hole every once in a while.

public static class ContextCache
{
	public static T Get(string key)
	{
		var value = HttpContext.Current.Items[key];
		return value is T ? (T)value : default(T);
	}

	public static void Put(string key, object value)
	{
		HttpContext.Current.Items[key] = value;
	}
}

It’s pretty simple to use:

var entity = ContextCache.Get("Entity_123");
if (entity == null)
{
    entity = GetFromBackingStore(123);
    ContextCache.Put("Entity_123", entity);
}

return entity;

This is definitely one of those bits of ugly code that can get you out of a hole in a rush. It aint pretty, but it works.

Forcing Culture Settings in WCF

1

I had the need to force the thread culture on a WCF service recently. The culture kept dropping back to en-US, but I needed it to run in en-GB as the client was sending me files with UK dates in them. After banging my head against every setting I could find I gave up and opted to write a custom WCF service and force the culture. It’s not a pretty hack, but it works.

If you use this and it breaks your servers, steals your wallet and then runs off with your wife, consider it your fault for using code from some random blog post you found. Caveat emptor applies.

You can download a working sample here: WCFCulture

First up we need to create a message inspector to hook in and mush about with our messages:

public class CultureMessageInspector : IDispatchMessageInspector
{
	private readonly string _culture;
	public CultureMessageInspector(string culture)
	{
		_culture = culture;
	}

	public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
	{
		Thread.CurrentThread.CurrentCulture = new CultureInfo(_culture);
		return null;
	}

	public void BeforeSendReply(ref Message reply, object correlationState)
	{
	}
}

Then we need to hook this into an endpoint behaviour:

public class CultureBehavior : IEndpointBehavior
{
	private readonly string _culture;
	public CultureBehavior(string culture)
	{
		_culture = culture;
	}

	public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
	{
	}

	public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
	{

	}

	public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
	{
		var inspector = new CultureMessageInspector(_culture);
		endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
	}

	public void Validate(ServiceEndpoint endpoint)
	{
	}
}

And because we want to configure the culture we end up using, we need a custom extension element:

public class CultureExtensionElement : BehaviorExtensionElement
{
	[ConfigurationProperty("Culture", DefaultValue = "en-GB")]
	public string Culture
	{
		get { return (string)base["Culture"]; }
		set { base["Culture"] = value; }
	}

	protected override object CreateBehavior()
	{
		return new CultureBehavior(Culture);
	}

	public override Type BehaviorType
	{
		get { return typeof(CultureBehavior); }
	}
}

Ok, so assuming that you can get that pretty lot to compile all we need to do is hook it in via the web.config in the services project.

First register the extension:


	
		
			
		
	

Then to your behaviour simply add:

Your resulting config should look a bit like this:


	
		
			
				
				
			
		
		
			
				
			
		
	
	
		
			
		
	
	

So now, it won’t matter what your client wants the culture to be, you can override it in config.

Go to Top