Category Archives: .NET

everything about .net

.NET Coding

Download large files with Web Api as a relay

Published by:

Consider the following scenario: you have a file storage in the cloud (google docs, openstack object storage etc.) and you need to provide your app consumers a way to download the files through your app. The challenges here are mainly memory related – if you get files in memory and then return them in the response, your app will soon be crushed with OutOfmemory Exception. So you need a way to turn your app into a relay which is kind of a pipe through which bytes flow from the file storage to the client without buffering any of the content. I guess you are already thinking streams and you are right.

Change the buffer policy

Web api by default will try to buffer the content that you are trying to download and that needs to be changed. You will need to be inherit from IHostBufferPolicySelector  or inherit from the only implementor of this interface (WebHostBufferPolicySelector) and override its methods :


public class WebHostBufferPolicySelector : IHostBufferPolicySelector
    public virtual bool UseBufferedInputStream(object hostContext);
    public virtual bool UseBufferedOutputStream(HttpResponseMessage response);

You will also need to override one of the two methods, depending if you want unbuffered content for download or upload. In our case we need UseBufferedOutputStream. A possible implementation would be:

public class NoBufferPolicy : WebHostBufferPolicySelector
        public override bool UseBufferedOutputStream(HttpResponseMessage response)
            if (response.RequestMessage.RequestUri.LocalPath.Contains("download"))
                return false;

            return base.UseBufferedOutputStream(response);

So now we use not buffered content when anybody hits a route that contains download and buffered for any other case. After we have done that we need to register our class in GlobalConfiguration:

 GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicy());

Back to the controller

In the usual case the code in your controller should be something like:


var client = new HttpClient();
var responseWithHeadersOnly = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

Two things are worth mentioning here – the second parameter of the GetAsync method – HttpCompletionOption.ResponseHeadersRead which basically reads only the headers of the response and not the content. The second thing is the ConfigureAwait(false) which has to do with how async and await play in a web app.

Here is the time to check if the response is ok. Once we have the response, we need to get hold of the content stream without putting it in memory:

Stream streamToReadFrom = await responseWithHeadersOnly.Content.ReadAsStreamAsync();

After we get the headers, make sure that everything is ok (no service unavailable, server errors etc.) and have control over the stream it is time to start streaming to the client. We will use a push approach in this case, contrary to the traditional pull. Luckily web api gives us the tools for that – we will use the PushStreamContent object for our response content. What it does is that it reads from a stream and pushes the bytes to the client chunk-wise. It has a couple of overloads but it basically uses a function that takes a Stream, HttpContext and TransportContext as params and may return void or a Task. Let’s see some code:

 var client = new HttpClient();
var streamToReadFrom = await client.GetAsync(requestUrl, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

                var buffer = new byte[65536];
                var result = Request.CreateResponse();
                int bytesRead = 0;

                result.Content = new PushStreamContent((stream, content, context) =>
                    while ((bytesRead = streamToReadFrom.Read(buffer, 0, buffer.Length)) > 0)
                        stream.Write(buffer, 0, bytesRead);


                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentDisposition.FileName = filename;
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                return result;

Every time you go through the while loop, you read bytes from the incoming stream and pass them to the outgoing stream.

The flow here is as follows – a request comes in (1), you read the headers of the requested file from the file storage provider (2), return response from the method (return result; line (3)), file starts to download (stream.Write(buffer, 0, bytesRead); (4)), file is done downloading (stream.Close(); (5)). The whole thing ends when you close the outgoing stream and not when you return from the method.

That should be all to turn your web api in a working and scalable file download relay. You can find the source code HERE under the LargeFilesWebApi folder


Async/Await done right in the context of a web app

Published by:

Since .NET 4.5 we are provided with a handy way for async programming through the await-async operators. However, i feel that these are widely misunderstood as looking at peer’s code.

First things first – what are async-await good for in a web app?

Making your IO bound or computational intensive methods async, makes your app much more scalable. It releases the thread to do any other work (most often serving requests) instead of waiting for computations and IO read/write. If your server can handle 100 people synchronously, it should be ok with at least double that if you use async methods (rule of thumb – depends on many things).

What is a bad idea to use async-await?

If i make a request and that triggers a very slow job, i will be waiting a heck lot of a time until the job is done and the response returned no matter if i use synchronous or asynchronous methods. The benefit of async methods is not that they return fast (you have to await them at the end of the day) but the fact that they utilize threads until doing slow jobs. So response time should be the same but in the mean time the released thread could have server another request before continuing the first job after the await. So if is about utilizing resources and not returning immediately. If you want to return a result to the client immediately and do a job in the background that is a whole new topic. For example, when you make a request to open stack to provision a virtual machine, you get 201 Created immediately, no matter that it takes 10 minutes to provision it. So that is definitely not async-await pattern but rather background workers, queues etc.

Good practice

If you decide to implement async methods go all the way – don’t mix up synchronous and asynchronous code. This may cause deadlock very often. The code below is a deadlock:

public IHttpActionResult Files()
    var resultFromLongComputation = this.TestAsync().Result;
    return Ok(resultFromLongComputation);

public async Task<int> TestAsync()
    await Task.Delay(2000);
    return 42;

So we have an async method where we await a long job. When hitting the await line we return immediately in the Files method where we synchronously start to wait for the result from the TestAsync method (the .Result forces the waiting for a Task to complete in synchronous mode). The thread and the related context hang. When the Delay elapses, the TestAsync method wants to get hold of the previous bound context so that it finishes its work and returns a result. However, that context is being blocked by the Files method (it is in a synchronous wait).

How to prevent it?
  1. One way would be to use
public IHttpActionResult Files()
    var resultFromLongComputation = await this.TestAsync();
    return Ok(resultFromLongComputation);
  2. Another way is to set the ConfigureAwait to false which prevents the method for waiting for the same context to be available. It will grab a thread pool thread instead.
public async Task TestAsync()
    await Task.Delay(2000).ConfigureAwait(false);
    return 42;

The deadlock is valid for UI apps also (Win forms and WPF) but not for console apps (async in a console app is not bound to the request context or the ui context but just grabs a thread pool thread). So if you have a testing console that is very confusing.

Some words on the Synchronization Context

The default behavior of awaiting a task is to capture the current Synchronization Context and when the task is finished to try to post the invocation of the continuation delegate (compiler generated code that wraps the stuff after the await) on the same Synchronization Context. Synchronization Context will be null in a console app and will be not null in a UI or Web App. So that’s why all the hassle with the contexts and mixing up synchronous and asynchronous code.

Further Reading:

Stephen Cleary intro to async-await

Async/Await FAQ in the pfxteam team msdn blog 



Published by:

app_offline.htm is an old feature of ASP.NET that i recently found and find quite useful. If you put an app_offline.htm file in the root of your .net hosted site (yeah, simple as that), ASP.NET will shut down your site unload it form the app domain and stop serving any incoming requests. Instead it will start serving the content of the app_offline.htm file. That comes quite handy of your site is “Under Construction” or you make any major changes.




.NET Coding is live

Published by:

Just released one of my projects live – the portal for Sofia High School of Mathematics’ alumni . I developped that as an open source projects and it can be found on github. The project is built for Sofia High School of Mathematics but can be used for any other school or university with minimal effort for customization.

Technological stack is MSSQL on the server side with Entity Framework as ORM, ASP.NET Web Api on the back-end and AngularJS on the front-end. The portal is feature rich and features user, amdin and super admin functionality. Superadmin may edit system settings and assign roles through the ui. Admin creates news, fundraising campaigns, resets user passwords and verifies registered users (this may be used or not). On the user part, there is a section for news, fundraising campaigns, search (by year and class division so far) , forum and account management. Most pages are available for not logged in users, except the search, the account management and in the cases when you want to create content in the forum.

Account management features account edit, forgot password and change password.

The solution is a perfect fit for shared hosting – recurring services are implemented as jobs instead of windows services. This particular site runs on shared ASP.NET hosting from ICN for about 50E per year, which is quite a deal in my opinion. Special thanks to SMG’s Director – Mr. Stoyanov for covering the first year’s expenses.

I believe that every school/uni needs alumni network site where alumni can keep in touch, help themselves, help current students and also help the school or uni.

Feel free to fork the repository and use the project freely wherever you want. If you need any assistance don’t hesitate to PM me.

.NET Coding

A really good pdf library for .net

Published by:

If you are into Web apps development you will probably face at least once the problem to export web content to pdf. And if it is the first time you face that problem, things get scary. You usually face a few options:

– commercial and expensive library
– the almighty wkhtmltopdf tool (built on top of WebKit rendering engine) but you have to run the executable from your .net app which makes deployment more complex
– a .net wrapper library of the wkhtmltopdf tool

The third one is definitely the winning option as the tool is really powerful and free. Which wrapper though? Some of them don’t work in some cases and docs are poor. After an extensive research i found this one called NReco PDF Generator for .NET to be the best and render everything you might need (html of course, but also svg, custom fonts etc.) in one liner. The library is free but for 30$ you can get some support and code samples and for 100$ you can get all future updates plus component’s source if you want. As i said it works perfect outside of the box and chances are you wont need samples and support unless you render something very special. It the most basic scenario, you need only

var converter = new HtmlToPdfConverter();
var result = converter.GeneratePdf(html);

where html is… right, your html that you want to export. If you need any customization you may find useful to use:

converter.PageFooterHtml="your html as string goes here"


converter.PageHeaderHtml="your html as string goes here"

If you want some more granular control you may use :


property which takes native to the wkhtmltopdf tool arguments as a string so if you need page numbers in the footer you may type in:

converter.CustomWkHtmlPageArgs ="--footer-right [page]/[topage] --footer-font-size 8";

I saved the best for last – it is available through NuGet and has no dependencies so installation is one-click away and makes a deployment as consistent as it can get. So to wrap up , good job guys for that library. It is very rare to find something free to work so well outside of the box.


Manage your passwords

Published by:

In modern world one of the huge challenges – at least for me is managing my passwords for the various sites that i use.

The challenge is further enhanced by:

– your passwords need to be super strong so that they withstand hackers. Passwords are usually stored as hashes and not strings on the server so hackers use brute force guessing mechanisms to get you password as a string if those passwords get stolen. So using password as RgGZ5DOynJ5*dd*TsrAXEz will make them reluctant to crack it as for the same time they will crack 1000 passwords as password123.
– you need to change your passwords often enough so that be secured (i use 2-3 months time-intervals)
– you need to use unique password for every site you use. One of the biggest mistakes in terms of security is to make up a super strong password, use it all over the place and not change it for years.

So, either you have to have a very smart way to make up and remember passwords or you need to use a tool. I have decided for myself to use the second. But i couldn’t come up with a free tool that i could trust enough so i decided to make up one for myself.

Here is how it looks:



This is a simple winforms app and uses the built in System.Security.Cryptography methods to leverage the asymmetric cryptography method of encryption.

With this simple app you can:

– Generate public/private key pairs
– Generate random password for you
– Encrypt passwords as string with the public key
– Decrypt encrypted passwords in string format with the private key

So you may generate strong password and keep their encrypted representation in a simple .txt file if you want to and decrypt them when needed with the private key:

encrypted password

You don’t really need to worry about that txt as everything in it is encrypted and if passwords are strong enough, it will require huge amount of effort to brute force crack them. That does not mean that you have to be negligible though. The single thing that you have to worry about is the PRIVATE KEY – that is the single most vulnerable point here so keep that the best way you can. If you thing that the private key has been compromised, just create another pair public-private key and run your passwords through those.

You can find the source of the app here -> and build it for yourself. If you are out of the .NET world drop me a pm and i will send you the exe.

Disclaimer – i haven’t refactored the code so please don’t be that critical on the source quality 🙂

.NET Coding

Dynamic objects in C#

Published by:

I know that it is not what strongly typed language is supposed to support but sometimes we need to add properties on the fly as in JavaScript. Here are two alternative ways to do that:

One way is to use the ExpandoObject that is being shipped in System.Dynamic. We can add properties (of any type) on the fly and to consume them afterwards. Consider the following example:

        dynamic dynamicObject = new ExpandoObject();
        dynamicObject.myCat = cat;
        dynamicObject.myCar = car;
        dynamicObject.justAString = "I am just a string";
        dynamicObject.justAnInteger = 42;

If we try to consume a property that is not present we get an exception. No need to say that you have to say good bye to intellisense.

The second way is to implement a class with an indexer and an underlying dictionary as the data store. You can add properties on the fly with a slightly different syntaxis. Consider the following example:

public class ViewBag
    public ViewBag()
        dict = new Dictionary();

    private Dictionary dict;

    public object this[string index]
            object val=null;
            dict.TryGetValue(index,out val);
            return val;
            if (dict.ContainsKey(index))
                throw new Exception();

and that is how we add properties

        var viewBag = new ViewBag();
        viewBag["mycar"] = car;
        viewBag["myCat"] = cat;
        viewBag["justAString"] = "I am just a string";
        viewBag["justAnInteger"] = 42;

I have named it viewBag purposefully because the actual MVC ViewBag is built this way.

I must admit that it is mainly border scenarios where you might need those but you never know.

.NET Coding

Construct Dynamic Filters with C#

Published by:

Filtering data with C# is pretty straight-forward when using LINQ – you get results with one-liners as

var result=cars.Where(a=>a.carMake=="Fiat" && a.speed>100);

However, we know the filtering properties (carMake and speed) and the filtering conditions (equals with carMake and greater than with speed) in advance. The more interesting case, however, is when we don’t know the filtering properties, their number and the filtering criteria in advance but have to construct them in real time. Consider the case when you have data objects with many properties and allow the user on the front end to filter it according to his/her needs. In this case Dynamic Expression Construction comes to rescue.
LINQ extension methods work with predicates (or anonymous functions). Fortunately, C# provides very powerful api to build Expression trees, which can be compiled to predicates in runtime and passed to the LINQ extension methods afterwards.
Let’s see an example. Suppose that we have a list of cars and we want to filter them dynamically for whatever purpose – here is our Car object

public class Car
        public string Model { get; set; }
        public string Make { get; set; }
        public string CountryOfOrigin { get; set; }
        public string CountryOfProduction { get; set; }

        public int MaxMilesPerHour { get; set; }
        public int NumberOfSeats { get; set; }
        public int MilesPerGallon { get; set; }
        public double WeightInKg { get; set; }

        public decimal BasePrice { get; set; }
        public decimal FullPrice { get; set; }

With 10 properties, we can filter a collection of cars in many possible ways.
Next we need a class that would represent a filter – so we need a property name for comparison, value to be compared to and operation (equal, less than etc). Let’s call it ExpressionFilter

public class ExpressionFilter
        public string PropertyName { get; set; }
        public object Value { get; set; }
        public Comparison Comparison{ get; set; }

Comparison is nothing more than a enum with possible operations

public enum Comparison
        Contains, //for strings
        StartsWith, //for strings
        EndsWith //for strings

Next comes the real thing – we need a class which can take a list of ExpressionFilters, do its thing and return an Expression tree composed of these filters, which we can use as a parameter in any LINQ extension method after compiling it. Let’s have a class that constructs And expression trees. We will call it ConstructAndExpressionTree

public static Expression<Func<T, bool>> ConstructAndExpressionTree<T&gt(List<ExpressionFilter> filters)
            if (filters.Count == 0)
                return null;

            ParameterExpression param = Expression.Parameter(typeof(T), "t");
            Expression exp = null;

            if (filters.Count == 1)
                exp = ExpressionRetriever.GetExpression<T>(param, filters[0]);
                exp = ExpressionRetriever.GetExpression<T>(param, filters[0]);
                for (int i = 1; i < filters.Count; i++)
                    exp = Expression.And(exp, ExpressionRetriever.GetExpression<T>(param, filters[i]));

            return Expression.Lambda<Func<T, bool>>(exp, param);

The class is generic so it can be used with any type. The code is pretty straight-forward -> we start with the ParameterExpression which is the t=> part of the predicate. Then we iterate through the filters and start building the actual expression called exp here. You probably notice that we use a helper method ExpressionRetriever.GetExpression to construct the separate expressions (like a.speed>100), which we stick with Or binary operator aferwards. Here is the code of ExpressionRetriever.GetExpression:

public static class ExpressionRetriever
        private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
        private static MethodInfo startsWithMethod = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
        private static MethodInfo endsWithMethod = typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });

        public static Expression GetExpression<T>(ParameterExpression param, ExpressionFilter filter)
            MemberExpression member = Expression.Property(param, filter.PropertyName);
            ConstantExpression constant = Expression.Constant(filter.Value);
            switch (filter.Comparison)
                case Comparison.Equal:
                    return Expression.Equal(member, constant);
                case Comparison.GreaterThan:
                    return Expression.GreaterThan(member, constant);
                case Comparison.GreaterThanOrEqual:
                    return Expression.GreaterThanOrEqual(member, constant);
                case Comparison.LessThan:
                    return Expression.LessThan(member, constant);
                case Comparison.LessThanOrEqual:
                    return Expression.LessThanOrEqual(member, constant);
                case Comparison.NotEqual:
                    return Expression.NotEqual(member, constant);
                case Comparison.Contains:
                    return Expression.Call(member, containsMethod, constant);
                case Comparison.StartsWith:
                    return Expression.Call(member, startsWithMethod, constant);
                case Comparison.EndsWith:
                    return Expression.Call(member, endsWithMethod, constant);
                    return null;

Expression class provides methods for the standard operations as equal, not equal, less than etc. but notice also the last three cases where we use Expression.Call to call the string methods Contains, StartsWith and EndsWith. Here lies a big potential for extension as you can use whatever methods you like defined on any type. You only should get their MethodInfo through reflection.
So sticking it all together (i skip the part where i populate the cars collection):

      static void Main(string[] args)
            var filters = new List<ExpressionFilter> 
                new ExpressionFilter
                new ExpressionFilter

            var expressionTree= ExpressionBuilderHelper.ExpressionBuilder.ConstructAndExpressionTree<Car>(filters);
            var anonymousFunc = expressionTree.Compile();
            var result = cars.Where(anonymousFunc);

You can see that the result is a car that has MaxMilesPerHour>190 and CountryOfOrigin that starts with ‘Fr’


Variance and Contravariance in C# generics

Published by:

No, it is not a mistake – you didn’t landed on a math blog although the terms in the title sound more math than IT. However, variance and contravariance are terms deeply rooted in C# since version 4.

The simplest way to think about those is that variance preserves the direction (from less derived object to more derived on – i.e. object->string) while contravariance reverses it. Variance is somewhat intuitive as it coincides with assignment compatibility. It is natural to make something as Object a = “test string”.

If you examine IEnumerable interface in the .net dlls, you will find out that it’s signature is IEnumerable (we denote variant generics with out and contravariant with in) and it means that the interface works with generic types that behave variant. So that if we have SomeMethod(IEnumerable items) we can pass it parameter as IEnumerable items and that’s very logical because if we can enumerate and manipulate the less derived type it is safe to go through and manipulate the more derived type.

I personally find contravariance way more challenging. I wont try to explain it but rather show an example which is very self-explanatory:

 public class Animal
        public void SayYourType()

    public class Human : Animal


So far so good – we have a class Human to derive from Animal. They do nothing more than say their types so that we can keep things simple

    public interface ICallType<in T>
        void CallType(T x);

    public class AnimalTypeCaller : ICallType<Animal>
        public void CallType(Animal x)

    public class TypeDiscoverer<T>
        T Item;
        ICallType<T> TypeCaller;

        public TypeDiscoverer(T item, ICallType<T> typeCaller)
            Item = item;
            TypeCaller = typeCaller;

        public void DiscoverType()

lets have an interface that works with generics and exposes only one method that is able to call the type (Note the in keyword). Let’s also have a concrete implementation – the AnimalTypeCaller that inherits from ICallType and works with objects of type Animal. Finally we have a class that works with generics, takes a generic item argument and ICallType interface and is able to call the type of the underlying item using concrete implementation of the interface ICallType.

The magic lies in the next two lines though:

var humanTypeDiscoverer = new TypeDiscoverer<Human>(human,new AnimalTypeCaller());

we declare humanTypeDiscoverer that works with Human object but pass it AnimalTypeCaller, so we reverse the direction- > we handle more derived types(Human) with handler that works with less derived types (Animal). Even the intellisense will hint you that it expects ICallType of type Human but because of the contravariance and the in keyword, the above code is perfectly legal and works as expected and we can treat Humans with AnimalTypeCaller 🙂

This pattern is used with handlers and most notably comparers. IComparer is implemented this way. And if you think about it, it makes sense – it is ok to compare integers with an object comparer, but comparing objects with int comparer would be strange.

I suggest you to make yourself a little proof of concept if you still have difficulty to grasp the idea. I spent a lot of time reading on the topic but it took me only 15 minutes to make my own example. 10 lines of code say much more than pages of text. And are more interesting to read 🙂


Change MVC project name in VS

Published by:

Changing the MVC project name in VS is not a standard procedure as hitting F2 and typing the new name. Here are the steps to change the name:

– Click on the project name, hit F2 and rename the project

Go to project properties (right click the project and select Properties). Then under the Application tab change the Assembly name and the Default Namespace

– Go to any class in the project and select the namespace (that should be the old project’s name). Right-click it and select -> Refactor -> Rename and type in the new name. That should change the namespace for the project.

– Change the project folder’s name

Open the .sln with a text editor and manually change the project’s name

– Finally (that’s tricky) go to views folder, locate the web.config there and edit the namespace in the file