Hello Laravel 5

Refereces:

install-laravel-mac

วิธี ติดตั้ง Laravel 4 บน Mac Maverick

View at Medium.com

Material Design

Now I am working on a material design project (In progress). I think this design is suitable for mobile devices to view.

This application I will create a basic CRUD application with AngularJS.

capture

You can download the source code project from here where you also find the instruction on how to run the app.

 

References:

https://material.angularjs.org/latest/

https://material.google.com/

https://design.google.com/icons/

Custom Form Authentication MVC4

MembershipProvider – API information in user

RoleProvider – API information in role

IPrincipal – tells us if the user is authenticated or in a given role

IIdentity – holds information about the user

MyMembershipProvider.cs


public class MyMembershipProvider : MembershipProvider
{
  // code omit
  public override bool ValidateUser(string username, string password)
  {
    using (DatabaseEntities dc = new DatabaseEntities())
    {
      var user = dc.Users.Where(u => u.Username.Equals(username) &&
 u.Password.Equals(password)).FirstOrDefault();
      return user != null ? true : false;
    }
  }
}

MyRoleProvider.cs


public class MyRoleProvider : RoleProvider
 {

// code omit

public override string[] GetRolesForUser(string username)
 {
 if (!HttpContext.Current.User.Identity.IsAuthenticated)
 return null;

// Check cache
 var cacheKey = string.Format("{0}_role", username);
 if (HttpRuntime.Cache[cacheKey] != null)
 return (string[])HttpRuntime.Cache[cacheKey];

string[] roles = new string[] { };
 using (DatabaseEntities dc = new DatabaseEntities())
 {
 roles = (from r in dc.Roles
 join ur in dc.UserRoles on r.RoleID equals ur.RoleID
 join u in dc.Users on ur.UserID equals u.UserID
 where u.Username.Equals(username)
 select r.Name).ToArray<string>();
 if (roles.Count() > 0)
 HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
 }
 return roles;
 }

public override bool IsUserInRole(string username, string roleName)
 {
 var userRoles = GetRolesForUser(username);
 return userRoles.Contains(roleName);
 }

}

MyPrincipal.cs


public class MyPrincipal : IPrincipal
 {
 private readonly MyIdentity _MyIdentity;

 public MyPrincipal(MyIdentity myIdentity)
 {
 _MyIdentity = myIdentity;
 }

 public IIdentity Identity
 {
 get { return _MyIdentity; }
 }

 public bool IsInRole(string role)
 {
 return Roles.IsUserInRole(role);
 }
 }

MyIdentity.cs


public class MyIdentity : IIdentity
 {
 public IIdentity Identity { get; set; }
 public User User { get; set; }

 public MyIdentity(User user)
 {
 Identity = new GenericIdentity(user.Username);
 User = user;
 }

 public string AuthenticationType
 {
 get { return Identity.AuthenticationType; }
 }

 public bool IsAuthenticated
 {
 get { return Identity.IsAuthenticated; }
 }

 public string Name
 {
 get { return Identity.Name; }
 }
 }

Web.config


<membership defaultProvider="MyMembershipProvider">
<providers>
<add name="MyMembershipProvider" type="CustomFormAuthentication.Infrastructure.MyMembershipProvider, CustomFormAuthentication" />
</providers>
</membership>

<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add name="MyRoleProvider" type="CustomFormAuthentication.Infrastructure.MyRoleProvider, CustomFormAuthentication" />
</providers>
</roleManager>

AccountController.cs


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
  if (ModelState.IsValid)
  {
    bool isValidUser = Membership.ValidateUser(model.Username, model.Password);
    if (isValidUser)
    {
      User user = null;
      using (DatabaseEntities dc = new DatabaseEntities())
      {
        user = dc.Users.Where(u => u.Username.Equals(model.Username)).FirstOrDefault();
      }
      if (user != null)
      {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string data = js.Serialize(user);
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
          1,
          user.Username,
          DateTime.Now,
          DateTime.Now.AddMinutes(30),
          model.RememberMe,
          data);
        string encToken = FormsAuthentication.Encrypt(ticket);
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encToken);
        Response.Cookies.Add(authCookie);
        if (Url.IsLocalUrl(returnUrl))
          return Redirect(returnUrl);
        else
          return RedirectToAction("MyProfile", "Home");
       }
     }
  }

  ModelState.Remove("Password");
  return View();
}

Company Store Web Application

ASP.NET Web API 2 + AngularJS

This project is a Single Page Application to support the device management in a small company.

What the technologies I am using.

Server Side

  • Entity Franework
  • ASP.NET Web API 2
  • Autofac
  • Automapper
  • NUnit3

Client Side

  • AngularJS
  • Bootstrap 3
  • Angular File Upload
  • MorrisJS
  • Angular Datatables
  • Full Calendar

You can download the source code project from here where you also find the instruction on how to run the app.

MockData Library

MockData allows you to generate large amounts of a test data based on your class.

To install MockData in package manager console

>> Install-Package MockData

At the moment MockData has the following static classes .

  • Address
    • City
    • Country
    • DefaultCountry
    • State
    • StateAbbr
    • ZipCode
  • Company
    • BS
    • Name
    • CatchPhrases
  • Internet
    • Email
    • FeeEmail
    • Username
    • DomainName
    • DomainWorld
  • Person
    • FirstName
    • Surname
    • FullName
  • Product
    • Department
    • ListDepartment
    • ProductName
  • Utils
    • Boolean
    • RandomDate

Employee emp = new Employee()
{
    FirstName = MockData.Person.FirstName(),
    LastName = MockData.Person.Surname(),
    Email = MockData.Internet.Email(),
    IsActive = MockData.Utils.Boolean()
};

Membership

The membership is service layer there is one middle layer between the web application and the data repositories. This layer only for the membership’s requirements leaving all data repositories being injected as they are directly to API Controllers.

First, we’ll create a simple encryption service to create salts and encrypted passwords and then we’ll use this service to implement a custom membership.

IEncryptionService.cs

public interface IEncryptionService 
{ 
  string CreateSalt(); 
  string EncryptPassword(string password, string salt); 
}

IMembershipService.cs

public interface IEncryptionService 
public interface IMembershipService 
{ 
  MembershipContext ValidateUser(string username, string password); 
  User CreateUser(string username, string email, string password, int[] roles); 
  User GetUser(int userId); 
  List<Role> GetUserRoles(string username); 
}

Add the encryption service implementation. It’s simple password encryption based on a salt and the SHA256 algorithm from System.Security.Cryptography namespace.

public class EncryptionService : IEncryptionService
{
	public string CreateSalt()
	{
		var data = new byte[0x10];
		using (var cryptoServiceProvider = new RNGCryptoServiceProvider())
		{
			cryptoServiceProvider.GetBytes(data);
			return Convert.ToBase64String(data);
		}
	}

	public string EncryptPassword(string password, string salt)
	{
		using (var sha256 = SHA256.Create())
		{
			var saltedPassword = string.Format("{0}{1}", salt, password);
			byte[] saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
			return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
		}
	}
}

MembershipService.cs

public class MembershipService : IMembershipService
{
	#region Variables
	private readonly IEntityBaseRepository<User> _userRepository;
	private readonly IEntityBaseRepository<Role> _roleRepository;
	private readonly IEntityBaseRepository<UserRole> _userRoleRepository;
	private readonly IEncryptionService _encryptionService;
	private readonly IUnitOfWork _unitOfWork;
	#endregion
	public MembershipService(IEntityBaseRepository<User> userRepository, IEntityBaseRepository<Role> roleRepository,
	IEntityBaseRepository<UserRole> userRoleRepository, IEncryptionService encryptionService, IUnitOfWork unitOfWork)
	{
		_userRepository = userRepository;
		_roleRepository = roleRepository;
		_userRoleRepository = userRoleRepository;
		_encryptionService = encryptionService;
		_unitOfWork = unitOfWork;
	}
	
}