Wednesday 22 February 2017

Angular 2 Component


Angular 2 application uses the component pattern. It allow us to breakdown the project/product into well defined discrete smaller components. For example smart phone battery is component of a smart phone. In software development we can say that components are logical units that can be combined in a specific way(interfaces) to build large application. Components are basic building block of an angular 2 application. Furthermore we bundle/combine these components through angular module. At high level we can say that to develop angular application you
1. create the component
2. bundle them into module
3. bootstrap your application
Component = Template (View Layout  Angularized HTML) + Class (Data + Behavior)  + Metadata (Defined with angular decorator)
Here is the example code link
In the example code above we will focus only on app.component.ts
Class:
Right now for simplicity it only has one property as “name”.
1
2
3
4
5
6
export class AppComponent {
name:string;
constructor() {
this.name = 'Angular2 Component'
}
}
Metadata and angularized html tempalate:
In this example we are using inline HTML Template with interpolation binding feature of Angular 2 {{name}}
1
2
3
4
5
6
7
8
@Component({
selector: 'my-app',
template: `
<div>
<h2>This is my first {{name}}</h2>
</div>
`,
})
Decorator is function that adds metadata to class, its members or its methods arguments
Decorator start with @ sign.
Angular do provide built in decorators.
@Component is angular 2 built in decorator that takes an object as parameters. You can say angular 2 decorator are similar to C# class attribute. Also notice that there is no comma after @Component({})
Import:
1
import {Component} from '@angular/core';

We import what we need using import statment.

Hope it help to understand angular 2 component.

Sunday 22 June 2014

C# MongoDb setup configuration for ASP.NET, ASP.NET MVC AND ASP.NET WEB API Applications


In this post, I will explain a basic mongoDB sample setup project for different .net applications (ASP.NET,ASP.NET MVC/WEB API etc.). You can use this code as base to mongoDB integration to your application.

Project Structure:
- Data
contains the mongoDB bootstrap logic for .net applications
- CSharpMongoDBSetup
C# console application as client application for mongoDB integration.

In Data project we have BaseEntity.cs which contains the core logic of mongoDB bootstrap/setup. On line # 185 we have repository section where we initialize the repository, and implemented the basic repository methods like get, delete and count etc.

 #region Repository

        [BsonIgnore, JsonIgnore]
        public static readonly string TypeName = typeof(TEntity).Name;

        [BsonIgnore, JsonIgnore]
        private static object _repoSync = new object();
        [BsonIgnore, JsonIgnore]
        private static MongoRepository<TEntity> _myRepository = null;
        /// <summary>
        /// Gets the repository used for manipulating this instance.
        /// </summary>
        [BsonIgnore, JsonIgnore]
        public static MongoRepository<TEntity> Repository
        {
            get
            {
                if (_myRepository != null)
                    return _myRepository;

                lock (_repoSync)
                {
                    if (_myRepository != null)
                        return _myRepository;

                    var myRepo = typeof(TEntity)
                        .GetCustomAttributes(typeof(RepositoryAttribute), true)
                        .OfType<RepositoryAttribute>()
                        .FirstOrDefault();

                    string cName = (myRepo == null || string.IsNullOrWhiteSpace(myRepo.ConnectionStringName)) ? "MongoServerSettings" : myRepo.ConnectionStringName;
                    var connString = ConfigurationManager.ConnectionStrings[cName];
                    if (connString == null)
                        throw new ApplicationException(string.Format("MongoDB connection string '{0}' is missing from configuration", cName));
                    _myRepository = new MongoRepository<TEntity>(connString.ConnectionString, TypeName);
                }

                return _myRepository;
            }
        }//end: Repository

        /// <summary>
        /// Gets the entity by its Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns>The entity found by the Id or <c>null</c> if no entity was found by that id.</returns>
        public static TEntity GetById(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
                return default(TEntity);

            return Repository.GetById(id.ToLowerInvariant());

        }

        /// <summary>
        /// Gets a queryable version of this entity type's repository for manual searching.
        /// </summary>
        /// <returns>A queryable version of this entity type's repository for manual searching.</returns>
        public static IQueryable<TEntity> AsQueryable()
        {
            return Repository.AsQueryable();
        }

        /// <summary>
        /// Counts the total entities in the repository.
        /// </summary>
        /// <returns>Count of entities in the collection.</returns>
        public static long Count()
        {
            return Repository.Count();
        }

        /// <summary>
        /// Deletes an entity from the repository by its id.
        /// </summary>
        /// <param name="id">The entity's id.</param>
        /// <exception cref="201"></exception>
        public static void Delete(string id)
        {
            var entity = GetById(id);
            if (entity != null)
                entity.Delete();
        }

        /// <summary>
        /// Deletes all entities in the repository.
        /// </summary>
        public static void DeleteAll()
        {
            Repository.DeleteAll();
        }

        /// <summary>
        /// Checks if the entity exists for given predicate.
        /// </summary>
        /// <param name="predicate">The expression.</param>
        /// <returns>True when an entity matching the predicate exists, false otherwise.</returns>
        public static bool Exists(Expression<Func<TEntity, bool>> predicate)
        {
            return Repository.Exists(predicate);
        }

        #endregion

 On line #66 we have implemented few public events for example "saving" which is useful to validate entity before actually saving the data.

 #region Public Events

        /// <summary>
        /// Event is called before this entity of type TEntity is saved. This is useful
        /// for additional validation, etc. and may be canceled.
        /// </summary>
        public event Action<object, CancelableEntityEventArgs<TEntity>> Saving;

        /// <summary>
        /// Event is called after an entity has been saved, passing the newly saved entity.
        /// </summary>
        public event Action<object, EntityEventArgs<TEntity>> Saved;

        /// <summary>
        /// Event is called before this entity of type TEntity is deleted. This is useful
        /// for additional validation, etc. and may be canceled.
        /// </summary>
        public event Action<object, CancelableEntityEventArgs<TEntity>> Deleting;

        /// <summary>
        /// Event is called after an entity has been saved, passing the recently deleted entity.
        /// </summary>
        public event Action<object, EntityEventArgs<TEntity>> Deleted;

        #endregion


Furthermore, all domain objects/collections which going to persist inherit from BaseEntity.cs, to use the logic implemented in BaseEntity.cs. For example User.cs in this sample inherits from BaseEntity.cs, and in console application you can see that we are able to use save method for user collection.

I hope that it will help people to get going with mongoDB.

Code Sample:
https://github.com/aamir-poswal/CSharpMongoDbConfigurationSetup

Tuesday 29 April 2014

Using filters in AngularJS controllers and services

Live Editable Example:

JS

 angular.module('FilterInControllerModule', []).  
 controller('FilterController', ['$scope', 'filterFilter',  
  function($scope, filterFilter) {  
   $scope.EntryName = '';  
   $scope.array = [{  
    name: 'Tobias'  
   }, {  
    name: 'Jeff'  
   }, {  
    name: 'Brian'  
   }, {  
    name: 'Igor'  
   }, {  
    name: 'James'  
   }, {  
    name: 'Brad'  
   }];  
   $scope.$watch('EntryName', function() {  
    $scope.filteredArray = filterFilter($scope.array, {  
     name: $scope.EntryName  
    });  
   }, true);  
  }  
 ]);  

HTML

 <!doctype html>  
 <html lang="en">  
 <head>  
  <meta charset="UTF-8">  
  <title>Example - example-example96-production</title>  
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.3/angular.min.js"></script>  
  <script src="script.js"></script>  
 </head>  
 <body ng-app="FilterInControllerModule">  
  <div ng-controller="FilterController">  
   <div>  
    Filter by :  
    <input type="text" ng-model="EntryName">  
   </div>  
   All entries:  
   <span ng-repeat="entry in array">{{entry.name}} </span>  
   <div>  
    Filter By Name in angular controller  
    <span ng-repeat="entry in filteredArray">{{entry.name}} </span>  
   </div>  
  </div>  
 </body>  
 </html>  

Tuesday 14 May 2013

How to Set Area Controller in ASP.NET MVC 4 as Default

in routeconfig.cs or global.asax.cs



routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  var route = routes.MapRoute(
     "Home_Default",
      "",
     new { controller = "Home", action = "index" },       //controller settings
     new[] { "EventSorbet.Web.Areas.Consumer.Controllers" }    // namespace
               );
 route.DataTokens["area"] = "Consumer";     // area name



Wednesday 7 March 2012

How to remove check all/header checkbox option in extjs 4 checkboxmodel?


listeners: {
        
        afterrender: function (grid) {
           $('.x-column-header-checkbox').css('display','none');
        }
    }


Saturday 4 February 2012

Scalable Black Jack Card Game using Best OOP Practices,Dependency Injection and Singleton patterns (C#)


Introduction:
In this post, I will present the working example of scalable and reusable simple Black Jack Card Game using Best OOP practices, Dependency Injection and Singleton Patterns.
The key feature of this solution is usability, which achieve through above-mentioned factors


Project Structure: 
1) CardGameFramework: it contains base classes, which can be inherited to implement different card games.
2) BlackJackGame: it consists of classes specifically related to Black Jack Card Game.
3) BlackJackConsoleClient: it is a console application through which users play the game.




Brief Description of Design and how to add Future Enhancements:
I have used base class wherever it adds value. For example, I have a base class named as Player in my implantation, and that base class is extended using BlackJackPlayer for more specialized implementation in case of BlackJack Card Game.
You can extend and use classes in CardGameFramework to implement different card games, to use these classes you just need to add dll of CardGameFramework into your project.

You can easily replace BlackJackConsoleClient GUI with web based or any other GUI client. Again, you only need to add reference of BlackJackGame project.

To implement more specialized Black Jack Card Game rules you can extend BlackJackGame class. By this way I have ensured OPEN/CLOSE PRINCIPLE, which states that classesshould be open for extension but modification, should not be allowed.

Design Pattern: 
I have used Singleton Pattern to make sure that only single instance of BlackJackGame class is created. Secondly, I have implemented Dependency Injection to remove tight coupling between classes in BlackJackGame class.

In the below section of code I have used these two design patterns.

private static BlackJackGame _blackJackGameInstance;
        //method that make sure that only single instance for blackjackgame is return
        public static BlackJackGame BlackJackGameInstance(BlackJackPlayer player, BlackJackPlayer dealer, Deck deck)
        {

            if (_blackJackGameInstance == null)
            {
                _blackJackGameInstance = new BlackJackGame(player, dealer, deck);
            }
            return _blackJackGameInstance;

        }
        //private constructor so that object can not be created apart from singleton method
        private BlackJackGame()
        {

        }
        //overload constructor used for Dependency Injection, is private to make sure that only instance is created through singleton method
        private BlackJackGame(BlackJackPlayer player, BlackJackPlayer dealer, Deck deck)
        {
            _dealer = dealer;
            _player = player;
            _deck = deck;
        }
 You can download complete demo code with link provided.
http://code.google.com/p/jqgridwithqtipintegration/downloads/list