Tired of looking for errors in log files? Use OneTrueError - Automatic exception management for .NET.

ADO.NET, the right way

ADO.NET is actually quite powerful if you use it correctly. This post will teach you everything from making your ADO.NET code driver independent to how to implement the repository pattern and unit of work. This is the follow up post of my “Datalayer, the right way” post. The purpose is to demonstrate that ADO.NET can be used as an alternative to OR/Ms.

Continue reading

Posted in CodeProject | Tagged , | 19 Comments

Data layer, the right way.

The goal with this post is to give you a better understand about how you can design your data layer and why it’s important to create a complete abstraction layer.

Continue reading

Posted in Architecture | Tagged | 5 Comments

Better support for localization in ASP.NET.

If you’ve tried the built in localization features in ASP.NET you’ll probably written cluttered view models like:

Continue reading

Posted in Architecture, CodeProject | Tagged , | 4 Comments

Solved: Getting 401 Unauthorized while calling an ASMX service using windows authentication

Today I’ve spent almost the whole day to figure out why an application (COM+) couldn’t authenticate against a ASMX web service. Using my favorite networking tools Wireshark and HTTP Fiddler I saw that the credentials didn’t get included in the initial request, and no other request was made when the 401 challenge came from the web service.

Continue reading

Posted in Uncategorized | Tagged , | 10 Comments

Griffin.Decoupled – Winforms sample application

I’ve created a small winforms sample application to demonstrate the features of Griffin.Decoupled. I’ve intentionally kept it small to just demonstrate the core features. This post won’t get into the details of how to bootstrap the framework. There are several samples for that. Instead I’ll show how you can put all pieces together using RavenDB as backend.

Continue reading

Posted in Uncategorized | 2 Comments

Griffin.Networking – Added support for HTTP ranges

Added support for partial file downloads (content ranges)

Someone requested that I should add support for the Range headers in the HTTP protocol. I’ve done that now. But let’s back up a bit first.

In Griffin.Networking you can send files no matter the file size (GB files are no problem). What you do is simply to invoke Send() in your service class. Here is an example:

public class YourService : IServiceService
{
	public override void HandleReceive(object message)
	{
		var buffer = (byte[])message;
		// check message here
		
		var fileStream = new FileStream(@"C:MyFilesSomeVeryLargeFile.zip", FileMode.Open,
                                                FileAccess.Read, FileShare.ReadWrite);

		Context.Send(fileStream);
	}
}

That’s it. The framework will take care of the file sending, sending one piece at a time (the size of the piece is determined by the buffer pool size that you defined when creating the server).

Dealing with ranges manually

In a custom tailored server (i.e. you just use the HTTP protocol implementation from Griffin.Networking) you do it like this:

var rangeHeader = request.Headers["Range"];
if (rangeHeader != null && !string.IsNullOrEmpty(rangeHeader.Value))
{
	var response = request.CreateResponse(HttpStatusCode.PartialContent, "Roger, you'll get partial content");
	response.AddHeader("Accept-Ranges", "bytes");
	var fileStream = new FileStream(@"SomeFilePath", FileMode.Open,	FileAccess.Read, FileShare.ReadWrite);

	// parse requested ranges.
	// we can parse all, but currently do only support one in the ByteRangeStream
	var ranges = new RangeCollection();
	ranges.Parse(rangeHeader.Value, (int)fileStream.Length);
	response.AddHeader("Content-Range", ranges.ToHtmlHeaderValue((int)fileStream.Length));

	// move to the correct position in the inner stream.
	// will also report the correct range size instead of the entire file size
	// will support serving multiple ranges in the same response in the future.
	response.Body = new ByteRangeStream(ranges, fileStream); 
	Send(response);
}

// all other request processing here.

A full example can be found in the HTTP protocol sample folder at github.

Using the webserver

I’ve moved the WebServer implementation from Griffin.Networking repository to a seperate one at Github called Griffin.WebServer. It contains a file module which supports caching, partial file downloads and listing files (if enabled).

You can configure a HTTP server which serves static files like this:

// Module manager handles all modules in the server
var moduleManager = new ModuleManager();

// Let's serve our downloaded files (Windows 7 users)
var fileService = new DiskFileService("/", string.Format(@"C:Users{0}Downloads", Environment.UserName));

// Create the file module and allow files to be listed.
var module = new FileModule(fileService) {ListFiles = true};

// Add the module
moduleManager.Add(module);

// And start the server.
var server = new HttpServer(moduleManager);
server.Start(IPAddress.Any, 8080);

The WebServer is still work in progress. The pieces are however coming together pretty well.

Posted in Uncategorized | Tagged , , , | Leave a comment

Displaying date/time using the user timezone in ASP.NET MVC

This post will show you how you can display date/time using the user timezone (without it being configured anywhere in your application).

Continue reading

Posted in CodeProject | Tagged | 3 Comments

New version of Griffin.Networking – A networking library for .NET

I’ve refactored Griffin.Network quite a lot (I did say that it was still an early release). The new version is called v0.5 (the library is taking shape, but there is still some things to take care of).

Highlights:

1. The pipeline is no longer mandatory
2. I’m using the Async methods instead of Begin/EndXxxx
3. The buffer management is a more effecient
4. It’s easier to work with the buffers
5. Introducing messaging support

Continue reading

Posted in Architecture, CodeProject | Tagged , , | 8 Comments

Feature request: Visit the oldest bookmark

Can someone please make an extension for Google Chrome which once a week suggest that I should visit my oldest bookmark (i.e. the one that I haven’t clicked on for the longest time).

In that way I can start cleaning up my bookmarks.

Posted in Uncategorized | Leave a comment

How to dynamically modify model meta data in ASP.NET MVC

Normally you just add the [Required] attribute to a view model to make it required. But I needed a way to configure whether a field to be required or not. The requirement was that it should be configured through web.config:

<appSettings>
    <add key="ticket-cat1-required" value="true" />
</appSettings>

Having to modify the view or the controller would not be very clean. Instead it’s much better to take advantage of the ModelValidatorProvider. I could have just done like this:

public class ConfigurableModelValidatorProvider : LocalizedModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<System.Attribute> attributes)
    {
        bool isRequired = metadata.ContainerType == typeof (CreateViewModel)
                            && ConfigurationManager.AppSettings["ticket-cat1-required"] == "true";


        var theAttributes = attributes.ToList();
        if (!theAttributes.Any(x => x is RequiredAttribute) && isRequired)
            theAttributes.Add(new RequiredAttribute());

        return base.GetValidators(metaDataContext.Metadata, context, attributes);
    }
}

And then assigned it in global.asax:

protected void Application_Start()
{
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new ConfigurableModelValidatorProvider());

    //...
}

But that would have created a tightly coupled provider.

The loosely coupled way

Instead I decided to take advantage of my inversion of control container and define some interfaces.

/// <summary>
/// Can adapt the generated metadata before it's sent to the view
/// </summary>
public interface IModelMetadataAdapter
{
    /// <summary>
    /// Adapt the meta data
    /// </summary>
    /// <param name="context">Context information</param>
    void Adapt(MetadataContext context);
}

The context used to modify the meta data:

/// <summary>
/// context for <see cref="IModelMetadataAdapter"/>
/// </summary>
public class MetadataContext
{
    /// <summary>
    /// Initializes a new instance of the <see cref="MetadataContext"/> class.
    /// </summary>
    /// <param name="metadata">The metadata.</param>
    public MetadataContext(ModelMetadata metadata)
    {
        if (metadata == null) throw new ArgumentNullException("metadata");
        Metadata = metadata;
    }

    /// <summary>
    /// See MSDN for info
    /// </summary>
    public ModelMetadata Metadata { get; set; }
}

Which allowed me to create this class (which is automatically registered in Griffin.Container):

[Component]
public class ToggleRequiredOnCreateModel : IModelMetadataAdapter
{
    public void Adapt(MetadataContext context)
    {
        if (context.Metadata.ContainerType != typeof(CreateViewModel))
            return;
        context.Metadata.IsRequired = false;
        if (context.Metadata.PropertyName != "Category1")
            return;

        context.Metadata.IsRequired = ConfigurationManager.AppSettings["ticket-cat1-required"] == "true";
    }
}

To make it all possible I’ve also have to modify the validator provider:

public class ConfigurableModelValidatorProvider : LocalizedModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<System.Attribute> attributes)
    {
        var services = DependencyResolver.Current.GetServices<IModelMetadataAdapter>();

        var metaDataContext = new MetadataContext(metadata);
        foreach (var service in services)
        {
            service.Adapt(metaDataContext);
        }

        var theAttributes = attributes.ToList();
        if (!theAttributes.Any(x => x is RequiredAttribute) && metaDataContext.Metadata.IsRequired)
            theAttributes.Add(new RequiredAttribute());

        return base.GetValidators(metaDataContext.Metadata, context, attributes);
    }
}

In my case I’m using my Griffin.MvcContrib project to handle the localization, that’s why I inherit LocalizedModelValidatorProvider and not DataAnnotationsModelValidatorProvider.

Posted in Architecture | Tagged | Leave a comment