C# Base Repository Interface

For those Developers using Repository Pattern, this is the ideal structure of your Base Repository Interface.

public interface IBaseRepository{
  Task<IEnumerable<Entity>> FindAll();
  Task<IEnumerable<Entity>> FindAll(Expression<Func<Entity, bool>> predicate);
  Task<Entity> GetByID(int id);
  void Delete(int id);
  Task<Entity> SaveOrUpdate(Entityentity);
  Task<Entity> SaveOrUpdate(int id, Entityentity);
  void BulkSaveOrUpdate(List<Entity> entities);
}

How to Create DataTable in Angular2 / TypeScript

I am not sure if there are any ported Jquery DataTable available but I’m pretty sure I find a hard time finding it.
So I created my own DataTable implementation in Angular2/TypeScript.

I too busy to explain so just copy and paste this and if you have any problems drop me a comment or email me.

Angular2 restful client. #angular2 #aspnetmvc5 #webapi #entityframework #javascript #webdev #webdesign #sofwareengineering #singlepageapplications

A video posted by Full-Stack .Net Developer (@butchokoiechronicles) on

@Component({
  selector: 'btc-table',    
  moduleId:module.id,
  template:`
  <div>
    <input type="text" [(ngModel)]="searchString" (keyup)="filterResult($event)" placeHolder="Search" class="form-control" />
  </div>
  <table class="table table-bordered">
    <thead>
        <tr><th *ngFor="let t of theader">{{t}}</th></tr>
    </thead>
    <tbody>
        <tr *ngFor="let d of displayData">
            <td *ngFor="let t of theader">{{d[t]}}</td>        
        </tr>
    </tbody>
    <tfoot>
        <tr><th *ngFor="let t of theader">{{t}}</th></tr>
    </tfoot>
  </table>
  <div>    
        <div style="display:inline-block">{{displayStatus}}</div>
        <div
        (click)="showPage(ndx + 1)"
        style="display:inline-block"
        class="btn btn-success"
        *ngFor="let item of totalPages | fill let ndx = index">{{ndx + 1}}</div>
  </div>
  `,
   pipes: [ FillPipe,FilterArrayPipe ]
})
export class BtcTableComponent {
    theader = ["id","FullName","Email"];  
    totalResultCount:number = 10;
    totalResultPerPage:number = 3;
    totalRemaining:number;
    totalPages:number;
    searchString:string;
    displayStatus:string;
    displayData:Datum[];
    inMemoryData:Datum[];
    data:Datum[] = [
        {id:1,FullName:"Julius Bacosa",Email:"juliusbacosa@gmail.com",p:1},
        {id:2,FullName:"Julius Ceasar",Email:"juliusceasar@gmail.com",p:1},
        {id:3,FullName:"Napoleon Bonaparte",Email:"napoleonbonaparte@gmail.com",p:1},
        {id:4,FullName:"Genghis Khan",Email:"genghiskhan@gmail.com",p:2},
        {id:5,FullName:"Joseph Stalin",Email:"josephstalin@gmail.com",p:2},        
        {id:6,FullName:"Cara Delevingne",Email:"caradelevingne@gmail.com",p:2},
        {id:7,FullName:"Wintson Churchill",Email:"winstonchurchill@gmail.com",p:3},
        {id:8,FullName:"Vladimir Putin",Email:"vladimirputin@gmail.com",p:3},
        {id:9,FullName:"Adolf Hitler",Email:"adolfhitler@gmail.com",p:3},
        {id:9,FullName:"Donald Trump",Email:"donaltrump@gmail.com",p:4},
    ];

    constructor(){}

    ngOnInit(){        
        this.inMemoryData =this.data;
        this.showPage(1);
       
    }

    showPage(index){      
        var  d = this.inMemoryData;      
     
        var newd = [];
        for(var i in d){    
            if(d[i].p==parseInt(index)){
              newd.push(d[i]);      
            }
        }        
        this.totalPages = Math.ceil(this.inMemoryData.length / this.totalResultPerPage);
        this.totalRemaining = this.inMemoryData.length % this.totalResultPerPage;
        this.displayData = newd;
        this.displayStatus = "Showing " + newd.length + " of " + d.length;

    }
    filterResult(event:any) {
       
        var str = this.searchString;
        var d = this.data;
        var newd = [];
       
       
        var itemCounter = 1;
        var pageCounter = 1;                
        for(let i in d){
          if((typeof d[i].FullName === 'string' || d[i] instanceof Datum) && (d[i].FullName.indexOf(str)!==-1)){
               
               d[i].p = pageCounter;
               newd.push(d[i]);

               // assign page
               if(itemCounter >= this.totalResultPerPage){
                   itemCounter=1;
                   pageCounter++;

               }else{
                   itemCounter++;
               }
               
          }
        }

        this.inMemoryData = newd;
        this.totalPages = Math.ceil(newd.length / this.totalResultPerPage);
        this.totalRemaining = newd.length % this.totalResultPerPage;
        this.showPage(1);
    }
   
   
}

export class Datum{
    id:number;
    FullName:string;
    Email:string;
    p:number;
}

Loosely Coupled , Test Driven Design and API Centric Application

I now have my Asp.net MVC WebAPI 2 implemented with Test Driven Design.

Loosely Coupled with the help of Unity and TDDed with Moq.

Now I can begin porting my Real Estate Billing Management System coded in PHP and Zend Framework

public class PeopleRepository<T> : IPeopleRepository<T> where T : class
{
   protected AppDBContext db;

   public PeopleRepository(IUnitOfWork unitOfWork)
   {
     db = unitOfWork.DbContext;
   }
}
   public interface IPeopleRepository<T> where T : class
   {
      IEnumerable<T> FindAll();
      T GetByID(int id);
      void Delete(int id);
      void SaveOrUpdate(T customer);
   }
   public interface IPeopleRepository<T> where T : class
   {
      IEnumerable<T> FindAll();
      T GetByID(int id);
      void Delete(int id);
      void SaveOrUpdate(T customer);
   }

I will have this Application front ended with AngularJs2 because of TypeScript.

I heard that ReactJs is becoming more popular. But just *7^&off!

Mastering Inversion of Control (IoC) and Test Driven Design Discipline Concept step-by-step

My Application is going to have 3 type of people entity or maybe more in the future.
For now I have Customers, Agents and Employees. So I created one main Entity which I called Person, and
have these 3 models get inheritance from the Person model.

And to avoid repeating codes on this three entities during implementation, I make use of C#’s Generics,

To illustrate generics in my Unit Testing using Moq. The following codes are for your perusal Kids.! Enjoy!

[TestClass]
public class CustomersControllerTest
{
   Mock<IPersonRepository<Customer>> _repositoryMock;
   CustomersController controller;

   public CustomersControllerTest(Mock<IPersonRepository<Customer>> repositoryMock)
   {
      _repositoryMock = repositoryMock;
   }
       
   [TestInitialize]
   public void SetUp()
   {
      _repositoryMock = new Mock<IPersonRepository<Customer>>();
      controller = new CustomersController(_repositoryMock.Object);            
   }        
}

Unity Dependency Injection, Test Driven Design and Entity Framework

Early Today I struggled on implementing Dependency Injection using Unity on a new Asp.net MVC 5 setup. I struggle so much that I move on to unit testing instead just to make some progress today using Moq.

So Unit Testing my Project right now is using only the Repository Pattern. I’ll be back on Dependency Injection Containers Maybe next week. I’ll use this Repository Pattern setup to finish my 2 projects this week.

Here are some code highlights

Instantiating your controller

private ICustomerRepository _customerRepository;

public CustomersController(ICustomerRepository customerRepository)
{
  _customerRepository = customerRepository;
}

public CustomersController()
{
  _customerRepository = new CustomerRepository();
}

Moq Unit Testing

 //arrange
 var customers = new List<Customer>();
 customers.Add(customer);
           
 repositoryMock.Setup(x => x.FindAll()).Returns(customers.AsQueryable());

 //act
 var result = controller.Lists() as ViewResult;
 var model = result.ViewData.Model as List<Customer>;

 //assert
 Assert.AreEqual(1, model.Count);
 Assert.AreEqual("Lists", result.ViewName);

Repository Interface for Customers Implementation

public interface ICustomerRepository : IDisposable
{
  IEnumerable<Customer> FindAll();
  Customer GetByID(int id);      
  void Delete(int id);
  void SaveOrUpdate(Customer customer);
}

This will now be my base code to implement by Billing and Payroll Applications.

Bye!

Query for Entity Framework using Concept of Projection for Tuned Performance.

Hi Kids,

You should not filter your entity framework results with-in a loop.

It is better to code it like this.

var object = await db.Tables.Include(o => o.AnotherTable)
.Where(s => s.Created >= startDate && s.Created <= endDate)
.OrderByDescending(lambda => lambda.id)
.Select(anotherlambda => new TemporaryObject{
                        SelectedColumn = so.SelectedColumn ,
                                               
}).ToListAsync();

Do I have to tell you everything?

Asp.Net Identity IsInRole not working or Returning Empty

Hi Kids,

If this piece of code in Asp.Net MVC 5 on .Net 4.6 is Not working

User.IsInRole("Admin");

Just code it like this.

       ApplicationUser u = await UserManager.FindByNameAsync(username);
       var roles = u.Roles;
       List<string> s = new List<string>();
       foreach (var i in roles)
       {
           var r = db.Roles.SingleOrDefault(w => w.Id == i.RoleId);
           s.Add(r.Name);                        
       }

       if (s.Contains("Admin"))
       {
          return RedirectToAction("Index","Jumpers");
       }

It will save you time.

Alright Kids! You’re Welcome!

Screen Scrolling with Mouse Wheel in Jquery

Hi Kids!

Here is how to detect scroll with Mouse Wheel in Jquery

$('#div1, #div2, #div3').on('DOMMouseScroll mousewheel', function (e) {            
        if(e.originalEvent.wheelDelta){
            if(e.originalEvent.wheelDelta < 0) {
               //down
               i++;
                if(i>divArr.length){
                    i=divArr.length-1;
                }
             
            }else{
                //up                
                 i--;
                if(i<0){
                    i=0;
                }                
            }                    
        }                                                            
        AnimateToView(divArr[i]);              
});

Alright Kids!
Ciao!