Tuesday, December 24, 2013

Loading Entities in Entity Framework

In Entity Framework you can load data in few different ways,
  • Eager loading
  • Lazy loading
  • Explicit loading

Eager Loading

Here query for a one type of entity also loads other related entities as a part of the query. You can load related entities by using Include method. Include is an extension method.

        List<Employee> employees = context.Employees
            .Include(e => e.Courses)
            .ToList();


        List<Employee> employees2 = context.Employees
            .Include("Courses")
            .ToList();

This will generate a left outer join (See diagram for types of joins) thereby, if no record found it will return null for them.



You can also load multiple levels of related entities. In eager loading, there won't be multiple database calls.  It retrieves all data at once. The downside is, it creates large nested queries which has a performance impact. Therefore avoid using multiple Include statements in a single LINQ query. See Performance considerations. See SO Questions.

Lazy Loading

Loads related entities automatically the first time the property referring the entity is accessed.

Lazy loading and serialization doesn't get together well. Most serializers work by accessing each property of an instance of a type. This property access triggers lazy loading. Therefore it is recommended to turn off lazy loading before serializing an entity. 


Explicit loading

Even with lazy loading off, you can load related entities lazily. By explicitly calling Load method.

References

Saturday, December 21, 2013

DbContext in Entity Framework

Entity Framework, commonly known as EF (latest being EF Core) is a ORM tool which is introduced and maintained by Microsoft.

In EF, DbContext Is the primary class which is used to interact with data as objects. DbContext is often referred to as context. The context class manages entity objects during run time, which includes populating data from database, change tracking and persisting data back to database.  

What exactly is DbContext class?

DbContext is actually a simplified alternative to ObjectContext. Its like a wrapper over ObjectContext. DbContext is the preferred way to interact with Entity Framework. (Is DbContext same as DataContext?). You can get ObjectContext from DbContext using the following code.


DbContext is most commonly used with derived type that contains DbSet<Entity> properties for the root entities of the model. These sets are automatically initialized when a derived type of DbContext is created. You can override protected method OnModelCreating to modify these models. (See Code First Building Blocks).

What is DbSet?

DbSet represents a table or a view in the database. DbSet(TEntity) cannot be constructed publicly. It can be instantiated only through DbContext instance. See DbSet and DbContext. You will be using DbSet to access, insert, update or delete your table data.

Lifetime of DbContext starts when object is created and ends when the object is disposed or garbage collected. By default context manages connections to the database. The context opens and closes connections as necessary. 

DbContext is not thread safe.You can still create multi-threaded applications as long as instance of same DbContext class is not tracked by multiple contexts at the same time. 

Here's some insight of DbContext class. You can find the source code in codeplex.

DbModelBuilder
Used to map CLR classes to database schema. This is mainly used in Code First approach. MSDN


Timeout in Entity Framework
Entity Framework operations have timeouts. The timeout duration is defined by underlying connection providers. You can set the connection timeout in Entity Framework connection string but there is a known bug in MySQL. Therefore you can set timeout in data context.

this.context.Database.CommandTimeout = 180; 


Overridable members in DbContext

Dispose : Usually you don't need to do this. see this article
SaveChanges and SaveChangesAsync : EF6 onwards 
ValidateEntity and ShouldValidateEntity : see this 


Change Tracking POCO entities

In EF, you can track POCO entity changes through change-tracking proxy object or through a snapshot.

When change tracking with proxies, tracking changes in object graph is automatically done by EF. You can disable proxy creation this using below command. Beware that even if proxy creation is enabled, EF will create proxy classes only if the requirements for proxy creation is satisfied.

entities.Configuration.ProxyCreationEnabled = false;

Proxies are created for lazy loading as well. Not only for change tracking

http://stackoverflow.com/questions/7111109/should-i-enable-or-disable-dynamic-proxies-with-entity-framework-4-1-and-mvc3
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
http://stackoverflow.com/questions/26355486/entity-framework-6-audit-track-changes
http://www.entityframeworktutorial.net/change-tracking-in-entity-framework.aspx
http://www.c-sharpcorner.com/UploadFile/ff2f08/working-with-change-tracking-proxy-in-entity-framework-6-0/

Attaching and Detaching Entities

Objects that are attached to ObjectContext can be tracked and managed by ObjectContext. When your object is detached, it won't be tracked by the object context. By default if you execute a query inside a ObjectContext, entities are attached to object context. 

You can detach entities by one of the options below,

Using MergeOption.NoTracking enumeration or AsNoTracking
See examples here, here and here. Also beware about possible performance issues as mentioned here and here. See advantages of using AsNoTracking here and here.

ObjectContext.Detach method
This method removes the object from ObjectStateManager. Disables change tracking and identity resolution. See the example below,

https://msdn.microsoft.com/en-us/library/vstudio/bb896271(v=vs.100).aspx
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

See Working with DbContext (MSDN)
See example files used in this article in this gist

Saturday, December 7, 2013

Performance considerations in KnockoutJS

For web applications performance is an important factor to consider. In KnockoutJS when you do things in the wrong way this matters. We'll see some key areas you need to consider about performance in KnockoutJS. 

First lets look at fundemental building blocks of KnockoutJS application

observables
most basic fundamental building block. You need to have these

observableArrays

subscribers
get notifications when observable gets changed. You can dispose these. Also you delay them in case of expensive updates.

computed observables
Observables which depends on other observables


Bindings in KnockoutJS



visible binding
set display none based on the value. So shouldn't cost much.

for 10,000 elements inside a foreach, ko if takes around 10 seconds while visible binding only takes 1 second.

foreach
duplicates section of a markup for each array entry. Could be a normal array . 

if
bit expensive because, not like visible binding, if will hide the content which is inside the tag

    <div data-bind="if: check">
        <h1>Inject this to DOM if check is true</h1>
        <h2>Otherwise this won't exist in the DOM</h2>
    </div>

the visible binding just uses CSS to toggle the container element’s visiblity. The if binding, however, physically adds or removes the contained markup in your DOM, and only applies bindings to descendants if the expression is true.

with
creates a new binding context. it'll add descendent elements dynamically.

If the expression you supply involves any observable values, the expression will be re-evaluated whenever any of those observables change. Then, descendant elements will be cleared out, and a new copy of the markup will be added to your document and bound in the context of the new evaluation result.


click


value


checked


template


custom bindings


Monday, December 2, 2013

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
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