Wednesday, 31 July 2013 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 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">
            <asp:CheckBox runat="server" ID="sampleCheckbox" Visible="true" />
           <asp:Image Width="100" ID="Image1" ImageUrl='<%# Bind("Name", "~/QRImages/{0}") %>'                  runat="server" />
     <itemstyle bordercolor="Brown" borderstyle="dotted" borderwidth="3px" horizontalalign="Center"
     VerticalAlign="Bottom" />

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)
                dtlist.DataSource = listItems;

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('/');


            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.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);
            var client = new SmtpClient("", 587)
                Credentials = new NetworkCredential("your gmail email here", " your password here"),
                EnableSsl = true
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 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 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.
             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);

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

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

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(),
            string result = sr.ReadToEnd();
            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" "" , will surely get into it when got some time :)
A very useful post from another forum is "".

QR codes and generation using .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 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 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 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 will be available soon. Sample project can be downloaded from Here.

Sunday, 21 July 2013