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.



Saturday, August 2, 2014

Execution Context Best Practices in JavaScript


In this article we'll see what this means, and places where this is applicable. 
We'll also look at how to manipulate this with built-in functions like 
apply, call and bind.

Every JavaScript statement is executed in one execution context or the other. In it's simplest terms this refers to the "owner"  of  the function we currently executing. this helps us to get the object or the execution context we are currently working with.

In the above example both func1 and func2 returns this. because f1 was called (executed) inside the window (or global context) func1 returns window. In f2 we are using strict mode. In strict mode, this will be whatever it's set to when entering the execution context. Since we have not defined this, it will remain undefined. We can set that to any value we want. Even null. 

Saturday, July 26, 2014

Hidden Secrets of Interfaces in .NET C#

Interface contains definitions for a group of related functionalties that a class or a struct can implement. Interface in C# is similar to an abstract class in which all methods are abstract (Why C# interface methods not declared as abstract). 

Interface can contain methods, properties, events, indexers but it can't contain constants, fields (why interface can't have fields), operators, instance constructors or types. Interface members are automatically public and cannot be static. (interfaces in MSDN)

When a class or struct implements an interface, it must provide an implementation for all the members that interface defines. If you implement an interface method in a deriving class it must be public. When a base list contains base class and interfaces, base class must come first in the list. 

Methods in interfaces can have optional parameters. But they are not enforced in implementing classes

Any class or struct that implements IEquatable<T> interface must contain definition for an Equals method. Also note that Reference types doesn't benefit much when using IEquatable.

Importance of an interface
Covered in SO, SO, Here 

An interface can inherit from one or more base interfaces. See Composition over Inheritance.

Explicit interface implementation 

Problem : Class implements 2 interfaces has a member with same signature
Solution : Explicit interface implementation



Friday, July 25, 2014

How to Asynchronous Programming in C#

async and await are the main keywords in asynchronous programming. You can use asynchronous with things such as downloads, uploads etc.


Below example shows you how to get a specific Http Header asynchronously.

  • Name of async method by convention ends with async. 
  • Return type is one of the following,
    • Task<TResult>
    • Task
    • void
  • Method has at least one await expression
Resources

https://msdn.microsoft.com/en-us/library/hh191443.aspx

Wednesday, July 9, 2014

Covariance and Contravariance in Generics

Covariance

Enables you to use more specific type than the type originally specified.

IEnumerable<Derived> d = new List<Derived>();
IEnumerable<Base> b = d;

Contravariance

Enables you to use more generic type than the type originally specified.

Action<Base> b = (target) => { Console.WriteLine(target.GetType().Name); };
Action<Derived> d = b;
d(new Derived());
Examples from MSDN.


Resources
https://msdn.microsoft.com/en-us/library/ee207183.aspx
http://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-world-example

Tuesday, July 8, 2014

Introduction to Entity Framework

Entity Framework (EF) is an object-relational mapper (ORM) for .NET. Entity Framework can be used to work with relational data using domain-specific objects. Entity Framework eliminates need for data access code that programmers usually need to write. The codes you write with Entity Framework will be converted to SQL queries. 

You can view them using ((System.Data.Objects.ObjectQuery)result).ToTraceString(); 
ObjectQuery class is the base class for queries against a conceptual model. There's also the ObjectQuery<T> generic class. 

Architecture of Entity Framework



Above diagram shows the high-level architecture of the Entity Framework. Conceptual model contains model classes and there relationshps this is independent from the actual tables in the database. For details of other components in the above diagram see this.

You can also check Entity Framework Overview available in MSDN

Workflows

In Entity Framework there are 3 workflows developers can use to start with. They are Model First, Database First and Code first. All of these has its own pros and cons so understanding the differences correctly is important.

Model First

Using Model First approach developers can create the Database model using ORM designer in Visual Studio. Here the designer relies on the .edmx file designer to maintain the design specifics. 

The physical database will be then generated from the model.

Database First

Using this approach you can reverse engineer a model from an existing database. The classes are automatically generated from EDMX file. Read Entity Framework Database First Example for steps.

In the wizard for creating the model, you'll get checkboxes to select Pluralize or singularize generated object names option. Read more about it here.  

Code First

Create classes first and generate Database from the classes directly. No use of Entity designer at all. 

Choosing the suitable workflow

Understanding which workflow to use is important before you start developing data access applications using EF. 

http://blog.smartbear.com/development/choosing-the-right-entity-framework-workflow/
http://msdn.microsoft.com/en-us/library/vstudio/cc853327%28v=vs.110%29.aspx  

Data Persisting in Entity Framework

Entity Framework use Unit of Work pattern to persist data. 

Monday, July 7, 2014

What is ASP.NET Core

ASP.NET Core (previously known as ASP.NET VNext and then ASP.NET 5is the next version of ASP.NET. Unlike its predecessors, Core is is open source available on github.

Here are some of the features

  • Open source and cross platform
  • Can run on .NET core or on full .NET framework
  • Leander and modular
  • ASP.NET Core is no longer based on System.Web.dll it is now based on NuGet packages
  • Built-in dependency injection
  • New light-weight and modular HTTP request pipeline

Wednesday, May 7, 2014

Understanding IEnumerable and IQueryable in C#

IEnumerable<T> is the base interface for collections in System.Collections.Generic namespace. IEnumerable<T> exposes the enumerator which supports iteration over a collection of a specified type. For non-generic types .NET has another interface called IEnumerable. See the difference between IEnumerable<T> and IEnumerableIEnumerable<T> has a single method GetEnumerator which you must implement when implementing the IEnumerable<T> interface. This returns a IEnumerator<T> object.



IQueryable<T> provides functionality to evaluate queries against a data source. This exists in System.Linq namespace. This inherits IEnumerable<T> interface thereby if it represents an query it can be enumerated. Enumeration forces associated expression tree to be executed.




Difference between IQueryable<T> and IEnumerable<T>
Both will give the ability for deferred execution but IQuerayable allows you to LINQ to SQL while IEnumerable does not. IEnumerable only allows LINQ to Object. IQueryable if possible will execute on database. 

AsEnumerable
Allows you to cast a specific type to its IEnumerable equivalent. In LINQ you can use this to run part of the query in SQL and the other part in memory as LINQ to Objects. One reason because when execute in memory we have more methods to work with than in database. (Ref)


AsQueryable
Converts IEnumerable to an IQueryable.

When exposing any of these interfaces to a client, the developer should design the API such that only the required details are exposed to the outside. 
Source - Stackoverflow
Also see questions for IEnumerable under stackoverflow

IEnumerable<T> has lot of extension methods. Check them here.

Provides a set of static methods for querying objects that implements IEnumerable<T>. This can be found under System.Linq namespace.

Enumerable.Empty<TResult>
Returns an empty IEnumerable<T>. 

Monday, March 10, 2014

Deferred in JQuery

Web applications are kept alive by data. These data usually retrieved from data sources. AJAX (Asynchronous JavaScript and XML) is a technique used to communicate with web servers to send and receive data asynchronously. Often you'll send a ajax request, wait for data to come inside callbacks and execute rest of the flow. Ajax uses XMLHttpRequest object to communicate with server side.


XMLHttpRequest object
Is used to exchange data between client and server. Using this you can update web pages without reloading or send data to server in background.

Below is how you can create a simple ajax request using jQuery. You can pass object to as a parameter which contains settings for the ajax request. jQuery.ajax() will return a jqXHR object. jqXHR is a superset of native XMLHttpRequest. As of jQuery 1.5, jqXHR object implements the Promise interface.

There are variety of options you can use to customize the ajax requests.



Also you can use jQuery.ajaxSetup() to set defaults for future Ajax requests but using this not recommended.

When you have multiple ajax requests to send you'll need some mechanism to chain them to have correct sequencing you desire. Also you'll need to make the requests asynchronously to make browser not getting freezed (you can make Ajax requests synchronous but it is not advisable). in jQuery you can use Deferred for this.

The Comparison of Continuous Integration, Deployment and the Delivery


What appears in title seems familiar? It should because these are the concepts (or you can say techniques) we use to deliver our products to stakeholders. Even though Continuous Delivery, Continuous Integration and Continuous Deployment are the buzzwords today most people often misunderstands the difference among each. 

First we'll look at what each of these are,..

Continuous Integration

Requires developers to integrate code into a shared repository or branch frequently. Each check-in of code is verified by an automated build. The idea here is to detect problems early.

Advantages

  • Detect issues early and address them
  • No more long integration processes
  • Quick stakeholder feed backs
  • You can make sure your product is stable

Continuous Delivery

This is deploying into a environment but to a set of users which can be QA or some customers for continual review and inspection. This is somewhat similar to Continuous integration but this can feed business logic tests which cannot be automated always. Continuous delivery ensures that the product is always in release-ready state.

Continuous Deployment

Deployment or release the code to production environment as soon as its ready. Any testing is done prior to merging and in a production like environment. This should be a automated process where anyone could do it.

After a deploy logs must be inspected to detect if the key metrics are affected (such as response time). See how Atlassian do continuous deployment.

http://guides.beanstalkapp.com/deployments/best-practices.html

References


image credit : qubiz.com

Saturday, March 1, 2014

Performance tuning JavaScript

In this article we'll look at what is performance
why it is important, different ways of tracking performance issues 
and ways to solve them.



What and why performance is important?


Performance tuning is very important when an application gets larger. But it can be very crucial to retain the value of the software. When developing JavaScript applications there are variety of tools which you can use to tune the performance of a web application.

Memory can be held by an object in 2 different ways. directly by the object itself or implicitly by holding references to other objects. 

Different types of performance issues exists!
Memory leaks 
Memory leak is a gradual loss of available computer memory. 

Identifying performance issues

Before do any kind of performance tuning you need to identify what are the performance issues I have. You can use different tools and mechanisms to identify existing performance issues like memory leaks. 

Using Chrome Developer Tools for profiling

Use timeline in Developer tools to do profiling. Start with reading this introduction

Things to take

Memory leaks in JavaScript is based on reference counting
See JavaScript memory profling with Google Chrome


Using timers

Measure time to execute a function (SO) 



Using Google Chrome
finding JavaScript memory leaks with Chrome (SO)

You can also use V8 benchmark suite to profile JavaScript performance and identity bottlenecks. Checkout this link for more information. 

Not only in Google Chrome, but there are tools available in other major browsers as well. 

Writing memory efficient code is another important thing. You can also optimize existing JavaScript code in different ways.

Memory management in JS
http://stackoverflow.com/questions/23506064/how-do-you-detect-memory-limits-in-javascript
http://stackoverflow.com/questions/2936782/javascript-memory-limit

Performance of popular JavaScript MVC frameworks
http://www.filamentgroup.com/lab/mv-initial-load-times.html

Tips from W3Schools
Best way to profile JavaScript execution DOM interaction is expensive
http://andyshora.com/how-bad-is-dom-interaction-javascript.html 
http://stackoverflow.com/questions/8750101/multiple-small-dom-operation-vs-one-large-dom-operation 
http://stackoverflow.com/questions/6022396/too-many-dom-elements?rq=1
http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
http://www.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
 
image credit : devbridge


Monday, February 24, 2014

Data Validation in Entity Framework

Validating data is important to make sure bad data is not getting into the system causing unnecessary troubles. When developing applications using Entity Framework, you can use features in .NET and Entity Framework to ensure only valid data will flow through it. Here we'll see what features we can use with Entity Framework to do our job

Using Data-Annotations

Data-Annotations are attributes you can add to property or a class. Data-Annotations are not a feature comes with Entity Framework. It's a feature of MVC. You must add System.ComponentModel.DataAnnotations to use this. 


IValidatableObject

Its is an interface which can be applied to a class. 

ValidateEntity


DbUpdateException

Exception throws by Entity Framework when updating to the database gets fails

References



updated November 2014
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