Wednesday, September 9, 2015

How to download a file in MVC

Provide a easy way to download file in MVC.

Introduction

File downloading is a kind of  common functionality which we want in our web application. I already have a post http://www.codeproject.com/Tips/663277/File-Download-on-ImageButton-or-Button-Click which provides the code snippet to be used for this functionality in webforms.

But now the era has changed. Developers are switching to MVC now and so do there comes a need for file downloading snippet. Mostly File downloading is provided in two ways. File are saved in database (i.e. in form of bytes) or File is physically present on application server inside the application hierarchy. The following snippet works for both the scenarios as it uses the BYTES format to provide file as download.

Background

When I started work in MVC for the first time and when the file download task comes in, I had to google for the solution. So purpose of posting this tip is to help the naive's like me to get the solution in easiest way.

Using the code

Following is a simple code snippet which can be used as Action in MVC Controller. It simply picks the file from one folder in application hierarchy, converts it into bytes and return the result as file to View.
  public ActionResult DownloadFile()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "FolderName/";
            byte[] fileBytes = System.IO.File.ReadAllBytes(path + "filename.extension");
            string fileName = "filename.extension";
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
 Simply replace the  FolderName  with the folder in which file is present in project hierarchy, and replacefilename.extension with your filename along with extension to make it work properly.. Simply call this in view using the line below.

 @Html.ActionLink("Click here to download", "DownloadFile", new { })

Points of Interest
Many code snippets are available on Google, but I found this one pretty interesting and straight forward for any programmer who is a kind of newbie like myself.
Do give me your feedback,  either suggestions, corrections or praises. Smile | :)  

Thursday, March 20, 2014

Encryption/Decryption for the Beginner's Level

Introduction

It often comes to the task list for the College/Uni Level Students, that they have to store passwords, pass the Query String with URL or other stuff in the Encrypted way. So this Trick would be focuses on the same to provide an easy to understand way of performing this task with the minimal time and effort.

Using the code

I have been doing some coding tasks, when this thing comes into my play, and after searching on GOOGLE, I found the following methods for both Encryption and Decryption.

Hence sharing here for others to get the tasks done in an understandable way.

Encryption

 private string Encrypt(string clearText)
    {
        string EncryptionKey = "KEY"; // See NOTE at end of TIP
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    } 

Decryption

private string Decrypt(string cipherText)
    {
        string EncryptionKey = "KEY"; //See Note at the End of TIP
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    } 
NOTE: in Place of KEY, You have to provide the key, based on which both Encryption and Decryption will be done. So same key would be provided in both methods.

Points of Interest

This tip while performing my self, taught me about the way encryption and decryption works and how they can be implemented in Web Application.

Comments, Positive Criticism and Advice's are heartily welcome. Smile | :)

Friday, March 14, 2014

Select/Un-Select All checkbox in Gridview Header & Vice Versa

Introduction

This has become a common task to implement select/un-select all child check boxes via a parent check box(in Header) and vice versa. This post is basically describing these common tasks in a precise way along with other related sub tasks.

NOTE: This mini article have been published on CodeProject.com and it is here to share the knowledge.

Background

Yesterday, I was assigned a task to add check boxes in a column of Data Grid for selection of concerned records/rows and further requirement was as below.                                
  •      All child checkboxes will be checked/un-checked using a Parent checkbox(in Header).
  •           Automatically check “parent checkbox”, based on all child boxes checked/unchecked.


Further during the implementation I faced a validation requirement of “Select at least one checkbox” before proceeding. So I have combined all these three(3) tasks in this post to help other users in future.
First of all I will start with the HTML content(aspx page). Let’s have a look below.

Using the code

HTML Content (.ASPX Page)

 <asp:TemplateColumn>
    <HeaderTemplate>
         <input id="chkAll" class="cbAll" onclick="javascript:SelectAllCheckboxes1(this);"           runat="server" type="checkbox" />                                        
   </HeaderTemplate>
         <ItemTemplate>
             <asp:CheckBox ID="rptCB" runat="server" CssClass="cbChild" /><br />         </ItemTemplate>
 </asp:TemplateColumn>  

Above I have placed a Template column in Data Grid's content, which contains two templates inside.

Header Template: which contains the "Select All" checkbox and by clicking on that all the child check boxes will be checked or unchecked.
Item Template: which contains the child checkbox which will be shown repeatedly in the Data Grid's column and if all child boxes of Grid will be checked/un-checked, than it will result in Selection/un-selection of "Select All" checkbox , which will be present in Grid's header.

As you can see, there is a javascript function being called on the Parent checkbox in the header template, So my next paragraph will be describing it and it's functionality.

Select/un-Select All Child Check Boxes (JavaScript)

       function SelectAllCheckboxes1(chk) {
          
            $('#<%=MyGrid.ClientID%>').find("input:checkbox").each(function () {
                if (this != chk) {
                    this.checked = chk.checked; 
                 }
                        });

        } 
The above function will iterate the Data Grid using Jqeury .each method and will select/un-select all the child checkboxes. The above function will be placed inside the script tag at the end of form tag and just before the body tag's ending
For Task two i.e. selection of Parent check box(Select All), in case all child checkboxes have been checked one by one, following piece of code will be used.

Select/Un-Selected Parent Check Box(JavaScript)

 $(".cbChild").change(function () {             
                  var all = $('.cbChild');                 
                  if (all.length === all.find(':checked').length) {
                      $(".cbAll").attr("checked", true);
                  } else {
                      $(".cbAll").attr("checked", false);
                  }
              }); 
The above function will get all the childboxes using its class attribute and based on the scenario will selection or un-select the parent check box. This function will be placed inside the script tag at the end of form tag and just before the body tag's ending.

Further for the validation i.e Task three, we can use the following java script function

Please Select at least one check box (JavaScript)

Following function can be called on the button, on which we would be performing the further proecessing based on selected checkbox. So the following function will restrict the user to at least select one record.
HTML Content and function both are place below for better understanding.
 function checkSelected(btn) {
              
            var flg;

            var gridView = document.getElementById("<%=MyGrid.ClientID %>");
            var checkBoxes = gridView.getElementsByTagName("input");
            for (var i = 0; i < checkBoxes.length; i++) {
                if (checkBoxes[i].type == "checkbox" && checkBoxes[i].checked) {
                    flg = true;
                    return;
                }
            }
            flg = false;

            if (!flg) {
                alert("Please select Record(s).");
                return false
            }
          
            return true;
        } 
  

Button Content

    <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="Submit_Click"    OnClientClick="return checkSelected(this);" />  

Points of Interest
Its a 3 in 1 solution, which contains three mini tricks to save the time. These piece of codes are client side and hence makes the solution more optimized than the other available server side solutions.
At the end, I would be waiting and will appreciate any more advise/critic for improvement.

Hope it will help you. Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Monday, November 4, 2013

Browser Back Button handling after Sign Out throug JavaScript

Introduction

Disabling/Handling Browser's back button is a common functionality to be implemented or the problem to be solved during development of web applications now a days.  So when I found this problem in front of my nose, it took my a lot of time to understand and implement it as per my project. This simple Tip/Trick is focused on providing a simple and cross browser compatible solution in this context.

NOTE: This mini article have been published on CodeProject.com and it is here to share the knowledge.

Using the code 

JavaScript has become a most commonly used platform to sort out different types of problems on the client side (some time to enhance functionality and some time due to client restriction). In the same way, I have chosen the JavaScript to solve this oldie goldy problem.
To make my work (code) compatible for major browsers, I have extended the script a bit, So that it could work without any error.
I have created a JavaScript function in ASPX page which is being called from the code behind of  SignOut page of my application after the handling of Sessions (i.e., abandoning/clearing the sessions etc.).  
function ClearHistory()  
{ 
    //defining variables to get the browser width and height.
    var width;
    var height;

    // getting the Browser name which is currently in use.
    var BrowserName = navigator.appName;

    //handling the IE due to limitations of this browser
    // i.e., failure in getting proper height of browser.
    if (BrowserName == "Microsoft Internet Explorer") {
        //setting up height and width variable values.
        height = document.documentElement.clientHeight;
        width = document.body.clientWidth;
    }
    // code block to be executed in case of other browsers.i.e. except IE.
    else
    {
        height = window.innerHeight;
        width = window.innerWidth;
    }

    // getting the currently opened window. and than closing it to get rid of back button.
    //Mainly this is done to cover up the firefox limitation of window.close()
    var win = window.open("about:blank", "_self");
    win.close();

    //Opening a new Window with the Login page url
    //to redirect the user towards successful signout.
    var newWin = window.open('Login.aspx');

    //formatting the newly opened window to be adjusted accordingly.
    newWin.focus();
    newWin.moveTo(0, 0);
    newWin.resizeTo(width, height);
}

Points of Interest

While searching for a solution for this problem, I found a lot of solutions posted around, and I have created this by combining parts from there. 
I hope this could be much helpful and easy to implement (even though there is some hotchpotch). Any guidance from the seniors, comments/suggestions/errors are truly welcomed. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL).

Thursday, October 10, 2013

How to download a file on Button Click

Introduction

In most of the web applications now a days, there comes a need when we have to provide a link to download some sample file or file like that as per the requirements. So this tip is to perform this task in the easiest way (which I have found so far, as I am a newbie.

Using the Code

The following code performs the file download process in the simplest way, either from the application's local folder or from some system directory.
The developer has to place these line of codes inside the buttonclick or imagebutton clickevent.
Response.ContentType = "Application/xlsx";
Response.AppendHeader("Content-Disposition", "attachment; filename=filename.xlsx");
Response.TransmitFile(Server.MapPath("~/Templates/filename.xlsx"));
Response.End(); 

In the first line, we have to mention the content type, I have used it for Excel 2007 files while here, we can use the PDF or image as well.
The second line is just appending the header to the httpResponse and here we have to mention the filename along with the extension which we want to download.
While in the third line Complete Path where file is placed has to be provided.
In the last line of code, the Response is ending.

Points of Interest

Many code snippets are available on Google, but I found this one pretty interesting and straight forward for any programmer who is a kind of newbie like myself.
Do give me your feedback, as this is my first effort on any blog in my life, either suggestions, corrections or praises. :)

This Post is also available here File Download on Button Click  on www.codeporject.com i.e in fact the birthplace of this tip/trick.