Adventurous: Angular & .NET Core on Linux

Note: This article is not aiming on digging into details of setting up CI pipeline. It’s sole purpose is to explain my experience with deploying and running .NET Core app in Linux environment.

Another note: For the purpose of this article I created simple HelloWorld Web API (https://github.com/mattuu/HelloWorld.NetCoreApi) and simple HelloWorld Angular app (https://github.com/mattuu/HelloWorld.Angular) that calls this API.

Setup

This article will use following file system paths:

/usr/helloworld
|--> api (directory for .NET Core Web API)
|--> www (directory for Angular app)
|--> nginx.conf (config file for Nginx)

Get you code over to Linux server

The CI pipeline should push your code to file system on Linux machine.

Deploying .NET Core 2.1 Web API to CentOS7

Install .NET Core runtime on CentOS server

This guide describes steps to install .NET Core: https://www.microsoft.com/net/download/linux-package-manager/centos/runtime-current

To check if .NET Core installed successfully, simply run:

dotnet --version

Now you should be able to start API by typing:

dotnet /usr/helloworld/api/HelloWorld.dll
Create dotnet daemon

Every process in Linux needs to run it’s own daemon. In order to accomplish this, we will use SystemD utility.

First we create service file helloworld.service with following content:

[Unit]
Description=Hello World .NET Core App Service
After=network.target

[Service]
ExecStart=/usr/bin/dotnet /usr/helloworld/helloworld.dll 5000
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

Next we copy this file to SystemD location:

sudo cp helloworldapi.service /lib/systemd/system

Now we need to reload SystemD and enable the service:

sudo systemctl daemon-reload 
sudo systemctl enable helloworldapi

Finally we start the service and check the status:

sudo systemctl start helloworldapi 
systemctl status helloworldapi

More details of how to configure SystemD can be found here: https://www.freedesktop.org/wiki/Software/systemd/ or here: https://pmcgrath.net/running-a-simple-dotnet-core-linux-daemon

Install Proxy Server

Since .NET Core runs on Kestrel, we need to setup a web server that will act as reverse proxy for the API. Most commonly used are Nginx or Apache. I will use Nginx for this article.

Full instructions on how to install Nginx can be found here: http://nginx.org/en/docs/install.html

Configure Nginx to act as reverse proxy

Now we need to tell Nginx to forward requests to .NET Core application. By default .NET Core runs on port 5000 so below configuration should work fine (path: /usr/helloworld/nginx.conf)

location /api/ {
proxy_pass http://localhost:5000; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;
}

This ensures forwarding all requests to http://localhost/api are forwarded to http://localhost:5000 which is where .NET Core Web API is hosted.

Note: Nginx needs to be configured to include our custom configuration file so the following change needs to be done to Nginx default configuration (most likely to be in /etc/nginx/nginx.conf):

include /usr/helloworld/nginx.conf;

More on Nginx configuration options can be found here: https://nginx.org/en/docs/

Deploying Angular app to Centos7 OS

Our Angular app will be located in following directory: /usr/helloworld/www

Configure Nginx to serve static pages

Since Angular app is simple index.html, we need to tell Nginx to serve it as static content. Following article describes how to achieve this: https://medium.com/@jgefroh/a-guide-to-using-nginx-for-static-websites-d96a9d034940

Sample configuration may look like this (path: /usr/helloworld/nginx.conf)

location / {
root /usr/helloworld/www;
try_files /index.html =404;
}

location ~* .(js|jpg|png|css|woff|eot|svg|ttf|ico)$ {
root /usr/helloworld/www;
expires 30d;
}

First block ensures index.html is default document served by Nginx. This is needed to load Angular app properly.

Second line tells Nginx what to do with assets like JavaScript, CSS, images, fonts etc.

Once that’s done we should be able to navigate to http://localhost and see Angular app successfully loading:

If we now change browser url to http://localhost/?name=Matt, our application should display personalized greeting:

Our Angular app successfully passed name parameter to API and displayed greeting message generated by .NET Core.

Wrap-up

I really think .NET Core on Linux has great potential and will be exploring it further in future. I am planning on creating some bash scripts for dealing with this setup.

Useful links

Automatic generation of EF entities and mappings from existing database schema

This is  a bunch of useful scripts for generating C# Entity Framework Code First POCOs from existing database schema.

First, let’s create T-SQL function for generating C# class for EF entity:


This function deliberately ignores certain columns, (Created On/By, Modified On/By). This properties are pushed to EntityBase class, which our POCO inherits from. All other columns in DB table will be mapped to corresponding C# type.

Next, let’s create T-SQL function for EF configuration (mapping class):


Now, let’s put it all together in one script:


All source code is available here

Unit Testing stack for C#/Visual Studio

After spending some time on digging through unit testing components, I ran into a setup I am finally happy with. This consists of:

https://github.com/AutoFixture – acts as DI container/object factory, significantly improving unit test maintainability

https://github.com/moq – awesome mocking framework, fully integrated with AutoFixture

https://www.nuget.org/packages/SemanticComparison – excellent utility for comparing instances

https://github.com/shouldly/shouldly – great for simplifying assertion statements

https://github.com/xunit/xunit – superb unit testing framework, supporting parameterized tests, multiple test executions and much more

Although each utility is great on it’s own, when combined together, this stack significantly reduces amount of testing code.

Below I include sample config file with latest versions of all packages.

<?xml version="1.0" encoding="utf-8"?>
<packages>
    <package id="AutoFixture" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.AutoMoq" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Idioms" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Xunit2" version="3.50.2" targetFramework="net461" />
    <package id="Moq" version="4.1.1308.2120" targetFramework="net461" />
    <package id="SemanticComparison" version="3.50.2" targetFramework="net461" />
    <package id="Shouldly" version="2.8.2" targetFramework="net461" />
    <package id="xunit" version="2.1.0" targetFramework="net461" />
    <package id="xunit.abstractions" version="2.0.0" targetFramework="net461" />
    <package id="xunit.assert" version="2.1.0" targetFramework="net461" />
    <package id="xunit.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net461" />
    <package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net461" />
</packages>

 

 

 

Animated iPhone-style ImageButton with Silverlight 4

In this article I am presenting a way to create animated iPhone-style ImageButton control in Silverlight 4. Button will have icon on it, rounded corners and will zoom-in/zoom-out on hover. It will be done programmatically, with very minimum amount of XAML.

I start with creating ImageButton class. I use ButtonBase as base class:

Class declaration

I want my button to contain rounded rectangle with shadow and image on it. I add these items in constructor:

Class constructor

Now my control contains rectangle and image laid out over a grid to ensure proper items positioning. Next step is to add animation to enable zoom-in/out on hovering. This can be achieved with storyboards and double animations:

Animations

To start animations I need to start animations when mouse cursor enters or leaves control:

Events

Very last step is making ImageSource property “bindable” so you can specify image from XAML. In order to do this I register new dependency property on my class:

Dependency property

The control then can be used in a following way:

Usage

And ready controls looks like this:

Final effect

 

WCF Custom tool error: Failed to generate code for the service reference.

Very recently, building multi-tier application involving Silverlight front-end inter-operating with WCF back-end, I encountered very odd, yet annoying behaviour of Visual Studio 2010. I was building new functionality using Telerik RadMap for Silverlight control that was to display some spartial data supplied by WCF service. To achieve this my Silverlight application had to reference few Telerik assemblies (Telerik.Windows.Controls.DataVisualization.dll). What is important is fact, that Service Reference for WCF service had been there already, project built and everything was working nicely, until I added extra method to WCF. After using “Update Service Reference” VS command, I started getting following error.

WCF error Screenshot no.1

Lack of further details with regards to this error and appropriate feedback from Visual Studio certainly does not help to get to the bottom of the problem, however after some investigation it turned out that one of Telerik assemblies caused this problem. When VS2010 creates service reference, default settings are that it should “reuse” all available types in reference. Excluding certain types from serialization allows service reference to be added successfully.

WCF error screen 2

I hope this helps anybody who got stuck with this problem.

SQL Data Types vs. C# Data Types

This article is just a reference of SQL Data Types to C# Data Types.

SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) user-defined type None
table None None
cursor None None
timestamp None None
xml SqlXml None

	

Interface vs. Abstract Class in .Net

In this article I will try to briefly explain main differences between interface and abstract class concepts in .Net. Although the differences can appear to be very subtle and little important, badly design inheritance can lead to massive problems and great mess in the code.

Abstract Class

Accordingly to MSDN abstract classes “are classes that cannot be instantiated (…), useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.”

Do declare abstract class following syntax is required:

abstract class Car()
{
    public Car() { };
    public string Make { get; set; }
    abstract public void Drive();
}

This class cannot be instantiated so following line will cause compiler throwing error:

Car a = new Car(); // this won’t compile

The only way to instantiate class Car is by creating child class that will inherit from it:

public class OffRoadCar : Car
{
    public OffRoadCar();
    public void Switch4WD(bool On)
    {
        // method code
    };
}

Because class OffRoadCar inherits from Car, following code will work:

OffRoadCar offroader = new OffRoadCar();
offroader.Switch4WD(true); // from OffRoadClass
offroader.Drive(); // from Car class

Interface

Interface, after MSDN, is a “definition that can never change after the interface definition has been released. This interface invariance is an important principle of component design, because it protects existing systems that have been written to use the interface.”

Interface cannot be instantiated, but serve as sort of pattern for derived classes, that share and implement specific features. Derived classes can also extend interface functionality, by defining extra members. Following code demonstrates sample interface:

public interface ICar
{
    string Make { get; set; }
    void Drive();
}

Because interface can serve as a “template” for series of classes, implementing it is a way of ensuring that all derived object will have set of common features. In example:

public class SportsCar : ICar
{
    public string Make { get; set; } // required from ICar
    public bool IsConvertible { get; set; } // adds extra feature
    public void Drive() // required by ICar
    { 

    };
}

public class Van : ICar
{
    public string Make { get; set; } // required from ICar
    public double LoadWeight { get; set; } // adds extra feature
    public void Drive() // required by ICar
    { 

    };
}

Because both SportsCar and Van classes inherit from ICar interface, they are forced to have common set of features (Make property and Drive() method). Thanks to that it is possible to write:

List<ICar> vehicles = new {
    new SportsCar() { Make = "Ferrari", IsConvertible = false },
    new Van() { Make = "Ford", LoadWeight = 3000 }
};

foreach(ICar car in vehicles)
{
    Console.WriteLine(car.Make);
}

Conclusion

In opposite to abstract class, interface cannot implement any default functionality in its methods. It also cannot implement default constructor. This is why we say we implement interface and inherit from abstract class.

Class may implement an unlimited number of interfaces, but may inherit from only one abstract class. A class that is derived from an abstract class may still implement interfaces.

Abstract classes and interfaces play extremely important role in programming concept called polymorphism, which in essence is “ability for classes to provide different implementations of methods that are called by the same name” (MSDN).

Resources

Web service proxy in ASP.NET MVC – how to avoid cross-site script warnings

In this article I will walk through the process of creation of web service proxy in ASP.NET MVC. This is specifically useful as a method of preventing cross-site scripting (XSS) warnings on web page. This is a feature of all modern web browsers and cannot be easily omitted as it enforces same origin policy. This sort of attack can happen when browser tries to download client script from outside of application domain – simply speaking when web browser downloads script from different location.

For the purpose of this demo I will use IP look-up web service available at http://ipinfodb.com/. This web service allows to obtain geodata for given IP address and can be extremely useful for in example centralizing map (i.e. Google maps or Bing maps) on user’s location.

Valid request should look like this: http://ipinfodb.com/ip_query.php?ip=213.180.146.27

Of course it is possible to call this web service at Ajax request level, by simply writing:

    var ipaddress = '213.180.146.27';
    $.get('http://ipinfodb.com/ip_query.php?ip=' + ipaddress + '&timezone=false',
        function(data) {...}
    );

although on all most recent web browsers (IE 8, FF 3.6, Chrome, Safari) user will get very ugly security warning every time browser executes this code. This is due to XSS vulnerability mentioned above and can be extremely annoying to user when application performs this operation on very first page load.

Thankfully ASP.NET provides set of mechanisms to overcome this problem. In simplest words there is an extra layer between web service and Ajax call needed, and this layer is web service proxy.

The core component of proposed solution is a HTTP handler class, in this example named LocationProxyHandler. This class will create and execute HTTP request to web service and return response to client. It needs to implement two interfaces: IHttpHandler and IRouteHandler. First interface guarantees that class can process HTTP request, second allows to use class in routing rule that will be required to redirect requests to the handler class. Implementation of class is as follows:

    public class LocaionProxyHandler : IHttpHandler, IRouteHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string ipAddress = context.Request.QueryString["ipaddress"];

            string str = string.Format(@"http://ipinfodb.com/ip_query.php?ip={0}",
                ipAddress);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(str);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());

            HttpResponse res = context.Response;
            res.ContentType = "application/xml; charcode=utf8";
            res.StatusCode = 200;
            res.Write(reader.ReadToEnd());
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return this;
        }
    }

The most important method in the class is ProcessRequest(). It takes current HttpContext as parameter and for this context it executes HTTP request to external web service and builds and returns response. Before it fires HTTP request, it takes IP address as parameter from URL.

There is one more thing that needs doing before this proxy can serve the purpose. It has to be registered in ASP.NET MVC routing table within the application. To accomplish this the following code is needed in RegisterRoutes() method inside Global.asax.cs:

    routes.Add(new Route("{action}.proxy", new SocialCitiProxy.LocaionProxyHandler()))

This makes calls like http://localhost:1431/myApp/Service.proxy understandable for MVC engine and ensures the request is redirected to LocationProxyHandler.

Very final step is Ajax request to LocationProxyHandler:

var ipaddress = '213.180.146.27';
$.ajax({
        url: 'GetUserLocation.proxy',
        data: 'ipAddress=' + ipaddress,
        dataType: 'xml',
        contentType: 'application/xml; charset=utf8',
        error: function (xhr, status, e) {...},
        success: function (data) {...}
});

No security warning messages appears now and this is exactly what we wanted to achieve.

Cascading dropdowns with just a bit of Ajax in ASP.NET 2.0

In this sample I am going to go through very common idea of cascading dropdowns. Very basically speaking it is all about having set of dropdowns where next dropdown is populated on the basis of value selected from previous one.

Let’s start with very simple xml document:

<?xml version="1.0" encoding="utf-8" ?>
<People>
    <Person ID="1" Name="Laith Francis" ParentID="0" />
    <Person ID="2" Name="Hammett Swanson" ParentID="0" />
    <Person ID="3" Name="Macon Hayden" ParentID="0" />
    <Person ID="4" Name="Kennan Mooney" ParentID="0" />
    <Person ID="5" Name="Jin Hutchinson" ParentID="4" />
    <Person ID="6" Name="Emery Schwartz" ParentID="1" />
    <Person ID="7" Name="Melvin Garrett" ParentID="2" />
    <Person ID="8" Name="Giacomo Lamb" ParentID="4" />
    <Person ID="9" Name="Stephen Harding" ParentID="3" />
    <Person ID="10" Name="Ian Ward" ParentID="1" />
    <Person ID="11" Name="Raphael Walters" ParentID="2" />
    <Person ID="12" Name="Lee Gould" ParentID="1" />
    <Person ID="13" Name="Carter Carpenter" ParentID="4" />
    <Person ID="14" Name="Kareem Shepard" ParentID="14" />
    <Person ID="15" Name="Zahir Montgomery" ParentID="12" />
    <Person ID="16" Name="Zachery Mcmahon" ParentID="14" />
    <Person ID="17" Name="Hu Dillon" ParentID="12" />
    <Person ID="18" Name="Allistair Bradford" ParentID="13" />
    <Person ID="19" Name="Vincent Bryan" ParentID="11" />
    <Person ID="20" Name="Vance Santos" ParentID="12" />
</People>

Now let’s create very simple .aspx page, that has three dropdowns. First one we will populate using standard ASP.NET binding method so we will use DropDownList control in this instance. Because we do not populate other dropdowns straight away, nothing stops us from using html select tags. The markup can be like this:

<form id="form1" runat="server">
<div>
    Boss:
    <asp:DropDownList DataSourceID="xmlBosses"
        DataTextField="Name"
        DataValueField="ID"
        ID="ddlBosses" runat="server"></asp:DropDownList>
    <asp:XmlDataSource DataFile="~/App_Data/data.xml"
        ID="xmlBosses" runat="server" XPath="/People/Person[@ParentID=0]">
    </asp:XmlDataSource>
    <br />
    Manager:
    <select id="ddlManagers"></select>
    <br />
    Workers:
    <select id="ddlWorkers"></select>
</div>
</form>

Having this markup done we now need a mechanism to populate ddlManagers when ddlBosses changes. Same action needs to happen to ddlWorkers when ddlManagers is changed. To accomplish that we need make Ajax request to some data provider. In our instance, because application is created in ASP.NET 2.0, I opted for web service, (.Net 3.5 with MVC with it’s JsonResult class and Json() method is much more friendly on this front thought).

Firstly we need web service. We want to give it a boss Id and get list of all managers that report to this boss. Web service can look like this one:

public class People : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
    public List GetData(int ParentID) { 
        List<int> result = new List<int>(); 

        XmlDocument doc = new XmlDocument(); 
        doc.Load(Server.MapPath("~/App_Data/data.xml"));
        XmlNodeList nodes = doc.SelectNodes("/People/Person[@ParentID=" 
            + ParentID.ToString() + "]");

        foreach (XmlNode node in nodes) {
            Person p = new Person();
            p.ID = Convert.ToInt32(node.Attributes["ID"].Value);
            p.Name = node.Attributes["Name"].Value;
            p.ParentID = Convert.ToInt32(node.Attributes["ParentID"].Value);
            result.Add(p);
        } 
        return result;
    }

    [Serializable]
    public class Person {
       private int _id;
       private string _name;
       private int _parentId;

       public int ID {
           get { return _id; }
           set { _id = value; }
       }

       public string Name {
           get { return _name; }
           set { _name = value; }
       }

       public int ParentID {
           get { return _parentId; }
           set { _parentId = value; }
       }
    }
}

Having all of that we are now ready for very final stage – building Ajax call to execute web service and process returned data. The only thing we need is a bit of jQuery code, that will do it all:

$(function() {
    // for each dropdown bind change event
    $('select').change(function(e) {
        // capture which dropdown caused request
        if(!e) var e = window.event;
        var srcId = e.srcElement.id;

        // create ajax request
        $.ajax({
            url: 'WebServices/People.asmx/GetData', //call to created web method
            data: { ParentID: $(this).val() },  //web method expects ParentID
            contentType: 'application/xml; charset=utf-8',
            dataType: 'xml',
            error: function(xhr, status, e) { ... },
            success: function(data) {
                // if success get dropdown to be updated
                var select = null;
                switch(srcId) {
                    case 'ddlBosses':
                        select = $('select#ddlManagers');
                    break;
                    case 'ddlManagers':
                        select = $('select#ddlWorkers');
                    break;
                    default:                         
                    break;
                };

                // remove items from dropdown
                $(select).empty();

                // loop through Ajax request results
                $('Person', data).each(function() {
                    // for each result create option element
                    var option = document.createElement('option');
                    $(option).text($('Name', this).text()).val($('ID', this).text());
                    // and append it to dropdown
                    $(select).append(option);
                });
            }
        });
    });
});

And this is it!

I hope you will enjoy it!