Thursday, November 28, 2013

Dependency Injection

Simply Dependency Injection means giving an object its dependencies, instead of them itself having initializing them. Dependency Injection is useful for testing as well. Because it allows dependencies to be mocked or stubbed out. 

Types of Dependency Injection ##

Constructor injection
Setting dependencies through constructor

Setter injection
Setting dependencies using Setter method

Interface injection 


http://stackoverflow.com/questions/12246438/constructor-injection-and-initialization-of-dependencies-being-injected
http://programmers.stackexchange.com/questions/190120/should-i-use-dependency-injection-or-static-factories


What is a Dependency Resolver
Allows you to abstract away Dependency Injection implementation 
http://stackoverflow.com/questions/20086440/asp-net-mvc-4-dependency-resolver

What is interception


You can use Unity for Dependency Injection in .NET. Read this comprehensive article set on unity.

Dependency Inversion in JavaScript

http://stackoverflow.com/questions/5349003/dependency-inversion-principle-in-javascript

Resources

https://www.youtube.com/watch?v=FuAhnqSDe-o

http://stackoverflow.com/questions/13442312/when-do-i-use-abstract-class-or-interface-in-dependency-injection

http://stackoverflow.com/questions/13442312/when-do-i-use-abstract-class-or-interface-in-dependency-injection

https://richnewman.wordpress.com/about/code-listings-and-diagrams/dependency-injection-examples/dependency-injection-example-interface-injection/


Wednesday, November 13, 2013

Other resources for Entity Framework


Difference between Eager loading and Lazy loading


http://stackoverflow.com/questions/3485317/entity-framework-4-single-vs-first-vs-firstordefault


Bulk Inserting in Entity Framework
http://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
http://stackoverflow.com/questions/6107206/improving-bulk-insert-performance-in-entity-framework

...............

  • By default, EF interprets a property that's named ID or classnameID as the primary key
    • using ID without classname makes it easier to implement inheritance in the data model
  • Navigation properties are typically defined as virtual so they can take advantage of certain EF functionality such as lazy loading. 
  • DatabaseGenerated is an attribute you can define on primary key. It says you'll manually enter the primary key rather than Database generating it.
  • The main class that coordinates EF functionality for a given data model is the database context class.
    • You create this class by deriving from System.Data.Entity.DbContext class
    • In your code you specify which entities are included in the data model

    • This code creates a DbSet property for each entity set. In EF, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.
    • Above, SchoolContext is the name of the connection string you define in Web.config
      • You can also pass the connection string itself (link)
      • If you don't pass anything to base, EF assumes the connection string name is the same as the class name
    • You can write a Seed method for EF to generate data


Useful methods

ObjectContext.SaveChanges()

Persists all updates to the data source and resets change tracking in the object context. Returns no. of objects in an added, modifled or deleted state when SaveChanges was called

link1, link2, link3


Configuring Entity Framework
You can configure entity framework options from the config file. Starting from EF 6 you can use Code based configurations.

sources

Monday, November 11, 2013

Interesting Findings ASP.NET

HttpClient
Use HttpClient for Downloads. It is a new feature. Makes it easier to download files in a separate thread.
Handling 404 in ASP.NET MVC Correctly (SO)  

HttpServerUtility (MSDN)
Provides helper methods for processing Web Requests. Methods and properties of HttpServerUtility are exposed through Server property  of HttpContext.


Working with Images in ASP.NET MVC (SO)

ASP.NET Scaffolding
It is a code generation framework for ASP.NET web applications. Scaffolding can make your development time less. See  the overview from ASP.NET

Automatic Deployments
You can do automatic deployments to IIS using Micrsoft Web Deploy. Chcek ScottGu's article on that. 

JSON Formatting
Razor View Engine


Dependency injection with Unity

http://www.asp.net/web-api/overview/advanced/dependency-injection

Saturday, November 9, 2013

Interesting Things on C#

Func vs Action

  • Func returns values from the delegate (LINQ .Where())
  • Action does not return anything (LINQ Foreach())

Fluent interfaces

https://www.simple-talk.com/dotnet/.net-framework/fluent-code-in-c/


Asynchronous Programming 

Using async and await 

Fluent validations


https://fluentvalidation.codeplex.com


IDisposable interface

http://stackoverflow.com/questions/6967108/is-idisposable-dispose-called-automatically
http://stackoverflow.com/questions/45036/will-the-garbage-collector-call-idisposable-dispose-for-me
Implementing IDisposable correctly


IDisposable vs Destructor (SO1, SO2)
IDisposable vs finalize (SO, MSDN)

Logging 

https://code.google.com/p/elmah/

Preprocessor Directives (link)
Provides instructions to the compiler. Used to help in conditional compilations.

Type Inference
C# used to be a strongly typed language. You need to specify the type of the variable explicitly. But from C# 3.0 type inference was introduced. with var keyword. This is very useful in LINQ and sometimes also increases  the readability of the program (See here, here and here). var is also called implicitly typed local variable.

Read more here, here (SO), MSDN, var and performance.

dynamic type 
you can use dynamic type to by-pass compile time type checking. It's type can be changed at run time hence these are resolved at run-time. dynamic type behaves like object.

dynamic can be used to make poorly designed external libraries easier to use. See here and here.

MSDN

Tuesday, November 5, 2013

Routing in ASP.NET MVC

Enables you to map URLs that does not map to any specific files in a web site. You should add default MVC routes to Application_Start event in Global.asax file as shown in the example below


check MSDN page ASP.NET routing for more information.



Provides a collection of routes for ASP.NET routing. This class is derived from Collection<RouteBase>. 

You can define custom routes by using RouteBase class. See a tutorial.

introduced in Web API 2 to overcome challenges faced with creating routes with conventional based routings. Uses attributes to define routes.


References

Tuesday, October 22, 2013

Introduction to AngularJS

AngularJS is a pure JavaScript framework. It extends HTML attributes with Directives known as ng-directives. A very basic angular application looks like below,



Here we define the ng-app in which the angular code resides. We add ng-model directive to input for data binding and show it in curly brackets in mustache style in next line. (We usually define a model nested inside a controller. Since we have not done that here it resides in $rootScope). We'll look at some useful things comes in AngularJS next.

Directives (documentation)

These are markers on a DOM element that tells AngularJS's HTML Compiler ($compile) to attach specific behavior to that DOM element. Below are some directives which comes with AngularJS. There are quite a lot of directives comes with the library. You can also create custom directives.
  • ng-app : defines AngularJS application
  • ng-model : binds the value of HTML controls (input, select, textarea) to a property on the scope. 
    • Binds view to a model
    • Provides validation behavior
  • ng-bind : binds application data to HTML view. Tells angular to replace text content inside a HTML element with expression's value
Model Binding (ng-model)
This directive binds an form element to a property on the scope using NgModelController, which is created and exposed by this directive. 

Module

You can configure your module using this.
Constants in AngularJS. You can inject constants to a module.

Dependency Injection
https://docs.angularjs.org/guide/di

Controllers

AngularJS applications are controlled by controllers. Look at the below example,
\
Above MyApp is the name we gave  to the ng-app attribute. We define the controller (SubController) and put it inside the module. After that we can reference it from the DOM. Without adding the controller into the module, we can also keep it global and reference from DOM. but it is not a good practice. Controllers should not have any logic.  


Services

Service is a component that does a specific job like logging, timer etc. Services are wired using Dependency Injection. Services in AngularJS are,
  • Lazily initialized : Instantiated only when a component depends on it
  • Singleton: Components depends on the services gets a reference to the single instance of the service through a factory
To use a service you should add a dependency to that from your controller, service etc. Developers can also create there own custom services.

AngularJS provides services like $route, $window, $location etc. 

Factory

You can create service using Factory as well. Factory and Services are kind of same.

Application Structure and Code organizing

AngularJS projects can be structured in many different ways. Each carries there own pros and cons. It solely depends on what is your requirements are. Following are some useful articles for you to make the decision.  

http://stackoverflow.com/questions/17461242/angularjs-application-file-structure
http://cliffmeyers.com/blog/2013/4/21/code-organization-angularjs-javascript

Angular 1.4 and 2.0

Angular 2.0 is the rewritten version of Angular optimized for mobile and future browsers. It's yet to be released but you can take a look from https://angular.io/. See whats new in Angular 2.0 and this.

AngularJS 1.4 and 2.0 can exist within the same project. See how to do it.

Authentication

https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

The calling order of AngularJS application (link)
  • app.config
  • app.run
    • you can use run block for authentication
  • directive's compile functions
  • app.controllers()
  • directive's link functions

Tips and Tricks

http://demisx.github.io/angularjs/2014/09/14/angular-what-goes-where.html
https://github.com/johnpapa/angular-styleguide

Resources

Saturday, October 12, 2013

HTML5 WebSockets

WebSockets is the next generation bi-directional communication technology for web applications. This operates over a single socket and is exposed via a JavaScript interface. 


var Socket = new WebSocket(url, [protocal] );



The socket starts out as a HTTP request and updates to TCP socket after a HTTP handshake. After that either can receive data. 



Is a real time messaging system build using WebSockets. This is implemented using Node.js. 


Check this getting started guide

Thursday, October 10, 2013

Structural elements in HTML5



<header>

Specifies a header for a document or a section. Can have several header elements for a page. You cannot place header tag within a footer, address or another header

<footer>

Just like header defines a footer for a document or a section. It typically contains author of the document, copyright information etc. You can have several footers

<article>

Specifies a independent, self-contained content. It should make sense of its own. You can typically use article element for Forum posts, blog posts, comments etc.

<aside>

Defines some content aside from the content it is placed in. It should be related to the surrounding content.  Appears in a side

<nav>

Defines a set of navigational links. Not all links of a document should be inside a <nav> element. It is intended only for major block of navigational links (such as menu). Screen readers for disabled can use this element  to determine whether to omit the rendering of this content.

<section>

Defines sections in a document, such as chapters, headers, footers. It's like a div. 

Above I listed basic info about some of the html5 elements. You might be asking yourselves why use html5 elements instead of <div>? These are included in html5 as for the move towards semantic web. Semantic web helps programmers understand the DOM structure better and also allows search engines to have a clear picture about the web page. It also helps screen readers to better parse the content as per there needs.

Media Controls in HTML5

To make our lives easier HTML5 introduced better media support via. <audio> and <video> elements.

You can embed videos in your page using following codes

<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" controls>
  Your browser does not support the <code>video</code> element.
</video>


You can embed several video sources, browser will choose the most suitable one. Below are some attribute you can use with video.

  • autoplay - boolean attribute ; If specified it will automatically begin to play before loading fully.
  • controls - If present, Gecko will offer controls
  • src - URL of the video to embed. This is optional. You can instead use <source> element within video block to specify video to embed
  • height and width is also available
HTML5 Player with Controls

 Like videos you can also add audio to your web page. 

<audio src="/test/audio.ogg">
<p>Your browser does not support the audio element.</p>
</audio>

The src attribute can be a URL or a path to the audio file on local system. 
  • controls - Display standard HTML5 controls 
  • autoplay - Make the audio play automatically
  • loop - Make audio repeat (loop) automatically
  • preload - for buffering large files
    • "none" does not buffer the file
    • "auto" buffer the file
    • "metadata" buffer only the metadata for the file
In both video and audio multiple sources can be specified using <source> element to provide different formats

<video controls>
  <source src="foo.ogg" type="video/ogg">
  <source src="foo.mp4" type="video/mp4">
  Your browser does not support the <code>video</code> element.
</video>

You can also specify the codecs the media file requires. 
<video controls>
  <source src="foo.ogg" type="video/ogg; codecs=dirac, speex">
  Your browser does not support the <code>video</code> element.
</video>
 
You can also control the media element from after getting it using a selector.

var v = document.getElementsByTagName("video")[0];
v.play();
 
source 

Saturday, October 5, 2013

Design patterns for cloud


Strangler pattern

Incrementally developing a newer system replacing the old system. Parts of the old system is replaced with features in new system eventually replacing the complete system. This pattern is mainly helpful for backend systems (API).


Federated Identity Pattern

Delegate authentication to an external identity provider. Simplify the development, minimizes requirements for user administration. 

Cache-Aside pattern
Load data on demand to a cache. Can improve performance.



Monday, September 9, 2013

Introduction to Web API

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. In general, you don't need to know ASP.NET MVC to use Web API.

See this nice poster http://www.asp.net/media/4071077/aspnet-web-api-poster.pdf

Unlike Controllers which inherits Controller base class, Web API controllers inherits ApiController class. You should use Web API if you're creating an API which exposes data. Use Controllers if you're writing HTML based application. (Difference between ApiController and Controller)

Web API Controller actions
Web controller action can return - (See more at asp.net)
  • void (returns 204 - No content)
  • HttpResponseMessage : returns Http Response. 
  • IHttpActionResult : introduced in Web API 2. Simplifies unit testing
  • Other types : Web API uses media formatter
Web API vs WCF (MSDN and SO)

  • Web API supports only HTTP. 
    • WCF Supports multiple  transports (HTTP, TCP, UDP)
  • Web API supports wide variety of media types (XML, JSON)
    • WCF supports multiple encoding types (Text, MTOM, Binary)
  • Web API supports HTTP, Web Sockets, SSL etc. 
    • WCF supports building services using WS-* standards


Routing (web-api-routing-and-actions)
Web API routing is similar to MVC routing. The main difference is Web API uses HTTP method, not URI path to select actions.

Here's a good article from asp.net about creating a RESTful API

Resources

Saturday, August 24, 2013

Control flow in KnockoutJS

foreach binding

duplicates section of markup for each entry in an array. Binds each copy of that markup to array item. You can nest foreach binding with other control-flow bindings such as if and with.

You can use special context property $data, to refer the current array item itself.

You can also use $index to refer the index of current array element. $index is an observable. Similarly you can use $parent to refer to data outside foreach.

Use as option to create alias for the array elements. 

In scenarios like in middle of a list, you can't use foreach binding as above, in such a case you can use containerless control flow syntax which is based on comment tags. 

Note : Destroyed entries are hidden by default. but you can set includeDestroyed option in foreach loop to make them visible. 

if binding

show/hide section of markup based on a condition. This is similar to visible binding.

with binding

Creates a new binding context. Descendent elements are bound in the context of a specified object. with can be used without a container element as well. 

Introduction to KnockoutJS

KnockoutJS is a JavaScript library of MVVM pattern with templates. It does not depend on jQuery. 

With KnockoutJS you can have,

  • Dependency tracking : Automatically update UI when model changes
  • Declarative bindings: Connect parts of your UI to your data model
  • Extensible: Implement custom behaviors

What is MVVM pattern

  • Model : objects and operations in your business domain, this is independent from the UI
  • View Model : Pure code representation of data and operations on a UI. No HTML
  • View: Interactive UI. Representing the state of the ViewModel
Here's a simple example of using KnockoutJS


To achieve two way binding you can use observables. When using observables when you update something in View, changes will be reflected in ViewModel as well.


Explicit subscribing

Used to get notifications when subscribed observable gets changed. You can assign the subscription to a variable and dispose it later.

You can force observables to notify subscribers always by using  
myViewModel.personName.extend({ notify: 'always' });

You can delay change notification by using 
myViewModel.personName.extend({ rateLimit: 50 });

 

Observable Arrays

Just like Observables but for arrays. Observable arrays only track which objects are in the array. Not the state of those objects. Observable array is actually an observable whose value is an array (with some additional methods). Check the documentation for other methods available. For the array also you can delay change notifications like for observables.

 

Computed observables (documentation)

functions that dependent on one or more other observables. Will automatically update when dependencies changes. You can also create writable observables. You can extend this by using rateLimit and notify attributes. 

See complete reference from documentation here


Writable computed observables (documentation

//see the documentation

Pure computed observables (documentation)

This was introduced in 3.2V. Use this if your computed do some calculation and simply returns a value. Here the evaluator does not modify other objects state).

This provides performance and memory benefits. Doesn't maintain subscriptions to its dependencies when it has no subscribers itself.


KnockoutJS - EcmaScript 5 Plugin


http://blog.stevensanderson.com/2013/05/20/knockout-es5-a-plugin-to-simplify-your-syntax/
https://github.com/SteveSanderson/knockout-es5

Friday, August 23, 2013

Using Canvas and SVG in HTML5

Canvas

<canvas> element is used to draw graphics using JavaScript. <canvas> element is only a container to hold the graphics. You must script it to draw the actual graphic.

A canvas is a rectangular area on an HTML page. 

<canvas id="myCanvas" width="200" height="100"

style="border:1px solid #000000;"> </canvas>

Using JavaScript you can manipulate the canvas


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75); 


svg

SVG stands for Scalable vector graphics. They are used to define vector-based graphics for web. SVG defines the graphics in XML format. 

SVG images can be created and edited using any text editor and they can be searched, indexed. SVG images are scalable so it can be printed in high quality at any resolution. 

<svg width="300" height="200">

  <polygon points="100,10 40,198 190,78 10,78 160,198"

  style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>

You now see that in HTML5 graphics there are 2 ways you can go with either Canvas or SVG. comparison between these 2 will be good in understanding which is better

Monday, August 19, 2013

Bindings in KnockoutJS

Visible binding #

Make associate DOM element hidden or visible. Sets yourElement.style.display as none. 


Text binding #

Display associated text value on DOM. Since the binding sets your text value using a text node, its safe to set any string value without risking HTML or script injection. 


HTML binding #

KO sets element's innerHTML property to your parameter value. Don't use this with untrusted model value due to possible script injection attack. 

CSS Binding #

adds or removes one or more named CSS classes to the associated DOM element. 


Styling Binding #

Directly bind CSS styles


Attr Binding #

provides a generic way to set the values of any attribute for the associated DOM element

Saturday, August 17, 2013

Form field bindings in KnockoutJS

the article is incomplete


click binding



When calling your handler, Knockout will supply the current model value as the first parameter. 

Accessing the event object, passing more parameters
Allowing default click action
Preventing the event from bubbling

event binding



 



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