Filtered by Month (1) and Year (2013)
This post walks you through on how you can install hub extension for Git (by defunkt) on Windows to work with GitHub more efficiently.
@ 01-19-2013
by Tugberk Ugurlu

We are all in love with Git but without GitHub, we love Git less. On GitHub, we can maintain our projects very efficiently. Pull Request” and "Issues" features of GitHub are the key factors for that IMO. You can even send yourself a pull request from one branch to another and discuss that particular change with your team. As your discussion flows, your code can flow accordingly, too. This is just one of the many coolest features of GitHub.

There is a cool Git extension for GitHub which is maintained by one of the founders of GitHub: Chris Wanstrath. This cool extension named hub lets us work with GitHub more efficiently from the command line and perform GitHub specific operations easily like sending pull requests, forking repositories, etc. It’s fairly easy to install it on other platforms as far as I can see but it’s not that straight forward for Windows.

You should first go and install msysgit on Windows and I am assuming most of us using this on Windows for Git. Secondly, we should install Ruby on windows. You can install Ruby on windows through RubyInstaller easily.

After installing ruby on our machine successfully, we should add the bin path of Ruby to our system PATH variable. In order to do this, press Windows Key + PAUSE BREAK to open up the Windows System window and click "Advanced system settings" link on the left hand side of the window.


A new window should appear. From there, click "Environment Variables..." button to open up the Environment Variables window.


From there, you should see "System variables" section. Find the Path variable and concatenate the proper ruby bin path to that semicolon-separated list.


Last step is actually installing the hub. You should grab the standalone file and then rename it to "hub". Then, put it under the Git\bin folder. The full path of my Git\bin folder on my 64x machine is "C:\Program Files (x86)\Git\bin".

Now you should be able to run hub command from Git Bash:


Special GitHub commands you get through hub extension is nicely documented on the "Readme" file of the project. I think the coolest feature of hub is the pull-request feature. On GitHub, You can send pull requests to another repository through GitHub web site or GitHub API and hub extension uses GitHub API under the covers to send pull requests. You can even attach your pull request to an existing issue. For example, the following command sends a pull request to master branch of the tugberkugurlu’s repository from the branch that I am currently on and attaches this to an existing issue #1.

hub pull-request -i 1 -b tugberkugurlu:master

Have fun Winking smile

If you enabled tracing on your ASP.NET Web API application, you may see a dispose issue for IDependencyScope. Here is why and how you can workaround it.
@ 01-12-2013
by Tugberk Ugurlu

ASP.NET Web API has a very cool built-in tracing mechanism. The coolest part about this feature is that none of the tracing code is being run if you don’t enable it. The mechanism makes use of well-known Facade Pattern and if you enable tracing by providing your custom ITraceWriter implementation and don’t replace the default ITraceManager implementation, several ASP.NET Web API components (Message Handlers, Controllers, Filters, Formatters, etc.) will be wrapped up inside their tracer implementations (these are internal classes inside System.Web.Http assembly). You can learn more about tracing from Tracing in ASP.NET Web API article.

ASP.NET Web API also has this concept of carrying disposable objects inside the request properties bag and two objects are added to this disposable list by the framework as shown below (in the same order):

The DisposeRequestResources extension method for the HttpRequestMessage object is invoked by the hosting layer at the end of each request to dispose the registered disposable objects. The invoker is the internal ConvertResponse method of HttpControllerHandler in case of ASP.NET host. The implementation of the DisposeRequestResources extension method is exactly as shown below:

public static void DisposeRequestResources(this HttpRequestMessage request) {

    if (request == null) {
        throw Error.ArgumentNull("request");

    List<IDisposable> resourcesToDispose;
    if (request.Properties.TryGetValue(HttpPropertyKeys.DisposableRequestResourcesKey, out resourcesToDispose)) {
        foreach (IDisposable resource in resourcesToDispose) {
            try {
            catch {
                // ignore exceptions

It iterates through the list and disposes the registered objects one by one. So far so good. However, there is one slightly problem here depending on your ITraceWriter implementation. I’m not sure if it’s fair to call this a bug, but to me, it really is a bug. Let me explain what it is.

As we know, the IDependencyScope implementation and the selected IHttpController implementation for the request are added to the disposables list in order to be disposed at the end of the request. As we also know, if we enable tracing in ASP.NET Web API, several ASP.NET Web API components wrapped inside their tracer implementations. In case of controllers, this is HttpControllerTracer. Since the IHttpController is also disposable, the HttpControllerTracer overrides the Dispose method to write a begin/end trace record for the dispose action. However, the disposable objects are disposed in order and when the controller’s dispose method is called, the dependency scope is already too far gone and if your custom ITraceWriter implementation tries to use the dependency scope, which is bound to that request, you will get an exception there. This doesn’t effect your application that much as this exception is swollen by the underlying infrastructure but this is not good. I wrote a little application to demonstrate this (actually, I went a little far and used a few more things for this *little* application Smile) and show how to workaround it for now. The code for this project is available on GitHub.

I created a custom tracer and registered through the global HttpConfiguration instance. This tracer tries to reach the ILoggerService implementation through the dependency scope. The code for my ITraceWriter implementation is as shown below:

public class WebApiTracer : ITraceWriter {

    public void Trace(
        HttpRequestMessage request, 
        string category, 
        TraceLevel level, 
        Action<TraceRecord> traceAction) {

        if (level != TraceLevel.Off) {

            TraceRecord record = new TraceRecord(request, category, level);

    private void Log(TraceRecord traceRecord) {

        IDependencyScope dependencyScope = 
        ILoggerService loggerService = 
            dependencyScope.GetService(typeof(ILoggerService)) as ILoggerService;
        // Log the trace data here using loggerService
        // Lines omitted for brevity

When we run this application in debug mode and send a request against a valid resource which will eventually go inside the controller pipeline (for this application /api/cars), we will see an exception as below:

1-12-2013 4-41-30 PM

If we are curios enough and decide to dig a little deeper, we will actually see what is causing this exception.

1-12-2013 4-42-58 PM

{"Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."}

   at Autofac.Core.Lifetime.LifetimeScope.CheckNotDisposed()
   at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
   at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType)
   at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType)
   at DependencyScopeTracingDisposeBug.Tracing.WebApiTracer.Log(TraceRecord traceRecord) in e:\Apps\DependencyScopeTracingDisposeBug\Tracing\WebApiTracer.cs:line 25
   at DependencyScopeTracingDisposeBug.Tracing.WebApiTracer.Trace(HttpRequestMessage request, String category, TraceLevel level, Action`1 traceAction) in e:\Apps\DependencyScopeTracingDisposeBug\Tracing\WebApiTracer.cs:line 18
   at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
   at System.Web.Http.Tracing.Tracers.HttpControllerTracer.System.IDisposable.Dispose()
   at System.Net.Http.HttpRequestMessageExtensions.DisposeRequestResources(HttpRequestMessage request)

It wasn’t hard to diagnose the problem and the question was how to workaround it for now as the issue is caused by a code which is deep inside the bowel of the hosting layer. There are several workarounds for this problem which I can come up with quickly such as replacing the HttpControllerTracer but the one I applied was very dirty: adding a message handler as the first message handler (so that it runs last (just in case)) and reordering the disposables on the way out. Here is the message handler which performs this operation:

public class DisposableRequestResourcesReorderHandler : DelegatingHandler {

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken) {

        return base.SendAsync(request, cancellationToken).Finally(() => {

            List<IDisposable> disposableResources = 
                request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey] as List<IDisposable>;
            if (disposableResources != null && disposableResources.Count > 1) {

                // 1-) Get the first one (which I know is AutofacWebApiDependencyScope).
                // 2-) Remove it from the list.
                // 3-) Push it at the end of the list.

                IDisposable dependencyScope = disposableResources[0];
        }, runSynchronously: true);

Notice that I used an extension method for Task object called Finally. This is a method which you can get by installing the TaskHelpers NuGet package. This allows you to run the continuation no matter what the status of the completed Task. Finally method will also propagate the proper Task back to the caller, which is kind of nice and clean in our case here as we want to run this code no matter what the status of the Task is.

When you run the application after registering this message handler, you will see the controller’s dispose trace record being logged successfully.

1-12-2013 7-35-21 PM

If you believe this is a bug and should be fixed, please vote for this issue:

With the new release of the GenericRepository.EntityFramework package, we now have clean, better and sexier generic repository implementation for Entity Framework. Enjoy!
@ 01-10-2013
by Tugberk Ugurlu

I have written a few blog posts about my experience on applying the Generic Repository pattern to Entity Framework and I even made a NuGet package for my naïve implementation. Even if that looked OK at the time for me, I had troubles about my implementation for couple of reasons:

  • The implementations inside the NuGet package didn’t allow the developer to share the DbContext instance between repositories (per-request for example).
  • When the generic repository methods weren’t enough, I was creating new repository interfaces and classes based on the generic ones. This was the biggest failure for me and didn’t scale very well as you can imagine.
  • There were no pagination support.
  • As each repository take a direct dependency on DbContext and it is impossible to entirely fake the DbContext, generic repositories needed to be mocked so that we could test with them. However, it would be just very useful to pass a fake DbContext instance into the repository implementation itself and use it as fake.

With the new release of the GenericRepository.EntityFramework package, the all of the above problems have their solutions. The source code for this release is available under the master branch of the repository and you can also see the ongoing work for the final release under the v0.3.0 branch. The NuGet package is available as pre-release for now. So, you need to use the –pre switch to install it.

PM> Install-Package GenericRepository.EntityFramework -Pre

The old GenericRepository.EF package is still around and I will update it, too but it’s now unlisted and only thing it does is to install the GenericRepository.EntityFramework package.

I also included a sample application which shows the usage briefly. I will complete the sample and extend it further for a better view. Definitely check this out!

Let’s dive right in and see what is new and cool.

IEntity and IEntity<TId> Interfaces

I introduced two new interfaces: IEntity and IEntity<TId> and each of your entity classes needs to implement one of these. As you can see from the implementation, IEntity just implements the IEntity<int> and you can use IEntity if you are using integer based Ids. The reason why I added these is make the GetSingle method work.

Use EntitiesContext Instead of DbContext

Instead of deriving your context class from DbContext, you now need to take the EntitiesContext as the base class for your context. If you have an existing context class based on DbContext, changing it to use EntitiesContext should not break it. The EntitiesContext class has all the same constructors as DbContext. So, you can also use those. Here is the sample:

public class AccommodationEntities : EntitiesContext {

    // NOTE: You have the same constructors as the DbContext here. E.g:
    // public AccommodationEntities() : base("nameOrConnectionString") { }

    public IDbSet<Country> Countries { get; set; }
    public IDbSet<Resort> Resorts { get; set; }
    public IDbSet<Hotel> Hotels { get; set; }

Then, through your IoC container, you can register your context as a new instance for IEntitiesContext per a particular scope. The below example uses Autofac to do that for an ASP.NET Web API application:

private static void RegisterDependencies(HttpConfiguration config) {

    var builder = new ContainerBuilder();

    // Register IEntitiesContext
    builder.Register(_ => new AccommodationEntities())

    // TODO: Register repositories here

    config.DependencyResolver = 
        new AutofacWebApiDependencyResolver(builder.Build());

IEntityRepository<TEntity> and EntityRepository<TEntity>

Here is the real meat of the package: IEntityRepository and EntityRepository. Same as the IEntity and IEntity<TId>, we have two different IEntityRepository generic interfaces: IEntityRepository<TEntity> and IEntityRepository<TEntity, TId>. They have their implementations under the same generic signature: EntityRepository<TEntity> and EntityRepository<TEntity, TId>. The big improvement now is that EntityRepository generic repository implementation accepts an IEntitiesContext implementation through its constructor. This, for example, enables you to use the same DbContext (IEntitiesContext implementation in our case, which is EntitiesContext by default) instance per-request for your ASP.NET MVC, ASP.NET Web API application and share that across your repositories. Note: don’t ever use singleton DbContext instance throughout your AppDomain. DbContext is not thread safe.

As we have registered our EntitiesContext instance per request above, we can now register the repositories as well. As our repositories accepts an IEntitiesContext implementation through their constructor, our IoC container will use our previous registration for that automatically. Autofac has this ability as nearly all IoC containers do.

private static void RegisterDependencies(HttpConfiguration config) {

    var builder = new ContainerBuilder();

    // Register IEntitiesContext
    builder.Register(_ => new AccommodationEntities())

    // TODO: Register repositories here

    config.DependencyResolver = 
        new AutofacWebApiDependencyResolver(builder.Build());

Out of the Box Pagination Support

Best feature with this release is out of the box pagination support with generic repository instances. It doesn’t perform the pagination in-memory; it queries the database accordingly and gets only the parts which are needed which is the whole point Smile Here is an ASP.NET Web API controller which uses the pagination support comes with the EntityRepository:

public class CountriesController : ApiController {

    private readonly IEntityRepository<Country> _countryRepository;
    private readonly IMappingEngine _mapper;
    public CountriesController(
        IEntityRepository<Country> countryRepository, 
        IMappingEngine mapper) {

        _countryRepository = countryRepository;
        _mapper = mapper;

    // GET api/countries?pageindex=1&pagesize=5
    public PaginatedDto<CountryDto> GetCountries(int pageIndex, int pageSize) {

        PaginatedList<Country> countries = 
             _countryRepository.Paginate(pageIndex, pageSize);

        PaginatedDto<CountryDto> countryPaginatedDto = 
           _mapper.Map<PaginatedList<Country>, PaginatedDto<CountryDto>>(countries);

        return countryPaginatedDto;

public interface IPaginatedDto<out TDto> where TDto : IDto {

    int PageIndex { get; set; }
    int PageSize { get; set; }
    int TotalCount { get; set; }
    int TotalPageCount { get; set; }

    bool HasNextPage { get; set; }
    bool HasPreviousPage { get; set; }

    IEnumerable<TDto> Items { get; }

public class PaginatedDto<TDto> : IPaginatedDto<TDto> where TDto : IDto {

    public int PageIndex { get; set; }
    public int PageSize { get; set; }
    public int TotalCount { get; set; }
    public int TotalPageCount { get; set; }

    public bool HasNextPage { get; set; }
    public bool HasPreviousPage { get; set; }

    public IEnumerable<TDto> Items { get; set; }

Paginate method will return us the PaginatedList<TEntity> object back and we can project that into our own Dto object as you can see above. I used AutoMapper for that. If I send a request to this API endpoint and ask for response in JSON format, I get back the below result:

        "Name":"United Kingdom",

Isn’t this perfect Smile There are other pagination method inside the EntityRepository implementation which supports including child or parent entities and sorting. You also have the ToPaginatedList extension method and you can build your query and call ToPaginatedList on that query to get PaginatedList<TEntity> object back.

Extending the IEntityRepository<TEntity>

In my previous blog posts, I kind of sucked at extending the generic repository. So, I wanted to show here the better approach that I have been taking for a while now. This is not a feature of my generic repository, this is the feature of .NET itself: extension methods! If you need extra methods for your specific repository, you can always extend the IEntityRepository<TEntity, TId> which gives you a better way to extend your repositories. Here is an example:

public static class HotelRepositoryExtensions {

    public static IQueryable<Hotel> GetAllByResortId(
        this IEntityRepository<Hotel, int> hotelRepository, int resortId) {

        return hotelRepository.FindBy(x => x.ResortId == resortId);

What is Next?

My first intention is finish writing all the tests for the whole project, fix bugs and inconsistencies for the v0.3.0 release. After that release, I will work on EF6 version for my generic repository implementation which will have sweet asynchronous support. I also plan to release a generic repository implementation for MongoDB.

Stay tuned, install the package, play with it and give feedback Winking smile

This weekend, I participated in an event as a speaker in Izmir, DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi. Sides and Source Code for my sessions are available.
@ 01-08-2013
by Tugberk Ugurlu

This weekend, I participated in an event as a speaker in Izmir. I also had the chance to meet Fatih Boy, İkay İlknur, Umut Erkal and Oğuzhan Yılmaz at the event. There were great sessions throughout the first and second day.



I gave two talks during the event and one of them was on Git and GitHub. You can see the slides for that session below:

At the second day, I talked about asynchronous programming for .NET server applications. Slides for that session is also available on my SpeakerDeck page. You can also get the source code for the demos:

I decided to dedicate this part of my life to JavaScript for a while and I will write my experience on JavaScript-heavy, maintainable web Applications as a n00b.
@ 01-08-2013
by Tugberk Ugurlu

Nearly every software developer dedicates a part of its time to improve him/herself on a particular area of expertise. Well, I dedicate this part of my life to JavaScript for a while. I have been writing JavaScript for approx. 3 years now but if anybody asks me if I know JavaScript, I tell them that I know JavaScript and I *don’t* know JavaScript at the same time. It’s probably because of the fact that I don’t get to work with it that much. One of the places I struggle most is the idea of maintaining big-ass JavaScript heavy web applications. That idea has been causing me to carry a psychic weight but now, at this very moment, I am committed to throw it away like a piece of garbage! And yes, it starts with a blog post Smile

A few months ago I talked to a brilliant developer about node.js, the platform built on Chrome's JavaScript runtime (V8) for easily building fast, scalable network applications, and asked his opinion about it. He was uncertain at the time but apparently he had more information about node.js than me. So, I expressed that I didn’t understand the need of JavaScript at the server side because it’s hard to maintain such a huge JS codebase. Then, he slapped me in the face with a follow-up sentence: "Well, the node community thinks that a big application codebase needs to be separated into small modules, components to be more maintainable". That was the nudge I needed to believe that the JavaScript codebase can be maintained.

Not long time later from that moment, I then started watching John Papa’s Single Page Apps with HTML5, Web API, Knockout and jQuery and I learnt lots of mind blowing stuff about JavaScript: new (at least new to me) libraries, well-known JavaScript patterns, which I had been aware of but didn’t know how to apply them most of the time, and many more. This was the start of my commitment to learn JavaScript (I mean really learning, going beyond the for loops and if statements) and I pulled out my JavaScript: The Good Parts book which I have bought in last June, but I thought that the best way to learn this stuff is to blog about it. So, here I am Winking smile In this post I am listing a few JavaScript libraries which make a lot of sense to be used in nearly every web applications. I have been working with some of this libraries for a while now and I am going to be working with some of those.

JQuery: The JavaScript framework we all know and fell in love at the time that we have noticed it. JQuery is especially helpful for DOM manipulation and Ajax interactions. If you don’t want to install JQuery, don’t worry; you eventually will have to because I am sure that at least of the libraries you are going to use will have a dependency on it.

KnockoutJS: KnockoutJS is one of the best things that can happen to a web developer. Starting to learn KnockoutJS gives you the equivalent feeling which you would feel at the very moment when you find a cup of hot chocolate in a freezing cold day. It enables your to have two way data-binding between your DOM elements and your view model which means when your data model's state changes, your UI updates automatically and vice versa. Check out its well-arranged documents and live tutorials.

Underscore.js: Underscore.js provides a utility suite which covers lots of useful functions. From the its official page: "Underscore provides 80-odd functions that support both the usual functional suspects:map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map,reduce, filter, every, some and indexOf". Don’t forget to watch this awesome presentation from Elijah Manor on Underscore.js.

RequireJS: I think RequireJS is the essential piece of library which makes it possible to have maintainable, well-designed JavaScript codebase. It’s a modular script loader which enables you to write small pieces of code in separate files and handle their dependencies and load order correctly. RequireJS also has a very nice documentation in its web site; definitely check that out.

Sammy.js: Last library I am considering for my every web application is Sammy.js. It gives us a nice way to handle page navigations without refreshing the page at all by providing a nice routing mechanism. Especially, if you are writing a Single Page Applications (SPA), this is the library that you want inside your suite. Don’t skip to check out its intro sample.

There are for sure other great libraries out there (e.g. Moment.js, AmplifyJS, JQuery UI, Breeze) but these are the ones I am in love at the moment. Go check them out and start exploring Winking smile

Hi πŸ™‹πŸ»β€β™‚οΈ I'm Tugberk Ugurlu.
Coder πŸ‘¨πŸ»β€πŸ’», Speaker πŸ—£, Author πŸ“š, Microsoft MVP πŸ•Έ, Blogger πŸ’», Software Engineering at Deliveroo πŸ•πŸœπŸŒ―, F1 fan πŸŽπŸš€, Loves travelling πŸ›«πŸ›¬
Lives in Cambridge, UK 🏑