Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

Thursday, 24 October 2013

How to Use a Windows Installer Disc to Back Up Your Files When Your Computer Won’t Boot



back-up-files-from-windows-cd
If Windows won’t boot, recovering your files can be a headache.  You do n0t have to pull the hard drive or use a Linux live CD – you can use a Windows installer disc to quickly back up your files.
We have included steps for both Windows 8 and Windows 7 here – the process is basically the same on each.  You can use a Windows 7 disc to back up files from a Windows 8 system or vice versa.

Boot From a Windows Installer Disc

First, insert a Windows installer disc (or a USB drive with the Windows installer on it) into your computer and restart your computer.  If everything is working properly, you will see a “Press any key to boot from CD or DVD” message.  Press a key to enter the installer.  If you do not see this screen, you may need to change the boot settings in your computer’s BIOS.
Click the Next option and select Repair Your Computer.  You will see this option at the bottom-left corner of the window, whether you are using a Windows 7 or Windows 8 installer disc.
If you are using a Windows 8 installer disc, select Troubleshoot > Advanced Options > Command Prompt.
If you are using a Windows 7 installer disc, select the Restore your computer using a system image you created earlier option, click Next, click Cancel, and click Cancel again.
You will see the System Recovery Options window – click Command Prompt to launch a Command Prompt window.
When you see a Command Prompt, type notepad and press Enter to launch a Notepad window.  Click File and select Open in the Notepad window.
Ensure you select the All Files option at the bottom of the window, and then click the Computer option.
You can use this Open dialog as if it were a Windows Explorer window – select files and you’ll be able to copy and paste them elsewhere.  If you connect a USB drive or removable hard drive to your computer, you will be able to copy-paste files onto it.
Do not double-click any files or Notepad will try to open them, possibly freezing.  If Notepad freezes on you, go back to the Command Prompt window and type taskmgr to launch the Task Manager.  You can end the frozen Notepad task and re-launch Notepad.
Once you are done copying your files off your hard drive, you can close the windows and shut down your computer.  Or, if you plan on reinstalling Windows anyway, you can now begin performing a clean installation with your files safely backed up.

Monday, 5 August 2013

SAVE AND RETRIEVE FILES FROM SQL SERVER DATABASE USING ASP.NET



As you can see above for the id field I have set Identity Specification true, so that it automatically increments itself.

Field
Relevance
id
Identification Number
Name
File Name
Content Type
Content Type for the file
Data
File stored as Binary Data

Content Type
Depending on the type of the file below are the content types

File Type
Content Type
Word Document
application/vnd.ms-word
Excel Document
application/vnd.ms-excel
JPEG Image
image/jpeg
Portable Document Format
application/pdf


Connection String
Below is the connection string to the database. You can modify it to suit yours

<connectionStrings>
<add name="conString" connectionString="Data Source=.\SQLEXPRESS;database=dbFiles; Integrated Security=true"/>
</connectionStrings >


Reading the File
The files will be read into a File Stream and then the File Stream will be converted into byte array using BinaryReader in order to save into the database table.

C#

// Read the file and convert it to Byte Array
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();                                                                                  
Saving the File to Database

Once the File is converted into Byte Array it will be inserted into the database. The File Name, File Content Type and the Binary data which resembles the file are stored in the database.

The figure below shows the data being stored in the table.


C#
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name"SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType"SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data"SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);

And the function InsertUpdateData accepts the SqlCommand object, executes the query and inserts the data into the database.

C#
private Boolean InsertUpdateData(SqlCommand cmd)
{
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        cmd.ExecuteNonQuery();
        return true;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return false;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}

Retrieving the File from Database

To retrieve the file from the database, a select query is executed and the ID of the file is passed as the parameter.
The command object is prepared and is passed to the GetData which returns the DataTable which contains the desired file data.
Then the DataTable is passed to the download function which starts the download of the file.

C#
string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id"SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
    download(dt);
}
Below is the code for the GetData function. It is a simple function that executes the Select query.

C#

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager
    .ConnectionStrings["conString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConnString);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}
Download the File

Here is the function which initiates the download of file. It basically reads the file contents into a Byte array and also gets the file name and the Content Type. Then it writes the bytes to the response using Response.BinaryWrite

C#

private void download (DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = dt.Rows[0]["ContentType"].ToString();
    Response.AddHeader("content-disposition""attachment;filename="
    + dt.Rows[0]["Name"].ToString());
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}


Friday, 10 May 2013

Upload Multiple Files with One Fileupload Control and Save these file in database as new row



.aspx Page Content

<style type="text/css">
        #divFile p { font:13px Century }
        #divFile h3 { font:16px Century; font-weight:bold; }
    </style>
    <script type="text/javascript">
    $('#btUpload').click(function() { if (fileUpload.value.length == 0) { alert('No files selected.'); return false; } });
</script>
<div id="divFile" style="width: 95%;float:right; text-align:center">
<b>Upload Multiple Reports by selecting multiple reports files</b>
            <p><asp:FileUpload ID="fileUpload" multiple="true" runat="server" /></p>
            <p><input type="button" id="btUpload" value="Upload Reports"
                onserverclick="btUpload_Click" runat="server" /></p>
            <p><asp:label id="lblFileList" runat="server"></asp:label></p>
            <p><asp:Label ID="lblUploadStatus" runat="server"></asp:Label></p>
            <p><asp:Label ID="lblFailedStatus" runat="server"></asp:Label></p>
            <br />
            </div>



.cs Page Content


protected void btUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
            {
                int iUploadedCnt = 0;
                int iFailedCnt = 0;
                HttpFileCollection hfc = Request.Files;

                lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";

                if (hfc.Count <= 40)    // 40 FILES RESTRICTION.
                {
                    for (int i = 0; i <= hfc.Count - 1; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            if (!File.Exists(Server.MapPath("../Report/") + Path.GetFileName(hpf.FileName)))
                            {
                                DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("../Report/"));
                                string sFileName = Path.GetFileName(hpf.FileName);
                                string sFileExt = Path.GetExtension(hpf.FileName);

                                // CHECK FOR DUPLICATE FILES.
                                FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + ".*");

                                if (objFI.Length > 0)
                                {
                                    // CHECK IF FILE WITH THE SAME NAME EXISTS (IGNORING THE EXTENTIONS).
                                    foreach (FileInfo file in objFI)
                                    {
                                        string sFileName1 = objFI[0].Name;
                                        string sFileExt1 = Path.GetExtension(objFI[0].Name);

                                        if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
                                        {
                                            iFailedCnt += 1;        // NOT ALLOWING DUPLICATE.
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    // SAVE THE FILE IN A FOLDER.
                                    string pid = "";
                                    string fname = "";
                                    if (Session["HID"].ToString() == "ultrad")
                                    {
                                        pid = hpf.FileName.Substring(0, 5);
                                        fname = hpf.FileName.Substring(5, hpf.FileName.Length - 5);
                                    }
                                    else
                                    {
                                        pid = hpf.FileName.Substring(0, 6);
                                        fname = hpf.FileName.Substring(6, hpf.FileName.Length - 6);
                                    }

                                    string path1 = Server.MapPath("../Report/Hosp/") + Session["HID"].ToString();

                                    if (!Directory.Exists(path1))
                                    {
                                        Directory.CreateDirectory(path1);
                                    }

                                    string path = Server.MapPath("../Report/Hosp/" + Session["HID"].ToString() + "/") + pid;

                                    if (!Directory.Exists(path))
                                    {
                                        Directory.CreateDirectory(path);
                                    }

                                 
                                    hpf.SaveAs(Server.MapPath("../Report/Hosp/" + Session["HID"].ToString() + "/" + pid + "/") + Path.GetFileName(DateTime.Now.ToString("yyyyMMddHHmmss") + " " + hpf.FileName));

                                    du.ExecuteSql("insert into Patient_MR(PatientId,RName,ReportPath,Hospital) values('" + pid + "','" + fname + "','Report/Hosp/" + Session["HID"].ToString() + "/" + pid + "/" + Path.GetFileName(DateTime.Now.ToString("yyyyMMddHHmmss") + " " + hpf.FileName) + "','" + Session["HID"].ToString() + "')");
                                 
                                    iUploadedCnt += 1;
                                }
                            }
                        }
                    }
                    lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
                    lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";
                    fileUpload.Attributes.Clear();

                }
                else lblUploadStatus.Text = "Max. 40 files allowed.";
            }
            else lblUploadStatus.Text = "No files selected.";
        }