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.

Wednesday, 31 July 2013

Asp.net select 1+ images in DataList controll

Recently there was a requirement in a project to create QR code image in one page and save it in a directory and show all images from that directory on another page in a view with a check box control , so that user can select multiple images send the email from that page.So I created a demo asp.net project and here I will share DataList code and button event code from code behind.

First have a look on datalist control code, very simple:


<asp:DataList ID="dtlist" runat="server" RepeatColumns="4" CellPadding="5"  Width="821px">
     <ItemTemplate>
            <asp:CheckBox runat="server" ID="sampleCheckbox" Visible="true" />
           <asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/QRImages/{0}") %>'                  runat="server" />
     </ItemTemplate>
     <itemstyle bordercolor="Brown" borderstyle="dotted" borderwidth="3px" horizontalalign="Center"
     VerticalAlign="Bottom" />
</asp:DataList>

So it looks like :


Next step is how to select images from that DataList controll , first we have to populate images to it which is done in Page_Load event:

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                DirectoryInfo dir = new DirectoryInfo(MapPath("QRImages"));
                FileInfo[] files = dir.GetFiles();
                ArrayList listItems = new ArrayList();
                foreach (FileInfo info in files)
                {
                    listItems.Add(info);
                }
                dtlist.DataSource = listItems;
                dtlist.DataBind();
            }
        }


After DataList got populated lets do selection work , I did that in button click event something like that :

            string Email = email.Text;
            List<string> files = new List<string>();

            foreach (DataListItem dli in dtlist.Items)
            {
                string location;
                bool IsCheck = ((CheckBox)dli.FindControl("sampleCheckbox")).Checked;
                if (IsCheck)
                {
                    location = ((Image)dli.FindControl("Image1")).ImageUrl;
                    int point = location.LastIndexOf('/');
                    files.Add(location.Substring(point+1));
                }

            }

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.From = new MailAddress("your gmail email"); // gmail is because we are using gmail smtp
            mail.To.Add(Email);
            mail.Subject = "Test";
            mail.Body = "";

            foreach (string path in files)
            {
                string attachmentPath = Server.MapPath("QRImages/");
                Attachment inline = new Attachment(attachmentPath + path);
                inline.ContentDisposition.Inline = true;
                inline.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
                inline.ContentType.MediaType = "image/png";
                inline.ContentType.Name = Path.GetFileName(attachmentPath);
                mail.Attachments.Add(inline);
            }
            var client = new SmtpClient("smtp.gmail.com", 587)
            {
                Credentials = new NetworkCredential("your gmail email here", " your password here"),
                EnableSsl = true
            };
            client.Send(mail);
            
Now you have everything , just copy paste above codes and have your one page application with multiple image selection for email attachment and sent email.

Tuesday, 30 July 2013

Asp.net MVC , custom authorization using AuthorizeAttribute Filter

Authorization in MVC with Authorization Filter is awesome thing. In MVC context controllers are all our resources for user more often i.e. users interact with our application using url and in MVC a url is mapped with our controllers and that's all.A controller is also consists of number of actions which are also used in url call.The point here is why not we should filter users requests to our resources and using a filter whole controller can be checked for a particular user (based on username, role or any thing ) as well as an individual action inside a controller.Asp.net MVC4 provides basic filters implementation in default template but we are going to do something different.

There are basically four types of filter that MVC offers :

  1. Authorization Filter
  2. Action Filter
  3. Result Filter
  4. Exception Filter

 Today we are only going with Authorization Filter ( basically going to customize it )
There is a class AuthorizeAttribute which implements IAuthorizationFilter, this class has two very important methods :


  • protected virtual bool AuthorizeCore(HttpContextBase httpContext)
  • protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
And we are going to override these methods.So start following steps described below :


         1.  Create a class with suffix "Attribute" , and inherit it from AuthorizeAttribute class e.g                                                                     public class UAuthAttribute: AuthorizeAttribute {

         2. Constructor with array of string                    
             private string[] Roles;   public UAuthAttribute(params string[] Roles){                                                                                                             this.Roles = Roles;
             }

        3. Override methods described above like this
    
          protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isAuthenticated = httpContext.Request.IsAuthenticated;
            // get the current user role by its name just an idea , do whatever you want
            string CurrentUserRole="Admin";//httpContext.User.Identity.Name

            bool AuthorizeRole = Roles.Contains(CurrentUserRole, StringComparer.InvariantCultureIgnoreCase);
            return isAuthenticated && !AuthorizeRole;
        }
        // un-authorize case handler
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Redirect("~/"); // by default it is redirected to the login page
        }

        4. HandleUnauthorizedRequest method is optional , is describes what to do if authorization fails , by default in case               of failure user is redirected to log in page but we can override that behavior and redirect to some custom page or              any where we want.

        5. Fifth and last thing is how to use this now , to use that filter just call it on top of the Action as shown below or you                 can also use it on top of controller which will be applicable for all its actions.
           
             [UAuth("admin","superAdmin")]
             public ActionResult Contact()
             {
                ViewBag.Message = "Your contact page.";
              return View();
             }


That is how we can use Authorization Filter to authorize users on the basis of their roles,names etc
I hope this little introduction helps for your further exploration.

Monday, 29 July 2013

JQuery, make html pages scroll-able ( Blogger example )

During writing a post in blogger I had a thinking that on other pages of my blog like "Project, Portfolio etc" , how to show some particular section of my page to users as these are single static pages with no posts and have to update the whole page if we want to add some piece of update , so what if I want to share some latest section on that page , here is the idea , make our page scroll-able to that specif location base on element id or class name , like that link : "Restaurant Chain Management System is launched", click on that link and see how it works.
Now lets have those tiny bits of lines that makes this happening:

 $(function () {
       function scrolView(i) {
           $('div').each(function () {
               if (($(this).attr('id'))==i) {
                   $('html, body').animate({
                       scrollTop: $(this).offset().top
                   }, 1000);
               }
           });
       }
       scrolView('1');
   });


That is it , use above lines and make your pages scroll-able.

Sunday, 28 July 2013

Html to Pdf document conversion in .Net

Hi, in this post I am going to share very simple and easy way to convert HTML document to Pdf file on the fly on just one click , you can use it from desktop as well as web application to convert a html page either from local storage or online web page.Lets start this , we are going to use PDFizer (http://sourceforge.net/projects/pdfizer/) for this task , a very easy and simple open source library to use for .net apps.Download that form above url and use the following code for creating a PDF document from html source.

  1. Include pdfizer.dll into reference of your project
  2. Specify the path where to store created pdf file                                                                              
           static  string sPathToWritePdfTo = "Report.pdf";
     
  3. Create a simple method                                                                                                                      public static void HtmlToPdf(string htmlString,string sPathToWritePdf)
           {

               Stream stream = new FileStream(sPathToWritePdf, FileMode.Create);
               HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();
               htmlToPdf.Open(stream);
               htmlToPdf.Run(htmlString);
               htmlToPdf.Close();
               stream.Dispose();
               stream.Close();

           }
  4. Use above method to create Pdf file from html source like following                                             StringBuilder sbHtml = new StringBuilder();
                sbHtml.Append("<html>");
                sbHtml.Append("<body>");
                sbHtml.Append("This is my document text ");
                sbHtml.Append("</body>");
                sbHtml.Append("</html>");

                HtmlToPdf(sbHtml.ToString(),sPathToWritePdfTo); 
And that all , your pdf is ready to use , you can convert html by reading html source from .html file , by downloading html from url by get request to url like :
public static String code(string Url)
    {
        
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(),
            System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();
            sr.Close();
            myResponse.Close();
            
            return result;
     }
 
This method will return you html source of the input url so you can create 
your pdf of online resources like that.

Recently during R&D I found another opensource pdf creation library for .net which seems to be more powerful (not sure), here is the link for library 
"PDFSharp" "http://pdfsharp.codeplex.com/releases/view/37054" , will surely get into it when got some time :)
A very useful post from another forum is "http://csharp.net-informations.com/file/create-pdf.htm".

QR codes and generation using .net ( asp.net )

QR code (Quick Response Code)  type of matrix barcode (or two-dimensional barcode), QR Code system has become popular  due to its fast readability and greater storage capacity. Basically it is an image consists of black dots on white background like shown below.



QR Code can be generated using .net technology , there are number of open source 3rd party libraries. Last weekend I got hands with QR codes and their generation and I used two libraries i.e 

XZing.net and MessagingToolkit.QRCode.1.3.0 , which can be used right from Package Manager console of visual studio by following commands respectively.
PM> Install-Package ZXing.Net
PM> Install-Package MessagingToolkit.QRCode

Lets come to their usage , I did use them with asp.net sample project but you can be use the same code with any type of project i.e. Windows Forms , Library project etc , lets start how to generate QR codes.

First create asp.net project from visual studio project templates , add a text field , a button and an image type. Register click event of button and in code behind file inside event use the following code:


            QRCodeEncoder encoder = new QRCodeEncoder();
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H; // 30%
            encoder.QRCodeScale = 4;
            Bitmap img = encoder.Encode(TextArea1.Text);

           
            img.Save(Server.MapPath("images/") + "img.jpg", ImageFormat.Jpeg);
            QRImage.ImageUrl ="~/images/img.jpg"; // will save the image in images folder as well

So that is simply how we can generate QR code using "MessagingToolkit.QRCode.1.3.0" library , code for Zxing.net will be available soon. Sample project can be downloaded from Here.

Sunday, 21 July 2013

Tuesday, 30 April 2013

Recently started a web app ( UEmail)  to manage your friends , colleagues etc email addresses on one page , arrange them in categories , create categories as you want.


Generally idea comes from sharing your content , ideas , posts etc to your friends by their emails, any suggestion , idea will be much appreciated :)

Thursday, 25 April 2013

Survey App has new look now www.usurvey.somee.com , provides more usability and  more interactive :)

Saturday, 20 April 2013

Reading List App

One more idea in my mind , coming soon stay tuned :)

USurvey is on its last node

Finally USurvey www.usurvey.somee.com app is in its final phase , although its been launched and working properly but in testing phase , currently thought about the variation in inputs from the participants of surveys secondly how to ensure that each participant can take part once only in one specific survey :)

Wednesday, 17 April 2013

My Own codded Blog

From along time I was trying to finalize my won hand codded blog , at last I was able to have some time to finalize it www.usmans.somee.com , just with simple UI but very mature back end programming , working on it is still going on , hopefully it will come in much batter form in next release , to give your suggestions if you want , or go to Projects tab to find some other codding stuff :)

Tuesday, 16 April 2013

My Survey App

Finally today I have been launched my Survey App www.usurvey.somee.com , now testing phase has been started , for details find it in my Projects tab usmansidea.blogspot.com/p/blog-page_10.html?id=usurvey , thanks :)

Wednesday, 10 April 2013

Move to 2Shared

Recently I used 2Shared.com to share my stuff and found it very cool , a bit simple to manage and gives access to non-registered clients to download files from links and also has password protected facility for private stuff  :)