Saturday 31 August 2013

Free Rich Text Editor for Asp.net MVC apps, simple 2 steps to use

Today I just make a search for free text editors for asp.net mvc applications and I find TinyMCE there ( http://www.tinymce.com ) , very useful , effective and powerful , I am just using its jquery package to maintain all editing on client side which actually maintained by itself , we just have its final raw html for storage to database and show as @Html.Raw(Content from database), its very simple two steps process :

1) Just run this command in visual studio package manager console

     Install-Package TinyMCE.MVC.JQuery
This will install all necessary files and plugins your application needed and will create a view in shared folder which will be used as an editor ( partial view ) where you will call this editor functionality.

2) Second thing is write following Annotation on the top of model property to which you want to open in editor while creating or editing , e.g lets say you have Blog model which have title and body properties  and it is obious you will want to open Body in editor while creating or updating entity, so use this annotation on the top of that property like this  :

 [UIHint("tinymce_jquery_full"), AllowHtml]
        public string Body { get; set; }



And that's all, you are ready to go and use your rich editor to write your text with style.


For more detailed tutorial go to : http://www.tugberkugurlu.com/archive/tinymce-html-text-editior-and-asp-net-mvc-setting-it-up-has-become-easy-with-nuget.

Just make sure one thing that your _layout.cshtml has included jquery library as this tool is built in javascript and run on the top of it. So Enjoy :)

Sunday 18 August 2013

Insert custom object to Forms Authentication cookie to Identify user at each request

Forms authentication is a way that we use to login in our systems in asp.net mvc , it creates cookie on user side and user remains logged in until cookie expires , normally we use :


Where " User.Identity.IsAuthenticated " checks whether is there any user exists who is currently logged in the system and "User.Identity.Name" gives the user name ( usually email ) which we give in login form during login process , but what if we want some thing more that just an email address like , if someone wants to send his/her name,age,address or any other information or property to the server with each request from client side , because if we achieve that then we don't have to worry about what are the roles allowed to current user , what is his name , his id or anything , because in that case we don't have need to make database requests to get user information each time.
To achieve this we have "FormsAuthenticationTicket" object , we can provides your custom data in it , and we then add this object into our forms authentication cookie , and that's how custom information remains stick with each request. i.e.


where UserInfo is custom object containing user information, we add it as string , have to serialize this object to convert to object and vise versa.
We can use above described method while login process like this :

  FormsAuthenticationTicket ticket = UserAuthenticationTicketBuilder.CreateAuthenticationTicket(customer);

  SetTicket(HttpContext.Current, ticket);

Where customer is your object you wants to store in cookie , and setTicket( ) may be defined as :

 private void SetTicket(HttpContext httpContext, FormsAuthenticationTicket ticket)
        {
            var user = new User(ticket);
            if (!ticket.Expired)
            {
                string ticketval = this.Encrypt(ticket);
                string[] userRoles = user.RoleName;
                httpContext.User = new GenericPrincipal(user, userRoles);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketval) {        Expires= DateTime.Now.Add(FormsAuthentication.Timeout); };
                cookie.Domain = "";
                httpContext.Response.Cookies.Add(cookie);
                httpContext.Response.AddHeader(FormsAuthentication.FormsCookieName, ticketval);
            }
            else
            {
                httpContext.Response.Headers.Set(FormsAuthentication.FormsCookieName, null);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, null) { Expires = DateTime.Now.AddSeconds(-1) };
                httpContext.Response.Cookies.Add(cookie);
            }

        }


And User class which is accepting ticket must be implementing IIdentity and should get data out of ticket.

And finally implement this in your Global.ascx file :

 public override void Init()
        {
            this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
            base.Init();
        }

        void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            SetCookie();


        }

and in SetCookie() , create user object , add to request header cookie in the form of FormAuthentication cookie , the above Init() method will be called each and every time when request goes to the server and so your user object to.

Implement placeholders in either html or razor view using jquery very easily

Jquery has very simple plugin for showing placeholders in textfields and textareas when they are empty like this :


you can download its plugin form there : http://matoilic.github.io/jquery.placeholder/

To use it in your applications just use its library in header like this :

<script src="jquery.placeholder.js"></script>
and use these lines:
<script>
    $('input[placeholder], textarea[placeholder]').placeholder();
</script>

in header and you can use in html like this :
<input type="password" placeholder="password" name="password">

and if you want to use this in asp.net mvc razor views , then use it in this way :
 @Html.TextBoxFor(x => x.Email, new { placeholder = "Email" })

That is how placeholders can be implemented very easily in any technology using jquery.


Saturday 10 August 2013

Why Dependency Injection and how to implement , a Ninject Example

Dependency injection is a design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.
It injects the depended-on element (object or value, etc.) to the destination automatically by knowing the requirement of the destination i.e. in simple words we have to register all dependend-on entities seperately as a set , and any time when we need dependent on entity we get that from our collection e.g IService an interface and MyService is a class which has implementation of IService , lets say any where we use IService's method so we have to need MyService which is dependent on in this case and we need it.There are number of 3rd party libraries for injection of dependency , most popular are Autofac, Ninject and Unity.

Why to use :
  • Flexibility to use alternative implementation without recompiling the application code.
  • Loose coupling which promotes use of interfaces.
  • Code becomes more usable, readable and testable.

I do commonly prefer ninject because it is simpler. To download Ninject latest version just run 
Install-Package Ninject -Pre from Package manager console of visual studio.

Now lets see how to implement dependency injection using Ninject , it is very simple , only three steps required.

1) Create a class as dependency resolver 

 public class NinjetDependencyResolver : IDependencyResolver
    {
        private readonly IKernel _container;

        public NinjetDependencyResolver(IKernel container)
        {
            _container = container;
        }

        public object GetService(Type serviceType)
        {

            return _container.TryGet(serviceType, new IParameter[0]);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {

            return _container.GetAll(serviceType, new IParameter[0]);
        }

    }

2) In second step create a method in Global.ascx , where define your dependencies and use above class as  resolver for those dependencies :

 public void RegisterNinjectResolver()
        {
            var container = new StandardKernel();
            container.Bind<IUserRepository>().To<UserRepository>(); // our dependency
            DependencyResolver.SetResolver(new NinjetDependencyResolver(container)); // our dependency resolver
        }

3) Third and last step is to call method created in second step in App_Start method of Global.ascx 


protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterNinjectResolver(); // here it is

        }


That is all about how to implement DI pattern in your asp.net mvc applications, you can download sample project here : DOWNLOAD

Asp.net MVC4 WebSercurity more handy than membership provider

In MVC4 WebSercurity is very simpler and manageable way of providing log-in registration service to the users. It is simpler than membership provider and reduced database tables and in fact it is built on the top of membership provider.Provides more features than Membership provider , just need to user WebSecurity class which has following methods :



First method in the list is very important , because it creates websecurity's required tables in your database, all methods are link with documentation where they are explained very well. WebSecurity is by default provided with MVC4 project template.

Models in Asp.net MVC should be called ViewModels , why ?

By default ( default template of asp.net mvc ) Models in mvc architecture are used in two senses i.e. one is as POCO entities which represents the entities of our system and other is as containers which are filled in controllers and bring data back to views as we declare model at the top of each strongly typed view.

 @model Base.Models.QueryModels

In professional way these are two different things lets say we are using entity frame work ( database first approach using .edmx ) , we know that it provides one DbContext object and by instantiating we can get our entities and their crud operations which in returns gives us results as objects ( a presentation of database table) and that objects are our entities. Lets say at that time we are standing in our controller , we have database results fetched in an object and we just need to pass them in our View( ) , that is the point where we use our ViewModels.

For one entity we can have multiple ViewModels and why is that so because of view requirements , a customer role can have a different view than an Administrator etc , now the question is this what is an appropriate way to translate our entities to ViewModels , we can do this in two way :

1 ) Create custom mapping extension e.g. lets say we have an entity User.cs and a view model      UserModel.cs as given bellow:

public class User
{
   [Key]
   public virtual int UserId { get;set;}
   public virtual string FirstName { get;set;}
}

public class UserModel
{
   public int Id { get;set;}
   public string Name {get;set;}
}

Now in order to map them we can create our custom mapping in a separate class :

 #region user

        public static UserToEntity(this UserModel model)
        {
            var entity = new User()
            {
             
                UserId= model.Id,
                FirstName=model.Name,

            };
            return entity;
        }

        public static UserModel ToModel(this User entity)
        {
            var model = new UserModel()
            {
               Id=entity.UserId,
                Name= entity.FirstName,
            };
            return model;
        }

        #endregion

And to use this in controller just call ToModel with your entity:

   public ActionResult Details(int id)
        {
            var user= from users in db.Users where users.Id==id
                           select users;

            return View(user.ToModel()); // here entity is converted to your view model
        }

2 ) Second way is to use third party to map your models and entities with each and other , auto-mapper is good for that task.


That was all about how we can separate our models form entities , why we do that and its advantages, in next post hopefully I will demonstrate how to use Automapper to do model and entity mappings.

Saturday 3 August 2013

Membership Provider in .net

This is going to be very basic lets say introductory post about Membership Provider in .net applications , its purpose,usage and what is more better than that.Basically whenever you want to restrict users to access resources and check credentials to log-in to some system then we need a perfect "Login Regestration" system and that is what Membership Provider simply  does.
On abstraction we have users and they have to register first and then log-in to get access to resources on our website and if we are using Membership Provider we can implement this flow within a second with some extra features too.It provides us with number of methods to use its funcitonality. e.g

 MembershipUser user = Membership.CreateUser("UserName", "Password");


It provides number of features like generate passwords, online users , get users etc you can find it in the link above. Now lets talk about how it manages the database, it handles all database operations by itself, we just need to know where to use its functionality all background work will be done automatically.


So what we have to do to update our database so that membership can use our database to perform its functionality, there are two simple steps to create our database, i.e.

1) Open visual studio command prompt and run the command "aspnet_regsql"

2) This will open a window and where you can select your database and follow the window till finish



Now open your database and see in the tables, membership tables will be created, so you are ready to use Membership provider features.