Category Archives: Coding

coding snippets, tutorials, practice

Coding

Ev(i|a)l code

Published by:

It has been a while since i last saw someone eval code coming from a remote source. I thought that technique is considered evil across the board but i am wrong, many people like it. So i decided to join the cohort of people that preach the perilous use of it.

The context

I have been doing Demandware (Salesforce commerce cloud or SFCC now) for quite some time. They have this custom script built on top of JS called demandware script (.DS). Being a dynamic language, evaling is quite easy as you may guess and a lot of people are tricked into it.

So what was the use case?

In the context of SFCC, you do a lot of object exporting so that you integrate with 3rd party systems. Some integrations take variable count of fields and the customer is the one to decide which fields to export. So how can we give the customer the freedom to decide what to export without going through the hefty procedure of a code change? Eureka! Let them write a bit of a well documented code that we eval and that’s how we construct our exports. If they want an extra field exported, they write an extra line of code that calls some API (either ours or SFCC) that does the magic and the export is ready, brand new and shiny without a single minute of developer time wasted. Customer writing code is as flexible as we get.

La la land

I guess, you buy the flexibility argument until the future you (or someone else) has to deal with the consequences. So why all the grunt:

  • Even though the customer (or whoever that may be) has the flexibility to write code that you execute for her, chances are she will never do that but will come and ask how to do this and that. Say good buy to flexibility.
  • You stop being owner of your code. When someone starts writing code that you eval, you are pretty much opening an API. A vast API. Have you considered the consequences of opening pretty much your whole system as API? Chances are you haven’t. First, you have to be very careful what you eval. Second, say hi to legacy. Forever. You can’t just change code that is being used by external sources. Third, you have to keep a very detailed documentation of who uses your code and how so that you may asses the impact of every code change. The team should be very well aligned with that. And fourth and fifth etc. Not being owner of your code is not cool.
  • Your code stops being greppable and that is very evil. Your code should be absolutely greppable. I have had the unfortunate moment to delete a function that no one uses only to find out later that a ton of stuff is broken because this function is actually used by some external code.
  • Security. Won’t delve here, this is self explanatory.

Is there a valid use case of evaling? It is there for some reason, right?

Yes, of course. I think evaling has some valid use cases and here is my criteria:

  • You should do very simple operations with evaling. Really simple.
  • You should touch as little as you can from the underlying system.
  • You should verify what you eval. Might be a regex, might be something else but you should have a very strict criteria what you eval.

I have done it only once and that’s my use case:

I was doing an application where you could draw windows (like real world windows that you have in your homes) and calculate prices. All that was done client side in the browser in a canvas. So at the end, you have the picture of your window plus the javascript artefacts associated with it. For every window you had the perimeter, area and a bunch of other properties calculated (number of glass panes, area of glass panes etc). However, to come up with a price you should apply a formula. That’s where eval fitted. I gave the customer the possibility to write stuff like that in a text field that i evalled against the constructed window objects:

  •  T + S * 20 (total price calculated by the system + 20 euro per sq. m.)
  • T * 1.2 (20% markup across the board of the total price)
  • T + S * 20 + P * 10 (total price + 20 euro per sq. m. + 10 euro per meter of the perimeter)
  • T + 50 (total price + 50 euro flat per item manufactured)
  • T + GN * 10 (total price + 10 euro per glass pane markup)

You get the point, every merchant does his own way of pricing and that varies a lot. However, all of the pricing formulas are very simple operations and use very limited API (area, perimeter and a couple of more properties of the window). Using a very limited API and doing only arithmetics, there is a very easy way to validate what gets evalled (like with a regex). There is also only one way to calculate area, perimeter and stuff like that in the context of geometrical shape, so you are not stuck with legacy. This code has no reason to change anyways.

TL;DR Don’t do it, unless you have a very concrete use case, open very limited API and can control what will get evalled.

.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 :

nbsp;

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);
                    }

                    stream.Close();
                    streamToReadFrom.Close();
                    client.Displose();
                });

                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

.NET

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:

[HttpGet]
[Route("api/files")]
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 

.NET

app_offline.htm

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.

markup

app_offline

site

.NET Coding

smg-alumni.com 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"

or

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

If you want some more granular control you may use :

converter.CustomWkHtmlPageArgs

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.

.NET

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:

passwordtool1

passwordtool

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 -> https://bitbucket.org/ivopashov/cryptoapp 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 🙂

Coding javaScript

Input validation in Angular

Published by:

Validation is one of the main issues that developers have to deal with when handling user input in forms. The premise is that all user data coming in may be corrupt and some users may have bad intentions so validate inputs on the client and on the server side.
Maybe for this reason, angular (1.3+) provides a pretty powerful validation api through the all famous ngModel directive and its controller. By adding our custom directive to the input and requiring ngModel we can have a grip over the ngModel Controller which provides the validation api. So we start with something like:

disclaimer- should be only start-date in the markup. My syntax highlighter adds the =”” so ignore those.

So far so good- we have a form with an input where we will require the user to type in a date in a specific format within a specified date range and we will validate if that date is available for reservation on the server. So we bind te input to reservationStartDate and put in our custom directive – startDate.

Next thing, lets create the directive itself:

.directive('startDate',function(constVars,dateParserService,$http){ 
	return {
        restrict: 'A',
        require: ['ngModel'],
        link: link
    };

    function link(scope, element, attr, ctrls) {
        var ngModelController = ctrls[0];
    }

})

So far we don’t do anything but the important takeaway here is the require: [‘ngModel’] line when declaring our directive which says – “Hey let me use the ngModel Controller here”. Assume that in constVars we hold a date regex and dateParserService is custom logic that we created for parsing dates from strings. All the validation will happen in the link function of our directive and the required ngModel Controller is passed in the link function through the fourth argument (ctrls). In this case we will use the following methods for validation:

$parsers – that is a collection of functions where we sanitize input from user before handing it to the $validators. Every parser function passes the sanitized value to the next one. If we ever return undefined, the pipeline doesn’t reach the $validators.

$validators – name is pretty exemplary here – these are collection of functions where we apply validation logic.

$asyncValidators – same as above but we typically use these for server, api or whatever long running operations validation. They start not one after the other but simultaneously and deal with promises rather than values. If all resolve the value than validation passes, if one rejects it – validation fails. Let’s get to some specific example.

First of all, we want to check if the manually input value is in the format that we want the user to use and we will use regex – so we will put that in the $parsers:

function link(scope, element, attr, ctrls) {
        ngModelController.$parsers.unshift(function (viewValue) {
                var date;
                if (angular.isString(viewValue)) {
                    if (!constVars.dateFormatRegex.test(viewValue)) return undefined;
                    else {
                        date = dateParserService.parse(viewValue, "dd-MM-yyyy");
                        if (isNaN(date)) {
                            return undefined;
                        }else{
		            return date;
			}
                    }
                }
        });
}

I we can parse it we pass the parsed Date object down the pipeline, if not – return undefined, which stops the value propagation down the pipeline and sets myForm.reservationStartDate.$error.parse = true.
If we parsed the user input to date we want to validate if the user entered a date in a correct date interval (we don’t want dates before today for a reservation). We will put that into $validators:

		ngModelController.$validators.afterToday=function (modelValue,viewValue) {
			var today=new Date();
			if(today < modelValue){
				return true;
			}
			return false;	
        };

So after the date has been parsed it will be passed to the afterToday for business rule validation. Let's go a little further and add an asyncValidator. We will validate the date for availabiliy on the server:

ngModelController.$asyncValidators.isDateAvailable=function (modelValue) {
    return $http.post('api/date/available',modelValue).then(function(success){                       
        //yeah, went through                      
    },function(error){
        // no availability
    })
};

As i said, async validators (you may have many of those) will start running simultaneously and input will be validated only if all resolve the promise. You may give the user indication that something is loading by:

Checking Value on the server....

So that is the main validation pipeline of the ngModelController - $parsers-> $validators & $asyncValidators. There is one more hook that you can use - $viewChangeListeners which is again array of functions. It does not take args or return anything - these functions are used usually for additional $watches on the model instead of some validation logic. What is provided more in the api are methods to change the input state as $setPristine(),$setDirty(), $setTouched(), $setUntouched(). Those are self-explanatory so i wont elaborate on them.

By default the view value gets passed down the validation pipeline on every change (ie keystroke) which might be not necessary. You may want to validate the input on blur event only. So that is very easily configurable - you only need to decorate your input markup with ng-model-option:{updateOn:'blur'}

You can clone the source for this example and some more on https://github.com/ivopashov/angular-presentation It is in app->ngModelExample

.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]
	{
		get 
        {
            object val=null;
            dict.TryGetValue(index,out val);
            return val;
        }
		set 
        {
            if (dict.ContainsKey(index))
            {
                throw new Exception();
            }
            else
            {
                dict.Add(index,value);
            }
        }
}

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
    {
        Equal,
        LessThan,
        LessThanOrEqual,
        GreaterThan,
        GreaterThanOrEqual,
        NotEqual,
        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]);
            }
            else
            {
                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);
                default:
                    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
                {
                    PropertyName="CountryOfOrigin",
                    Comparison=Comparison.StartsWith,
                    Value="Fr"
                },
                new ExpressionFilter
                {
                    PropertyName="MaxMilesPerHour",
                    Comparison=Comparison.GreaterThanOrEqual,
                    Value=190
                }
            };

            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’
result