Tuesday, 23 April 2013

Uploading and Downloading Word Files From Database Using ASP.NET C#

Background
Now, recently I am focusing on files related articles due to their relevance to file related operations. Now in this article I will explain how to upload Word files into a database and how to download those files from the database. This type of requirement can exist in any project such as how to upload only a .doc or .docx file resume, so because of the above requirement I have decide to write this article.

Now before creating the application, let us create a table named WordFiles in a database to store the uploaded Word files in a database table having the following fields (shown in the following image):
Wordtable.png

In the preceding table I have created four columns, they are id for the unique identity, Name for the Word  file name, type for file type and data to store the actual content of the files with a binary datatype because the content of the files are stored in bytes.

I hope you have created the same type of table.

Now  let us start to create an application to upload and download Word files step-by-step.
Now create the project  as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Give the Project   name such as  WordFileUploadDownload  or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Default.aspx page. 
  5. One File upload control, two Buttons, one label and a grid view.
Then the  <form> section of the Default aspx page looks as in the following:

 <form id="form1" runat="server">
    <div>  
   <table>
    <tr>
    <td> 
        Select File
        </td>
        <td>
        <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only word File" />
        </td>
        <td> 
        <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" />
        </td>
        <td> 
            <asp:Button ID="Button2" runat="server" Text="View Files" 
                onclick="Button2_Click" />
               </td>
        </tr> 
</table>
<table><tr><td><p><asp:Label ID="Label2" runat="server" Text="label"></asp:Label>  </p></td></tr></table>

<asp:GridView ID="GridView1" runat="server" Caption="Excel Files " 
        CaptionAlign="Top" HorizontalAlign="Justify" 
         DataKeyNames="id" onselectedindexchanged="GridView1_SelectedIndexChanged" 
        ToolTip="Word FIle DownLoad Tool" CellPadding="4" ForeColor="#333333" 
        GridLines="None">
        <RowStyle BackColor="#E3EAEB" />
        <Columns>
            <asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-ForeColor="Blue"/>
        </Columns>
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="Gray" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#7C6F57" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView> 
    </div>
 </form>

Now switch to design mode and double-click on the upload button and use the following code to upload and validate that only PDF files are allowed to be uploaded.

protected void Button1_Click(object sender, EventArgs e)
    {
        Label2.Visible = true;
        string filePath = FileUpload1.PostedFile.FileName;          // getting the file path of uploaded file
        string filename1 = Path.GetFileName(filePath);               // getting the file name of uploaded file
        string ext = Path.GetExtension(filename1);                      // getting the file extension of uploaded file
        string type = String.Empty;

 if (!FileUpload1.HasFile)
        {
            Label2.Text = "Please Select File";                          //if file uploader has no file selected
        }
        else
        if (FileUpload1.HasFile)
        {
            try
            {
                                                     
                switch (ext)                                         
// this switch code validate the files which allow to upload only PDF  file 
                {
                    case ".doc": 
                        type = "application/word"; 
                        break;    
                     case ".docx": 
                        type = "application/word"; 
                        break;               
                 
                }
 
                if (type != String.Empty)
                { 
                   connection();
                    Stream fs = FileUpload1.PostedFile.InputStream;
                    BinaryReader br = new BinaryReader(fs);                                 //reads the   binary files
                    Byte[] bytes = br.ReadBytes((Int32)fs.Length);                           //counting the file length into bytes
                    query = "insert into wordFiles (Name,type,data)" + " values (@Name, @type, @Data)";   //insert query
                    com = new SqlCommand(query, con);
                    com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1;
                    com.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
                    com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                    com.ExecuteNonQuery();
                    Label2.ForeColor = System.Drawing.Color.Green;
                    Label2.Text = " Word File Uploaded Successfully"; 
                }
                else
                {
                    Label2.ForeColor = System.Drawing.Color.Red; 
                    Label2.Text = "Select Only word Files  ";                              // if file is other than speified extension 
                }
            }
            catch (Exception ex)
            {
                Label2.Text = "Error: " + ex.Message.ToString(); 
            } 
        }
    }


Add the following code in the view file button click to View uploaded PDF files in GridView

protected void Button2_Click(object sender, EventArgs e)
    {
        connection();
        query = "Select *from WordFiles";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();

    }
Add the following code to the Gridview selected index changed event to download the files:

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
             connection();
            SqlCommand com =new SqlCommand("select Name,type,data from  WordFiles where id=@id", con);
            com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);
            SqlDataReader dr = com.ExecuteReader();

 
            if (dr.Read())
            {
                Response.Clear();
                Response.Buffer =true;
                Response.ContentType = dr["type"].ToString();
                Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString());     // to open file prompt Box open or Save file         
                Response.Charset = "";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite((byte[])dr["data"]);
                Response.End();
            }

}

Then run the page which will look as in the following:

demoscreen.png


From the above view I am using two buttons to do the upload; one to upload the selected files to the database and view files which shows the files in a grid view which is stored in a database table.

Now run the application and select a file that is not a Word file and the result will be the error as shown in the following:
Invalidfiles.png

Now select the Word file, which shows the following message after being successfully uploaded:

uploaded.png

Now click on view files details. The gridview shows the uploaded files with details as shown below. 

viewfiles.png

Now click on the download button of the gridview, the following prompt message is displayed as shown in the following image:

finaloutput.png

Then choose browse with MicroSoft Word and click on the "Ok" button. Then the file will be opened in Word format.

Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.

Thursday, 18 April 2013

Command Line Commands for Control Panel Applets(The Shortcut for open Application in Window PC)

Control Panel AppletCommandOS
Accessibility Optionscontrol access.cplXP
Action Centercontrol /name Microsoft.ActionCenter8, 7
control wscui.cpl8, 7
Add Features to Windows 8control /name Microsoft.WindowsAnytimeUpgrade8
Add Hardwarecontrol /name Microsoft.AddHardwareVista
control hdwwiz.cplXP
Add or Remove Programscontrol appwiz.cplXP
Administrative Toolscontrol /name Microsoft.AdministrativeTools8, 7, Vista
control admintools8, 7, Vista, XP
Automatic Updatescontrol wuaucpl.cplXP
AutoPlaycontrol /name Microsoft.AutoPlay8, 7, Vista
Backup and Restore Centercontrol /name Microsoft.BackupAndRestoreCenterVista
Backup and Restorecontrol /name Microsoft.BackupAndRestore7
Biometric Devicescontrol /name Microsoft.BiometricDevices8, 7
BitLocker Drive Encryptioncontrol /name Microsoft.BitLockerDriveEncryption8, 7, Vista
Bluetooth Devicescontrol bthprops.cpl138, 7, Vista
control /name Microsoft.BluetoothDevicesVista
Color Managementcontrol /name Microsoft.ColorManagement8, 7, Vista
Color1WinColor.exe2XP
Credential Managercontrol /name Microsoft.CredentialManager8, 7
Client Service for NetWarecontrol nwc.cplXP
Date and Timecontrol /name Microsoft.DateAndTime8, 7, Vista
control timedate.cpl8, 7, Vista
control date/time8, 7, Vista, XP
Default Locationcontrol /name Microsoft.DefaultLocation7
Default Programscontrol /name Microsoft.DefaultPrograms8, 7, Vista
Desktop Gadgetscontrol /name Microsoft.DesktopGadgets7
Device Managercontrol /name Microsoft.DeviceManager8, 7, Vista
control hdwwiz.cpl8, 7, Vista
devmgmt.msc8, 7, Vista, XP3
Devices and Printerscontrol /name Microsoft.DevicesAndPrinters8, 7
control printers8, 7
Displaycontrol /name Microsoft.Display8, 7
control desk.cplXP
control desktopXP
Ease of Access Centercontrol /name Microsoft.EaseOfAccessCenter8, 7, Vista
control access.cpl8, 7, Vista
Family Safetycontrol /name Microsoft.ParentalControls8
File Historycontrol /name Microsoft.FileHistory8
Flash Player Settings Managercontrol flashplayercplapp.cpl8
Folder Optionscontrol /name Microsoft.FolderOptions8, 7, Vista
control folders8, 7, Vista, XP
Fontscontrol /name Microsoft.Fonts8, 7, Vista
control fonts8, 7, Vista, XP
Game Controllerscontrol /name Microsoft.GameControllers8, 7, Vista
control joy.cpl8, 7, Vista, XP
Get Programscontrol /name Microsoft.GetPrograms8, 7, Vista
Getting Startedcontrol /name Microsoft.GettingStarted7
Home Groupcontrol /name Microsoft.HomeGroup8, 7
Indexing Optionscontrol /name Microsoft.IndexingOptions8, 7, Vista
rundll32.exe shell32.dll,Control_RunDLL srchadmin.dll8, 7, Vista, XP
Infraredcontrol /name Microsoft.Infrared8, 7
control irprops.cpl8, 7, Vista
control /name Microsoft.InfraredOptionsVista
Internet Optionscontrol /name Microsoft.InternetOptions8, 7, Vista
control inetcpl.cpl8, 7, Vista, XP
iSCSI Initiatorcontrol /name Microsoft.iSCSIInitiator8, 7, Vista
Keyboardcontrol /name Microsoft.Keyboard8, 7, Vista
control keyboard8, 7, Vista, XP
Languagecontrol /name Microsoft.Language8
Location and Other Sensorscontrol /name Microsoft.LocationAndOtherSensors7
Location Settingscontrol /name Microsoft.LocationSettings8
Mail4control mlcfg32.cpl58, 7, Vista, XP
Mousecontrol /name Microsoft.Mouse8, 7, Vista
control main.cpl8, 7, Vista
control mouse8, 7, Vista, XP
Network and Sharing Centercontrol /name Microsoft.NetworkAndSharingCenter8, 7, Vista
Network Connectionscontrol ncpa.cpl8, 7, Vista
control netconnections8, 7, Vista, XP
Network Setup Wizardcontrol netsetup.cpl8, 7, Vista, XP
Notification Area Iconscontrol /name Microsoft.NotificationAreaIcons8, 7
ODBC Data Source Administratorcontrol odbccp32.cplXP6
Offline Filescontrol /name Microsoft.OfflineFiles8, 7, Vista
Parental Controlscontrol /name Microsoft.ParentalControls7, Vista
Pen and Input Devicescontrol /name Microsoft.PenAndInputDevicesVista
control tabletpc.cplVista
Pen and Touchcontrol /name Microsoft.PenAndTouch8, 7
control tabletpc.cpl8, 7
People Near Mecontrol /name Microsoft.PeopleNearMe7, Vista
control collab.cpl7, Vista
Performance Information and Toolscontrol /name Microsoft.PerformanceInformationAndTools8, 7, Vista
Personalizationcontrol /name Microsoft.Personalization8, 7, Vista
control desktop8, 7, Vista
Phone and Modem Optionscontrol /name Microsoft.PhoneAndModemOptionsVista
control telephon.cplVista, XP
Phone and Modemcontrol /name Microsoft.PhoneAndModem8, 7
control telephon.cpl8, 7
Power Optionscontrol /name Microsoft.PowerOptions8, 7, Vista
control powercfg.cpl8, 7, Vista, XP
Printers and Faxescontrol printersXP
Printerscontrol /name Microsoft.PrintersVista
control printersVista
Problem Reports and Solutionscontrol /name Microsoft.ProblemReportsAndSolutionsVista
Programs and Featurescontrol /name Microsoft.ProgramsAndFeatures8, 7, Vista
control appwiz.cpl8, 7, Vista
Recoverycontrol /name Microsoft.Recovery8, 7
Regioncontrol /name Microsoft.RegionAndLanguage8
control intl.cpl8
control international8
Region and Languagecontrol /name Microsoft.RegionAndLanguage7
control intl.cpl7
control international7
Regional and Language Optionscontrol /name Microsoft.RegionalAndLanguageOptionsVista
control intl.cplVista
control internationalVista, XP
RemoteApp and Desktop Connectionscontrol /name Microsoft.RemoteAppAndDesktopConnections8, 7
Scanners and Camerascontrol /name Microsoft.ScannersAndCameras8, 7, Vista
control sticpl.cplXP
Scheduled Taskscontrol schedtasksXP7
Screen Resolutioncontrol desk.cpl8, 7
Security Centercontrol /name Microsoft.SecurityCenterVista
control wscui.cplXP
Software Explorers8msascui.exe9XP
Soundcontrol /name Microsoft.Sound8, 7
control /name Microsoft.AudioDevicesAndSoundThemesVista
control mmsys.cpl8, 7, Vista
Sounds and Audio Devicescontrol mmsys.cplXP
Speech Recognition Optionscontrol /name Microsoft.SpeechRecognitionOptionsVista
Speech Recognitioncontrol /name Microsoft.SpeechRecognition8, 7
Speechcontrol sapi.cpl10XP
Storage Spacescontrol /name Microsoft.StorageSpaces8
Sync Centercontrol /name Microsoft.SyncCenter8, 7, Vista
Systemcontrol /name Microsoft.System8, 7, Vista
control sysdm.cplXP
System Propertiescontrol sysdm.cpl8, 7, Vista
Tablet PC Settingscontrol /name Microsoft.TabletPCSettings8, 7, Vista
Task Scheduler7control schedtasks8, 7, Vista
Taskbarcontrol /name Microsoft.Taskbar8
rundll32.exe shell32.dll,Options_RunDLL 18
Taskbar and Start Menucontrol /name Microsoft.TaskbarAndStartMenu7, Vista
rundll32.exe shell32.dll,Options_RunDLL 17, Vista, XP
Text to Speechcontrol /name Microsoft.TextToSpeech8, 7, Vista
Troubleshootingcontrol /name Microsoft.Troubleshooting8, 7
User Accountscontrol /name Microsoft.UserAccounts8, 7, Vista
control userpasswords8, 7, Vista, XP
Welcome Centercontrol /name Microsoft.WelcomeCenterVista
Windows 7 File Recoverycontrol /name Microsoft.BackupAndRestore8
Windows Anytime Upgradecontrol /name Microsoft.WindowsAnytimeUpgrade7, Vista
Windows CardSpacecontrol /name Microsoft.CardSpace7, Vista
control infocardcpl.cpl7, Vista
Windows Defendercontrol /name Microsoft.WindowsDefender8, 7, Vista11
Windows Firewallcontrol /name Microsoft.WindowsFirewall8, 7, Vista
control firewall.cpl8, 7, Vista, XP
Windows Marketplacecontrol /name Microsoft.GetProgramsOnlineVista
Windows Mobility Centercontrol /name Microsoft.MobilityCenter8, 7, Vista
Windows Sidebar Propertiescontrol /name Microsoft.WindowsSidebarPropertiesVista
Windows SideShowcontrol /name Microsoft.WindowsSideShow8,7, Vista
Windows Updatecontrol /name Microsoft.WindowsUpdate8, 7, Vista12
Wireless Linkcontrol irprops.cplXP
Wireless Network Setup Wizard?XP