Printing Directly from Asp.Net MVC Controller Action to Printer in the Network

public async Task<ActionResult> Generate(string id)
{
     PrintDocument pd = new PrintDocument();
     pd.DefaultPageSettings.Margins.Left = 30;
     pd.DefaultPageSettings.Margins.Top = 10;
     pd.DefaultPageSettings.Margins.Right = 10;
     pd.DefaultPageSettings.Margins.Bottom = 10;
     pd.OriginAtMargins = true;
     pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
     // Set the printer name.
     //pd.PrinterSettings.PrinterName = "\\NS5\hpoffice
     //pd.PrinterSettings.PrinterName = "HP LaserJet 200 color M251 PCL6 Class Driver";
     pd.PrinterSettings.PrinterName = "EPSON LX-310";
     pd.Print();

     return RedirectToAction("Index", "Payslip", new { area = "Accounting", id = "", code = 801 });
}

void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
     Font printFont = new Font("3 of 9 Barcode", 18);
     Font printFont1 = new Font("Times New Roman", 11, FontStyle.Bold);
     SolidBrush br = new SolidBrush(Color.Black);
     ev.Graphics.DrawString("hello", printFont, br, 10, 65);
     ev.Graphics.DrawString("world", printFont1, br, 10, 85);
}

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);
}

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!

Simple Templating in C#

Hi Kids!

Here is a simple templating Sample and replacing placeholders in C#

StringBuilder str = new StringBuilder();          
string temp = "";

foreach (Item item in items)
{
     temp = Template.Text;    
     StringBuilder strTemplace = new StringBuilder(temp);
     strTemplace.Replace("{title}", item.title);
     strTemplace.Replace("{url}", item.url);
     strTemplace.Replace("{location}", item.location);
     strTemplace.Replace("{company}", item.company);                
     str.Append(strTemplace);
     str.Append("\n\r");
}

Alright Kids!
Ciao!

How to love C# and Entity Framework

This is how to fall in love with Entity Framework Kids.

 [Required]
 [StringLength(30)]
 [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Invalid Characters")]
 [Display(Name = "Firstname")]
 public string FirstName { get; set; }


 [Required]
 [StringLength(30)]
 [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Invalid Characters")]
 [Display(Name = "Lastname")]
 public string LastName { get; set; }

How can anyone not love that piece of art Kids.
It’s a thing of beauty.