Friday, March 24, 2017

Fluent interface (API) in C#

Hi,

I was wondering why "fluent API" or "fluent interface" brings so many developer into trouble. I do like that kind of style, but I am not sure I would sacrifice my whole development style for this nice calling structure.

As a C# developer I found a way to go for me. I wrote an extension method on object-level like this:
1
2
3
4
5
6
7
8
    static class Fluent
    {
        public static T Do<T>(this T item, Action<T> method)
        {
            method(item);
            return item;
        }
    }

now i can work fluent like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    class Program
    {
        static void Main(string[] args)
        {
            Console.Out
                .Do(x => x.WriteLine("test1"))
                .Do(x => x.WriteLine("test2"))
                .Do(x => x.WriteLine("test3"))
                .Do(x => x.WriteLine("test4"))
                .Do(x => x.WriteLine("test5"))
                .Do(x => x.WriteLine("test6"));
        }
    }

great.

It is probably not that expressive as it is in a real fluent interface, but it works for every single object in every single case...

Nevertheless see Martin Fowler's original post on FluentInterfaces: https://www.martinfowler.com/bliki/FluentInterface.html

kr,
Daniel

Saturday, March 18, 2017

Lightning fast (minimal) setup for a JSON Rest API using WebAPI

While development time it is often necessary to mock services or create services for test. These don't need to consider security or performance issues, but have to return valid responses.

So... 

  • Create ASP.NET-WebApplication (currently I used regular .NET framework application and not CORE)
    • consider to use Azure or not (I believe that for test-services no Azure usage will be the default)
  • Empty Template
  • Add NuGets
    • Microsoft.AspNet.WebApi and its dependencies
    • (Newtonsoft.Json for JSON Operations)
    • (System.Data.SQLite for in Memory or file Database implementing Linq and standard interfaces usable for any DB-Communication library)
    • (Dapper for DB-Communication)
  • Add a global.asax file
    • Add the following code to Application_Start
GlobalConfiguration.Configure((config) =>
                {
                    ((HttpConfiguration)config).MapHttpAttributeRoutes();

                    config.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional }
                    );
                });
  • Add a new Item (WebApi-Controller) ... I called it in my example MyController
  • I removed the code generated and implemented the following example for demonstration
        [HttpGet]
        public IHttpActionResult GetData()
        {
            return Ok(new List<string> { "data1", "data2", "data3" });
        }
  • you can test this method (after starting in debugger) using the web browser
    see: http://localhost:63268/api/My/
    (Attention: the port is randomly generated by visual studio: check in your Properties, which port visual studio assigned you for the debugging sessions, or see which page is started when debugging session starts).
This small tutorial showed an easy way of creating a REST Api using WebApi. Consider using http://www.restapitutorial.com/ for further investigation into REST (especially which Http-Methods should be used for which operation) because using the wrong http-method can be really confusing.

If you added the nugets in the parenthesis you would be able to use better data stores than "List". By using:          
            data = new SQLiteConnection("Data Source=:memory:");
            data.Open();
            
... you can create an in-memory datastore with an initialized connection object inheriting IDbConnection which is the standard interface for SqlConnection, OdbcConnection and all the others like oracle and stuff...

Using dapper makes a simple Get-Request to a really simple one-liner. See:

        [HttpGet, Route("api/InMemory/Dapper")]
        public IHttpActionResult TestDapper()
        {
            return Ok(data.Query("select * from data"));
        }

Consider that this storage is non-persistent, but could be perfectly used for testing purposes.

kr, Daniel