ITmeze - IT world server like cyprus meze

Running C# on AWS Lambda


One of the greatest things about AWS cloud is the AWS Lambda - event-driven service where AWS "runs your code in response to events". It is a perfect fit for any backend jobs or scheduled tasks. 

Unfortunatelly AWS Lambda currently supports  code in Node, Python or Java. And it runs on Amazon Linux. 

Thankfully, it looks like Microsoft is making .net for a cross platform world. Moreover, it looks like it would be possible to natively compile dotnet applications.

So, even though it looks like C# is not going to be among supported languages on AWS Lambda, we can alway spawn dotnet process from Node or Java. 

Let us start with getting dotnet cli. In order to do that i followed step-by-step I have created sample console app by simply running dotnet new. 

I have edited Program.cs file (note the return 0):

Now, it we have to natively compile application:

You can find executable in /bin/{Configuration}/dnxcore50/native/{appname}

Now we need node.js code to spawn external process. I may look more or less like that:

Call it index.js and zip it with executable. 

Now, create new aws lamda and uploading zip with those 2 file. 

And running test: 


This really makes me smile :)

Tags: [dotnet]

Deploying Clojure/Java based web app (via Jetty) on Windows and IIS. Step by step guide.


Few words to start with...

I got into clojure programming language some time ago. It took me some time to get into lisp, functional programming and repl-based developement as that was completely opposite to what i have been doing with c# over last couple of years. I find time i have spend with clojure to be very rewarding. More on this some other time.

I have recently completed small clojure based app and i needed to host it somewhere. Web is full of tutorials of how to deploy your clojure app into linux based vm. But i needed something different. Why? I already host couple of my hobby projects on aws' Windows VM ( and i just didn't want to get a linux vm (that you have to pay for and maintain).

Fortunatelly, there is quite an easy step to deploy your clojure (or any java based app) on IIS. Important thing to note here is that this process, that i am goind to present, will only work on windows equipped with IIS 8+. That means you need either Windows Server 2012 or Windows 8 at least.

Although guide below was made specifically for hosting Clojure on IIS via Jetty it can be easily amended to any Java based web application running on either Jetty or Tomcat.

We will start by preparing a simple clojure based web application.

1. Prerequisites

You need Windows machine (at least Windows 8 or Windows Server 2012) with IIS and JDK installed on it.

2. Installing Jetty on Windows

This is straightforward. Just grab recent version from Jetty web site and unzip it to your hard drive. No more work is necessary. Alternatively you may install jetty using chocolatey package. Whatever works for you. After installation your jetty folder should look more or less like that:

3. Preparing WAR file of your web app

As we will be going to host our site via Jetty, we need to prepare a so called WAR file of our web application - creating WAR file is outside scope of this blog post but i will just suggest to use lein-ring plugin to achieve that.

Now, you need to copy such a generated WAR file to webapps folder in your jetty installation path. In my case, as i called app ‘iis-loves-clojure’, webapps folder looks like that:

You can think about your jetty/webapps location as your typical inetpub/wwwroot folder for iis - a default place to keep all your web sites.

That’s it in this part. We are almost ready… Now to the key point:

4. Installing HttpPlatformHandler

Key to running Java apps on Windows is HttpPlatformHandler IIS module. This is relatively new thing, released by Microsoft in early 2015. Apparently it is being used by MS to host Java based app on their Azure cloud platform.

First thing you need to do is to install this module. You can do that via a direct link or using Microsoft’s Web Platform installer.

5. Setting up site on IIS

Once module is installed you can create new web site via your IIS Manager, like on the example below:

Now, just a note, ‘physical path’ that you specify doesn’t have to be a part of your jetty or webapps installation. For now, this can be just an empty folder.

6. Adding web configuration file

In the folder (defined by physical path of just created iis web site) create a new file called web.config. It’s content should look like that:

<?xml version="1.0"?>
        <add name="httpplatformhandler" path="*" verb="*" modules ="httpPlatformHandler" resourceType="Unspecified"/>
      <httpPlatform processPath="C:\Program Files\Java\jdk1.8.0_25\bin\java.exe" 
                    arguments=" -Djetty.port=%HTTP_PLATFORM_PORT% -Djetty.base=&quot;C:\tools\jetty&quot; -jar &quot;C:\tools\jetty\start.jar&quot;" 

Now, this requires an explanation. in configuration/system.webServer/handlers section we have added HttpPlatoformHandler module.

It’s configuration contains processPath - a path to your java.exe from jdk location. Arguments should point to your jetty location (and it’s start.jar file).

You can read detailed explanation of other parametes as well as sample configuration for Tomcat server on Microsoft’s website.

7. That’s it! It should work!

Now you can go to your site. In my case that’s it http://localhost:3333/iis-loves-jetty - subfolder ‘iis-loves-jetty’ is due to the name of WAR file. If you rename your WAR file to root.war then your site should be accessble via just ‘http://localhost:3333/.

That’s it!

Tags: [clojure jetty iis deploy]

System.Linq.Dynamic and Spatial Searches


On my current project i am doing a LOT of dynamic searches. 

Lot's of them go through System.Linq.Dynamic library - it is really just one .cs file. As library has lost somewhere on internet, the only place i have managed to find it is on one of github's repository :

I had to run some spatial searches over exposed DbGeography type - those are directly on database - via Entity Framework

public class Town { public string Name { get; set; } 
public DbGeography Location { get; set; } } 

The problem is, dynamic queries (based on string) simply won't work on that.

_db.Towns.Where("Location.Distance(@0) < 20000", someLocation).ToList() 

Such query will bruttaly fail with "Methods on type 'DbGeography' are not accessible". Going through the code shows us:

if (!IsPredefinedType(method.DeclaringType))

is throwing exception. Solution for that is simple and requires to add DbGeography to 'predefinedTypes' variable. Now, following test will pass:

public void DistanceSearchShouldWork()
	var warsaw = new Town() { Name = "Warsaw", Location = DbGeography.FromText("POINT(52.229718 21.012214)") };
	var lodz = new Town() { Name = "Lodz", Location = DbGeography.FromText("POINT(51.759304 19.455969)") };
	var berlin = new Town() { Name = "Berlin", Location = DbGeography.FromText("POINT(52.523206 13.410836)") };
	var towns = new List

	var distance = warsaw.Location.Distance(lodz.Location);

	Assert.Equal(1, towns.Where("Location.Distance(@0) < 20000", warsaw.Location).Count());
	Assert.Equal(2, towns.Where("Location.Distance(@0) < 200000", warsaw.Location).Count());
	Assert.Equal(3, towns.Where("Location.Distance(@0) < 2000000", warsaw.Location).Count());

In case you would like to grap solution directly - you can do that on fork here.


Tags: [linq] [DbGeography] [spatial]

This blog is powered by NancyFX!


This blog is powered by NancyFX MongoDB - source code can be found on github repo.

I have to add that it was a pleasure to work with both although i remain sceptical if i would use mongodb in future. It's lack of transactions and no async c# api really scares me. But anyway, If you are interested how both Nancyfx and MongoDB can work under .net check this one out.

Thats all really!

Tags: [nancyfx] [mongodb]

Redirect to new domain after rebranding with IIS Url Rewrite Module


Client has a bunch of domains and and websites. Because They have decided to change company's name recently I was asked to proceed with chanage of domain names as well. After few weeks of constantly informing visitors about planned changed We decided that it is a good time to abandon old domains and redirect visitors to new ones. In order to "be okay" with google (their page ranks, indexed pages and so on) we make those redirects permanent (301 Moved Permanently as a response status code). As all of the websites are hosted on IIS 7 I have decided to use URL Rewrite Module for the job. First of all - make sure You have Url rewrite module installed on Your server machine. Secondly, You need to update web.config file to something like the one that (assuming old-name):
                <clear />
                <rule name="rebranding" enabled="false" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_HOST}" pattern="(.*)old-name(.*)" />
                    <action type="Redirect" url="http://{C:1}new-name{C:2}/{ToLower:{R:1}}" appendQueryString="true" />
You can do that in IIS manager as well. Some explanation here:
  • match url="(.*)" - matches all request
  • trackAllCaptures="true" - will enable to use captured grups in our redirect url
  • (.*)old-name(.*) - matches each HTTP_HOST that has 'old-name' within, like: or
  • http://{C:1}new-name{C:2}/{ToLower:{R:1}} - redirected url, R:1 stands for matches from and C:1 and C:2 matches those from conditions, ToLower changes text to lower case letters
  • appendQueryString="true" - will append query string to newly generated url
Have fun

Tags: [web development]

Javascript Encode on server side - Medium Trust Environment


It happens from time to time I have to get rid of those funky apostrophe in my server/javascript code. To do such kind of things I was using Microsoft Anti-Cross Site Scripting Library. By simply calling:

public static string JavaSriptEncode(this string text) {
  return Microsoft.Security.Application.AntiXss.JavaScriptEncode(text, false);

Unfortunately, It doesn't work in Medium trust environment - btw, why the hell i get stingy clients. After some time digging all over internet and trying to write it by myself I accidentally found a thing that I never believed to be there. Well, ladies and gentleman, since .NET 4.0 HttpUtility has a new static function called... JavaScriptStringEncode

public static string JavaSriptEncode(this string text) {
  return HttpUtility.JavaScriptStringEncode(text);


Tags: [encoding] [javascript] [web development]

Deploying BlackBerry OTA App (.jad, .cod files) or Android(.apk) on IIS


Hope some other people will find this post helpful. We had an issue today at work with providing BlackBerry application over the web site that was hosted on IIS 7.5. Although Screen shots that You 'll find below were made for this specific server procedure might look pretty much the same when it comes to older versions of IIS. By default (for IIS) .jad and .cod files are not delivered over IIS. The problem and it's solution lies within MIME types registered on the server. To fix that someone has to add MIME types with valid extension and type:
  1. Go to Internet Information Services Manager  (I usually do that by right clicking on Computer, choosing Manage and expanding Roles/WebServer/IIS, or simply search for IIS in Start -> Search for Programs box
  2. Click on Your server name, Switch to Features View if You are in Content View
  3. You will find MIME Types icon. Double click it.
  4. On the Action Pane - usually on the right side, select Add..
  5. Fill window with provided information (This registers .jad extension).
  6. Do the same for .cod files - You may have to delete or edit existing .cod settings as I found those already existing with some image type.
  7. Restart IIS. (iisreset in command prompt)
  You can follow above steps to set up Android Package File (APK). To do that add MIME type like one below:   Hope this will help someone.

Tags: [blackberry] [iis] [mobile] [web development]

Handler "Elmah" has a bad module "ManagedPipelineHandler" in its module list


Elmah - awesome library for that enable to log exceptions (as well as those that end up with Yellow screen of death). It comes with a great module and a handler used to view error logs. It really helps a lot. I used that in literally every web project I have made. Yesterday, I was installing new project on fresh Windows Server 2008 R2. I ended up with an error: Handler "Elmah" has a bad module "ManagedPipelineHandler" in its module list. After hour of goggling I couldn't find a solution that would solve my problem (reinstalling, changing ISAPI restrictions). Nothing helped. Then I have found out that problem lies in IIS7 configuration part in my web.config.
    <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
    <add name="Elmah" path="elmah.axd" verb="POST,GET,HEAD" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode"   />
My set up was done based on dotnetslackers article, and I simply copied their pre IIS7 configuration to system.webserver part. The part that I was missing was preCondition="integratedMode" attribute for a handler. Hope that helps someone

Tags: [web development]

Validate max file size during upload in mvc


Just a quick sketch. Validation is done as an Attribute (DataAnotations way).
 public class FileAttribute : ValidationAttribute {

        public int MaxContentLength = int.MaxValue;
        public string[] AllowedFileExtensions;
        public string[] AllowedContentTypes;

        public override bool IsValid(object value) {

            var file = value as HttpPostedFileBase;

            //this should be handled by [Required]
            if (file == null)
                return true;

            if (file.ContentLength > MaxContentLength) {
                ErrorMessage = "File is too large, maximum allowed is: {0} KB".FormatWith(MaxContentLength / 1024);
                return false;

            if (AllowedFileExtensions != null) {
                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedFileExtensions);
                    return false;

            if (AllowedContentTypes != null) {
                if (!AllowedContentTypes.Contains(file.ContentType)) {
                    ErrorMessage = "Please upload file of type: " + string.Join(", ", AllowedContentTypes);
                    return false;

            return true;
And now decorators (within viewmodel).
[Display(Name = "Upload Proof of Address")]
[File(AllowedFileExtensions = new string[] { ".jpg", ".gif", ".tiff", ".png", ".pdf" }, MaxContentLength = 1024 * 1024 * 8, ErrorMessage = "Invalid File")]
public HttpPostedFileBase AddressProof { get; set; }
Hope that helps someone.

Tags: [] [data-annotations] [validation] [web development]

Noscript information with a link to google search


Some web apps just do not work without JavaScript. Just doesn't. Stop. We are usually asked to provide users with nice looking information that this site is best viewable with JavaScript turned on. Plus there is a need to explain them how to turn JS in their browsers. Smart and yet incredibly simple would be to direct them to google search result for a phrase like 'How do I enable JavaScript in my browser?'
  <a class="enable-js" href="">
    XXX application requires JavaScript to be enabled in browser
This one I use for most of web apps I have made so far. Smart, simple and always accurate. In fact that would be event nicer to add browser with version ...

Tags: [javascript] [noscript] [web development]

Next -->

Copyright 2013 © ITmeze