Ehsan Ghanbari

Experience, DotNet, Solutions

Getting started with Scala

I heard about Scala programing language a few days ago; its advantages and power. After reading a few hours about the features of this cool language, I decided to write a short post about to introduce it. Scala is one of the new languages that is based on the JVM and it's most famous because of its inherent strength. Scala is influenced by Java and Its syntax has a lot of similarities to Java and that's why most of the developers easily switch to Scala. Another advantage of Scala is that it supports the object-oriented, and functional style of programming; so it can be used for any sort of application.

As I'm not familiar a lot with Scala, based on what I read, it takes less time to code as compared to Java and it is easy to write, compile, debug and run the program in Scala. You can see the Language keyword in the table below:

 

abstract

case

catch

class

def

do

else

extends

false

final

finally

for

forSome

if

implicit

import

lazy

match

new

Null

object

override

package

private

protected

return

sealed

super

this

throw

trait

Try

true

type

val

Var

while

with

yield

 

-

:

=

=>

<-

<:

<%

>:

#

@

 

 

 

Just like many languages, a lot of keywords are the same. But definitely, there are some new keywords! Now let's get our hands a little bit dirty with code. By the way, one of the most famous IDE for Scala is IntellijIdea or you can use Scastie as an online Editor. Defining class in Scala is Just like C# or Java, Classes contain methods, values, variables, types, objects, traits:

 

class Sample

val sample = new Sample

 

If you would want to create a constructor for the above class, it's a little bit different from C# or Java:

 

class Sample(var a: Int = 0, var b: string = 0)

val sample1 = new Point 

val sample2 = new Point(1,"Ehsan")

println(sample1.a)

println(sample2.b)

 

Method Definition is so simple :

 

 def add(a: Int, a: Int): Int = (a + b)*2  //the definition

 println(add(1, 2)) //the usage

 

As I mentioned before, Scala is support for functional programming as well. Functions in Scala are like the expression in C# which takes the argument:

 

val zero = () => 1

val one = (a: Int) => a + 1

val two = (a: Int, b: Int) => a + b + 1



Docker is different from a virtual machine!

The use of Linux containers to deploy applications is called containerization. A container runs natively on Linux and shares the kernel of the host machine with other containers. It runs a discrete process, taking no more memory than any other executable, making it lightweight. virtual machine (VM) runs a full-blown operating system with just virtual access to host resources through a hypervisor. VMs provide an environment with more resources than most applications need!

 

Containers allow a developer to package up an application with all of the parts it needs, such as libraries and other dependencies and ship it all out as one package and docker is a tool designed to make it easier to create, deploy, and run applications by using containers. It provides a way to run applications securely isolated in a container with all its dependencies and libraries. Docker brings several new things to the table. The first one is that it makes containers easier and safer to deploy And it enables developers to easily pack, ship, and run anywhere. Based on reports, over 3.5 million applications have been placed in containers using Docker technology. Now the developer can rest assured that the application will run on any other Linux machine regardless of any customized settings.

 

Unlike a virtual machine, rather than creating a whole virtual operating system, Docker allows applications to use the same Linux kernel as the system that they're running on and only requires applications be shipped with things not already running on the host computer. This gives a significant performance boost and reduces the size of the application. For developers, it means that they can focus on writing code without worrying about the system that it will ultimately be running on. It also allows them to get a head start by using one of the thousands of programs already designed to run in a Docker container as a part of their application. Docker gives flexibility and potentially reduces the number of systems needed because of its small footprint and lower overhead. As a result, The main difference between containers and VMs is that containers just abstract the operating system kernel while the VMs abstracts an entire device.



Using Middleware to handle exceptions in asp.net core

There are a few ways to handle exceptions in asp.net core 2.1. using Middleware is so straightforward, and it handles the application exceptions as well as exceptions from filters and you can have full control over. Look at the following class:

 

 public class MiddlewareExceptionHandler

    {

        private readonly RequestDelegate _requestDelegate;

 

        public MiddlewareExceptionHandler(RequestDelegate requestDelegate)

        {

            _requestDelegate = requestDelegate;

        }

 

        public async Task Invoke(HttpContext context)

        {

            try

            {

                await _requestDelegate(context);

            }

            catch (Exception ex)

            {

                await HandleExceptionAsync(context, ex);

            }

        }

 

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)

        {

            var code = HttpStatusCode.InternalServerError;

            var result = JsonConvert.SerializeObject(new { error = exception.Message });

            context.Response.ContentType = "application/json";

            context.Response.StatusCode = (int)code;

            return context.Response.WriteAsync(result);

        }

    }

 

And register the class in Configure method of Startup class:

 

 

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();

            }

 

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCookiePolicy();

 

            app.UseMiddleware(typeof(MiddlewareExceptionHandler));

 

            app.UseMvc(routes =>

            {

                routes.MapRoute(

                    name: "default",

                    template: "{controller=Home}/{action=Index}/{id?}");

            });

        }

 

Note that I'm returning the exception as JSON. In order to Invoke the exception in HTTP, you can change the MiddlewareExceptionHandler class like below:

 

  

 public class MiddlewareExceptionHandler

    {

        private readonly RequestDelegate _requestDelegate;

 

        public MiddlewareExceptionHandler(RequestDelegate requestDelegate)

        {

            _requestDelegate = requestDelegate;

        }

 

        public async Task Invoke(HttpContext context)

        {

            try

            {

                await _requestDelegate(context);

            }

            catch (Exception ex)

            {

                if (context.Response.HasStarted)

                {

                    throw;

                }

 

                await context.Response.WriteAsync(ex.Message);

 

                return;

            }

        }

    }

 



GraphQL as an alternative for Rest

GraphQL is an open-source runtime for filling data query language introduced by Facebook. It could be an alternative to REST as it allows the client to define the structure of the data query based on the need and retrieve the same structure of the data from the server! Wow.. That's not all the story, in fact, the APIs of GraphQL get all the needed data in a single request while, traditional REST APIs sometimes require multiple URLs to fetch data. So it would be more efficient. Many programming languages support GraphQL, you can see the list of languages and frameworks here. I'm starting with C# and Dot Net. To keep it simple, create a console application and reference the GraphQL:

 

 

After installing, add a Class named Book in the project:

 

   class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

 

Now, in order to use the above class as GraphQL metadata, there is an attribute with the same name in GraphQL namespace:

 

 class Query
    {
        [GraphQLMetadata("Book")]
        public Book Retrieve()
        {
            var book = new Book { Id = 1, Name = "Asp.net Core" };
            return book;
        }
    }

 

A simple method with a custom return type(Book) which has been assigned by GraphQLMetadata attribute. Now in order to retrieve the sample data via GraphQL as JSON, create a class and use the Schema class of QraphQL which lives in GraphQL.Types namespace:

 

 static class GraphQLRequest
    {
        public static string Request()
        {
            var schema = Schema.For(@"
                  type Book {
                    id: ID
                    name: String
                  }

                  type Query {
                    book: Book
                  }
                  ", q =>
                     {
                         q.Types.Include<Query>();
                     });

            var json = schema.Execute(q =>
            {
                q.Query = "{ book { id name } }";
            });

            return json;
        }
    }

 

Now if you call the above Request method in your program class:

 

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}", GraphQLRequest.Request());
        }
    }

 

You will see the output of QraphQL as JSON:

 



The combination of Stackify and Netling are doing a great job!

There are lots of tools and libraries out there for monitoring the Dot Net web applications. I personally use several tools based on my need. One of the tools I've always liked is Netling. It's great for fetching some overall results about the load time and resource usages of the application on heavy requests.  Rather than that, I usually use another code monitoring tool to see what's going exactly in my code. Get the latest version of Stackify and Netling. Firstly, run the Netling client and test your application load via different Threads, I'm testing the app on my website source code:

 

 

You can see the result in the picture above for 16 threads. Note that I'm running the app on my local computer machine and running on the web server would appear different result:

 

 

Anyway, you can see about the details of each parameter of Netling over here. Netling gives us overall result about the load and performance but it doesn't give us which section or which method causes the load issue. As I told, Stackify is a great tool for code monitoring; After installing and enabling the application via the mentioned link at the beginning of the post, run your application and see the result in the local address that Stackify gives you:

 

 

It's obviously shown that which action takes more time than others. And by selecting the action on the left side you can see the details on the right side. You can detect the heavy queries and modify them. needless to say that, Stackify code monitoring and you can only use it in your local machine on your source code.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In asp.net MVC
Redis as a cache server
How to query over Icollection<> of a type with linq
Domain driven design VS model driven architecture
What's the DDD-lite?