Tuesday, February 21, 2017

Authentication and Authorization in ASP.NET Core

Common vulnerabilities in software

  • Cross-site scripting attacks
  • SQL Injection
  • Cross-Site request forgery
  • Open redirect attacks

Authenticiation

ASP.NET Core Identity is a membership system that adds login functionality to ASP.NET Core apps. External login providers are also supported. (Read the article) Identity is enabled by calling UseAuthentication() which adds authentication middleware to the request pipeline. (In ASP.NET Core 1.x this was UseIdentity() - See Migration Guide)

When signing out, SignOutAsync clears the user's claims stored in a cookie. You can also add custom user data to Identity. 


Tuesday, February 7, 2017

Software Architecture Design - Considerations

Image Credits  : Colour Box


Architecture of anything defines how well the thing is designed and how long it's going to last. Be it a a building, a car or anything the same rule applies. It is the same when it comes to a software architecture as well.

If the architecture of a software is designed well, it should be able to accommodate any or many of the requirements be it functional or non-functional, the stakeholders requests. Therefore when designing a good architecture, one should be very careful when laying the foundation.

Keep in mind the following non-functional requirements when you're designing the initial architecture of your application.

Scalability


High Scalability has many practical case studies. It is important to keep in mind how much scalable your application is going to be in coming milestones. Size of codebase also matters

  • Scale up (Increase power of hardware)
  • Scale out  (Increase no. of hardware)
Scalability of Django. This video demonstrate how Instagram scales.

Instagram has a caching(memcache) mechanism between database and the client. Whenever user is served it keeps it in the cache as well as update primary and secondary storage.



Read What is scalability for more information


Performance

This is a key fact when the application grows larger. This might not matter initially but it should be kept in mind as the application grows. Some considerations for performance are,

  • Perceived performance (Fluent Conf 2017 - Video)  : Measure of How Quick a User Thinks Your Site Is. 
    • If you look at some websites it first loads the content placeholders which is mainly html and then only loads the actual data which takes time
    • Applicable for mobile apps as well. First loads the placeholder before loading data from server
  • Bundle & minification : Reduces the size of files that needs to be downloaded
  • Caching & content delivery networks
  • Optimizing image usage

Web Performance: Leveraging the Metrics that Most Affect User Experience (Google I/O '17)

Re-usability

Make sure to design common things in such a way that they can be reusable.

Supportability

What devices is your application going to support in future? Can the architecture be designed in a way that it supports future requirements of new devices?

See - Azure Design Guideline

There are lot of other things which should be considered when designing an architecture. But most importantly,

"make sure to think through cost and the benefit for every decision you make."

Wednesday, February 1, 2017

Tuesday, January 31, 2017

Getting Started with Azure CDN

For a better user experience and a faster delivery of content from server to client, both caching and CDN (content delivery network) comes hand in hand. When considering performance it is important to use both of  these techniques for better user experience (See Caching vs CDN - Stackoverflow).

CDN can be used to cache static web content to provide content faster to end users. It caches content in physical nodes across the globe.

Watch this video to understand how to link a storage account with Azure CDN.



Resources
https://azure.microsoft.com/en-us/blog/enabling-cdn-for-azure-websites/
https://docs.microsoft.com/en-us/azure/cdn/cdn-create-new-endpoint

Wednesday, January 25, 2017

Catch these things in EF Core

            var b = _context.Tasks.Include(j => j.TaskItems).Include(j => j.Creator);

TaskItems is an ICollection in Task object, hence it'll execute separately in SQL Server. Since Creator is a 1 to 1 mapping, It'll do a inner join with Task.


            var a = _context.Tasks.Include(j => j.TaskItems).ThenInclude(j => j.Status);

First tasks will be queried. Then in another query, TaskItems will be left joined with Workflow status. To map with Tasks, Where query will be appended with Exists, which will map Tasks and TaskItems


Thursday, January 12, 2017

Microservices what is it really

Image Credit : Contentful

Microservices is a architectural pattern where a structure of an application is decomposed as collection of loosely coupled services. These services are responsible for handling separate business capabilities.

Microservices helps software teams to continuously deliver large scale complex application in pieces. (Should you use microservices)

We all can search and find theories of microservices, but practical use cases and practical issues are what most of us will be interested in espeically when such resources are rare. So I thought of organizing this page to list some concerns involved.

Image Credits : Bhagwati Malav (via. Medium)

Problems with Monolithic Architecture

Traditionally monolithic architecture is used for many software's but it generates bigger problems with time.

  • Involves a single code base which increases code complexity, learning curve, maintainability, dependencies
  • Overloads IDE since there's only single code base
  • Difficult continuous integration since all application is a single one
  • Scaling is linear. Since there is no modularity all modules comes as a single package. Cannot scale different modules separately based on the requirement (Even if module A gets used 99% and B 1% both will be handled via. same infrastructure) 
For smaller teams most of the time monolithic will be the way to go. Consider microservices if you  have previous experience but not because you want to try it. If your application tends to get bigger , much complex or if you encounter a non-functional business requirement such as one part of the application need higher performance consider using microservices. This is because separate services can scale independently. Note that what can be done in monolithic can be done in microservices as well.

Patterns in Microservices

There are patterns which can be used with Microservices.

API Gateway (source)

There could be requirements from front-end to have an API which would access multiple microservices to retrieve data. Solution here is to create a separate API Gateway which would access required microservices and give what you need. 

API Composer is when you need to query multiple services where services uses Database per service pattern. API Gateway often does API composition as well. 


Microservices in Azure - Service Fabric

https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-overview-microservices
https://azure.microsoft.com/en-us/blog/microservices-an-application-revolution-powered-by-the-cloud/
https://docs.microsoft.com/en-us/azure/service-fabric/

Case studies
https://blogs.msdn.microsoft.com/azureservicefabric/tag/case-study/

Authentication in Microservices

https://stackoverflow.com/questions/29644916/microservice-authentication-strategy

Microservices - Case Studies






Sunday, January 1, 2017

ASP.NET Core Request Pipeline

With ASP.NET to ASP.NET Core lot of things has changed. ASP.NET had a request processing pipeline with lots of events such as BeginRequest, EndRequest etc. With Core the architecture was changed.

This is how ASP.NET Core application is initialized



ASP.NET Core now has the concept of Middlewares. You can have many middlewares as you need and each of them will execute one after the other.

Fundamentals of Middleware

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.2

You can also write your own custom middleware

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2

Thursday, December 22, 2016

How Default Constructor Works in C#

Whenever a class or struct is created, its constructor will be called. Constructors enables developer to set default values and limit initialization. 

If the constructor is not provided, C# will instantiate default constructor and will assign default values to the member variables. Since value types cannot be null, they will be assign with default values while, Since reference types are null by default they will be assigned with null (Note that regardless of been value or reference type, local variables are not automatically initialized). 

Here .ctor is the shorthand for constructor called in IL (Intermediate Language). As you can see from the above screenshot, you can use free disassembler like ILSpy to view disassembled code.  

If you provide a parameterized constructor, the empty constructor will not be generated.



The purpose of user defining a parameterized constructor is to add some logic when initializing the class, if the compiler automatically adds a empty constructor, users can bypass the some logic in parameterized constructor class. That's why empty constructor is not generated.

Constructor can use base keyword to call the constructor of the base class. (for further details, see Using constructors).

If you try to invoke base default constructor and haven't specified it in the base class you will get 'does not contain a constructor that takes 0 arguments' error.

Static classes can have static constructors to initialize static data. It does not have parameters, and the constructor cannot be called directly. It'll be called automatically. Basically user does not have any control over it. (DotnetPerls)
  
Structs can also have constructors (link2). 

Private constructor is a special type of constructor. It is generally used in classes which contain static members only. Static constructor is used to initialize any static data, or to perform any action which should be performed only once.

Wednesday, July 6, 2016

What is Lean

The core idea of lean is to maximize the value provided to customer while minimizing waste as possible (What is lean). With fewer resources as possible. Lean is mainly goes together if you have uncertaninty in what you're delivering where early feedback is important. 



1. Identify Value (End Goal)

Value is what customer gets in the end. Value should always comes from customer because that is what he'll be expecting end of the day. What is the price point. Why this is important. Identify value is important for better delivery to the customer.

2. Map the Value Stream

After values are identified next step is to map the steps of your work process. Value stream may not give a direct benefit to the customer but will help deliver the final product/service. 

A benefit of value stream mapping is identifying places where you can improve and eliminate and identifying places needs improvement (waste). This could be code, a performance issue etc.


3. Create flow

After eliminating waste next is to creating a flow to make sure things go smoothly

4. Respond to customer pull

With improved flow time to market can be drastically improved. This means customers can pull whenever they want to unlike before. 

5. Perfection

Steps 1 to 4 will not sustain if you don't perfect this approach radically. It is important to identify bottlenecks, improvements, learning from these and continue to perfect the model

Difference between Lean and Agile (by CA technologies)




Resources


Wednesday, May 4, 2016

Tuesday, February 2, 2016

Sri Lankan IT Industry Statistics and Trends

It is said that fourth largest exporter of services in Sri Lanka is the IT industry. But is it getting the place it deserves? Here's a quick look at GDP of few countries and How much Information Technology Industry earns for the respective countries. 

Sri Lanka GDP (2013) - $67.18 billion
Sri Lanka IT industry (2015) - $700 - $800 million

India GDP (2013) $1877 billion
India IT industry (2015) $147 billion (source)

USA GDP (2013) $16770 billion
USA IT industry (2011) $646 billion (source)

Sources
http://www.slasscom.lk/why-sri-lanka
http://www.slasscom.lk/sites/default/files/Sri%20Lankan%20IT-BPM%20Industry%20Review%202014.pdf

Saturday, July 18, 2015

ASP.NET MVC Controller Actions

MVC Actions usually returns instance of a class which derives from ActionResult. But you can return any type of object from MVC action even objects. These return types are wrapped in appropriate ActionResult type before they are rendered in response stream.


There are few tricky things you need to understand when dealing with HTTP methods and Controller actions. The most basic form of returning a result from controller action is like below,


The return type Json above is just an extension method which returns JsonResult. There is no difference between returning Json and JsonResult

The above ReturnJSON() and GetAction() actions cannot be called via. a GET request. You'll get the following 500 internal server error.


You can read more about that here and here. But you can use HTTP methods like POST or PUSH to successfully call the ReturnJSON action. But since GetAction() is decorated with HttpGet attribute you can't call it using POST. If you try you'll get 404 not found error. 


You can get GET request work when you do like below. Not only GET, this allows you to do POST, PUT requests as well. 

You can do the following only to allow GET requests or POST requests.

Resources

Saturday, May 9, 2015

Application Pools in IIS

Application pool is a way to manage multiple web applications under IIS server. App pools allows you to isolate applications with different security controls from one another. It helps you to manage your applications separately. 


IIS Worker Process
Is a Windows process (w3wp.exe) which runs web applications. It is responsible for handling requests for a specific application pool. App pool can contain more than one worker process. This is known as web farm or web garden. Read here

Application Pool Recycling
To make the application running smooth without memory leaks you need  to recycle the application pool. Any code which failed to implement IDisposable would run finalizers which will release resources.


Identity

Application Pool Settings (General)
  • .NET CLR Version
    • This should correspond to appropriate version of .NET framework version of your application
  • Managed Pipeline Mode
  • Queue Length
    • Max No. of requests HTTP.sys will queue for the app pool. When queue is full you'll get 503 "Service Unavailable" error
  • Start Mode : OnDemand or Always Running. See (SimpleTalk - Speeding up your application with Auto-Start feature)

Resources

Friday, May 1, 2015

LINQ in Entity Framework

To retrieve lists from database you can use IEnumerbale<T> or IQueryable<T> interfaces. IQueryable allows you to do LINQ-to-SQL while IEnumerable<T> is LINQ-to-Objects. Both gives you the opportunity to do deferred execution. (Read this article for more).

In IEnumerable all objects matching the original query will be loaded to the memory from database. 

Above first and last LINQ statements will generate first SQL query while second LINQ expression will generate the second query below,

LINQ First and FirstOrDefault


LINQ Single and SingleOrDefault


LINQ Any
Note that Count will iterate all the records in the table while Any will stop at first record it finds. (source)

LINQ Count and LongCount



The difference between Count and Count_Big is latter returns bigint while count returns int. See more details on data types.

LINQ Contains




















Group by

Saturday, February 7, 2015

Introduction to ReactJS


React is a JavaScript library developed by Facebook. ReactJS focuses on,
  • UI : Use React as the V in MVC
  • Virtual DOM : DOM diff implementation for high performance
  • Data flow : Offers reactive data flow
React is all about building reusable components. (Why Facebook built react). It doesn't manipulate DOM unless it needs to (check react displaying data example). It uses a fast, internal mock DOM to perform diffs and computes the most efficient DOM mutation for you. React components can only render a single root node. If you want to return multiple nodes they must be wrapped in a single root. Why React's Virtual DOM concept is more efficient than dirty model checking. Also check how Virtual DOM and diffing works in React.

Why use Reactjs


Here's a simple hello world example. Here, React.createClass will create a Component. (Read more)

var App = React.createClass({
            render: function () {
                return React.DOM.h1(null, "Hi there");
            }
        });
React.render(App(), document.body);

JSX

React believes components are the right way to separate concerns rather than using templates. JSX enables you to create JavaScript objects using HTML syntax.

const element = <h1>Hello, world!</h1>;

JSX is similar to HTML, but not exactly the same. See JSX Gotchas and JSX in depth. You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.

JSX elements gets converted to react elements with Babel. Same as what you create using React.createElement method. Therefore you can only have single root tag for a JSX statement.

React can either render HTML tags (strings) or React components (classes). React JSX transforms from an XML-like syntax into native JavaScript. 


Components and Props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

Loading Ajax data using JQuery

In Load Initial Data via AJAX example, you can see how to load data from ajax call and show them in the browser. We use JQuery here to make things easier. Typical error you'll get when implementing is mountNode is not defined error.

React integration with C# and ASP.NET MVC

You can use ReactJS.NET to integrate your .NET application easily. Take a look at this sample tutorial.



What is Flux

Architecture Facebook uses internally when working with react. It is now recommended to use Redux over Flux

https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture
http://facebook.github.io/flux/docs/overview.html
http://facebook.github.io/flux/
https://www.youtube.com/watch?list=PLb0IAmt7-GS188xDYE-u1ShQmFFGbrk0v&t=621&v=nYkdrAPrdcw


Why use Redux

Redux has many benefits. Simply Redux is a state management tool. It is a very lightweight library which can be used with many JavaScript frameworks. 

Simply Redux keeps state of your application in a store. Each component can access any state that is needed from the store. So why use Redux? As React is based on components, these needs to communicate with each other. Redux helps you by keeping it in a central location. 

Redux has three building parts: actions, store and reducers.
  • Actions are events: They are the only way you can send data from your application to your Redux store. The data can be from user interactions, API calls or even form submission.
  • Reducers: Reducers are pure functions that take the current state of an application, perform an action and returns a new state.
  • Store: The store holds the application state. There is only one store in any Redux application.

Monday, December 29, 2014

C# - Classes and Structs

Classes and structs encapsulates set of data and behaviors into a logical unit. A class is a reference type while struct is of value type. When a struct is assigned to a new variable it is copied. Struct is like a light-weight class. (Read)


Note: the new operator is used to create and invoke objects. The new operator doesn't mean it is a reference type. It says the type has a constructor. All value and reference types has constructors at least the default one. (SO).

int i = new int(); equals to
int A = new int(); or int A = default(int);

Encapsulation defines how accessible the members of the classes are to the outside of the class. Class can have fields, constants, properties, methods, constructors, destructors, events, indexers, operators as well as nested types. (See Class members article)

When defining a struct if you're adding a parameterized constructor, you must initialize all fields in that (Source). Also it is not a good practice to use mutable structs. See examples of mutable structs. 

Inheritance : Classes support inheritance. A class can derive from another class (base class). Structs does not support inheritance because it is of value type. Classes can be declared as abstract meaning, one or more methods have no implementation. Classes and structs can inherit multiple interfaces. 
See : Why structs cannot be inherited, Why structs needs to be boxed

Generic Types : Classes and structs can be defined with one or more type parameters.

Static types : Classes can be declared as static while structs cannot. A static class can only contain static members and cannot be instantiated with new keyword. Both classes and structs can contain static members

Nested types : class and struct can be nested within another class or struct. (See Nested Types - MSDN)

Partial classes : You can also define a class in two files using partial

Object initializers : You can instantiate class or struct object without explicitly calling the constructor.  (MSDN)

Anonymous types : When it is not necessary to create named classes, you can use anonymous types. (See Anonymous Types in C# Programming guide)

var msg = new { Id = 108, Message = "Hello" };

Anonymous types are typically used in select clause of query expressions (LINQ). Anonymous type can contain  one or more public read-only fields. It cannot contain anything else (such as methods, event handlers etc.). 

Extension methods : You can extend a class without creating a derived class by creating separate types using extension methods.

Implicitly typed local variables : You can use these variables to instruct the compiler to determine correct type at runtime. (See implicitly typed local variables)


Resources
https://roslyn.codeplex.com/discussions/568824
http://programmers.stackexchange.com/questions/92339/when-do-you-use-a-struct-instead-of-a-class

Wednesday, October 8, 2014

Saturday, September 27, 2014

Overview of OWIN and Project Katana

owin and katana
Image credit : MSDN


Historically ASP.NET architecture (System.Web.dll) was coupled to a specific web hosting option IIS. To separate this, ASP.NET MVC was released as an independent download.

Then Microsoft built ASP.NET Web API such that it had no dependencies on any of the core framework types found in System.Web.dll. therefore it had no dependency on IIS and could be run in a custom host (console application, windows service etc. )

OWIN (Open Web Interface for .NET)
OWIN decouples the coupling between web server and the application. Inspired by the benefits achieved by Rack  in the Ruby community. OWIN has two core components. OWIN is not an implementation, it is just a specification. 

Environment dictionary
  • This data structure is responsible for storing all of the state necessary for processing an HTTP request and response. 
  • An OWIN-compatible Web server is responsible for populating the environment dictionary 
  • It is then the responsibility of the application or framework components to populate or update the dictionary with additional values
  • OWIN specification defines a list of core dictionary key value pairs
Application delegate
  • Is a function signature which serves as the primary interface between all components in an OWIN application
  • Function accepts the environment dictionary as input and returns a Task
  • The asynchronous design enables the abstraction to be efficient
Katana
Katana cloud optimizes your ASP.NET applications. The Katana project represents the set of OWIN components that, while still open source, are built and released by Microsoft.




Resources

Understanding Deferred in JQuery

Simplest example of ajax request in JQuery.

        $.ajax('http://ip.jsontest.com/', {
            success: function (result) {
                console.log('success');
            },
            error: function (err) {
                console.log('error');
            }
        });

Result of success callback function will have 3 parameters, which are "Anything (any type of) data, String textStatus, jqXHR jqXHR".


You can check the state of jqXHR object using jqXHR().state(), If you check with beforeSend event, you can see the state is pending before request is sent. Sometimes you'll get “No 'Access-Control-Allow-Origin' header is present on the requested resource” error.

$.ajax also returns jqXHR object. You can assign multiple callbacks to this.

        var a = $.ajax({
            url: 'http://jsonplaceholder.typicode.com/posts/1',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log(data);
            }
        });

        a.done(function (result) {
            console.log('done : ' + result);
        });

        a.then(function (result) {
            console.log('then : ' + result);
        });

        a.error(function (result) {
            console.log('error : ' + result);
        });

here after sending the ajax request, the object immediately returns and other callbacks are attached. Still the ajax state is pending, If success callback get hits, state becomes resolved and then callbacks are called.

If it hits error state is rejected. done or then callbacks won'get called but error callback will get called. then() can also have failCallback attached like below,

        a.then(function (result) {
            console.log('then : ' + result);
        }, errorCallback);

        function errorCallback(err) {
            console.log(err);
        }

If you specify this, errorCallback will get called if an error occurs.

jQuery.when()
accepts one or more objects and provide a way to execute callback functions. Usually deferred. If single Deferred is passed, its Promise is returned.

            function ajaxCall() {
                return $.ajax({
                    url: 'http://jsonplaceholder.typicode.com/posts/1',
                })
                .done(function (data) {
                    console.log(data);
                })
                .fail(function (data) {
                    console.log(data);
                })
            }

            function function2() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(function2);

If a single argument is passed to $.when which is not a Deferred or a promise, It'll be treated as resolved and attached callbacks will be called. Above if you don't return anything from ajaxCall(), a will be resolved and function2 will be executed without waiting for ajaxCall to be finished. Since your Deferred never gets rejected, fail callbacks are never get called. If Deferred resolved with no value, callbacks will get undefined value.

If you return ajax, a will be at pending state until ajaxCall() is finished and then only function2 gets executed.

deferred.then()
Add handlers to be called when deferred object is resolved, rejected or pending.

If we expand on the example above, here you can attach fallCallbacks as well.

            function failPath() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(happyPath, failPath);

deferred.done()
Handlers to be called when deferred object is resolved

        var defer = $.Deferred();
        defer.done(function (val) {
            console.log(val);
        });

        defer.then(function (val) {
            console.log(val);
        }, function (val) {
            console.log(val);
        });

if defer.resolve()
done callback and then's done callback will be called

if defer.reject()
done callback won't get called. then's fail callback will get called.

You can check active Ajax requests using $.active function. See this


Thursday, August 21, 2014

Abstract in C#

In this article, we'll look at what abstract in C# is. Also we'll look at 
when and how you can use it to get its benefits.


In C# abstract modifier indicates that the thing being modified has a missing or incomplete implementation. This modifier can be used with classes, methods, properties, indexers and events. 

Abstract classes can contain both abstract and non-abstract members. Abstract member cannot exist outside an abstract class. You can instantiate abstract class by making a concrete class deriving from it (An instance of a derived class is also a instance of its base class). 

Also you can't create abstract constructor because abstract means you must override it in any non-abstract child class. But you can have non-abstract constructors. You can't override a constructor. You can't create sealed abstract classes. 

You cannot have non-abstract method signature inside abstract class. For non-abstract methods you must provide implementation (link). You cannot have private virtual or abstract members inside a abstract class. But You can have non-abstract private methods inside abstract classes.



Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook