Steve Lydford on .Net

Sticking all my useful bits in one place in the hope that I may find them again one day!
posts - 4, comments - 0, trackbacks - 0

My Links

News

Hi. This just a collection of useful bits and pieces that I am posting here so that I might be able to find them again in the future. Feel free to browse through and use anything that may be of some help to you.

Archives

Post Categories

Wednesday, May 14, 2008

Uploading Files in ASP.Net

Just a quickie to show how to use the FileUpload control in ASP.Net.

The following is the click event of a button called btnUpload. The only catch-me-out is that you need to make sure that sufficient rights have been granted to the folder which you want to upload the files to, for the ASP.Net user.

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
        string SaveLocation = Server.MapPath("d:\\Data\\Uploads") + "\\" + fn;
        try
        {
            FileUpload1.PostedFile.SaveAs(SaveLocation);
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.Message);
 
        }
    }

posted @ Wednesday, May 14, 2008 12:13 PM | Feedback (0) | Filed Under [ C# ASP.Net ]

Monday, May 12, 2008

Open Page in Default Browser From Code

This code uses the System.Diagnostics namespace to open a specified URL in the users default web browser. There is some error checking in there incase the user has no default browser, so it should be fairly robust.

The following code is the Click event of a LinkLabel called linkLabel1:

       
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string webURL = "http://geekswithblogs.net/stevelydford";
 
            try
            {
                System.Diagnostics.Process.Start(webURL);
            }
            catch
                (
                 System.ComponentModel.Win32Exception noBrowser)
            {
                if (noBrowser.ErrorCode == -2147467259)
                    MessageBox.Show(noBrowser.Message);
            }
            catch (System.Exception other)
            {
                MessageBox.Show(other.Message);
            }
 
        }

posted @ Monday, May 12, 2008 11:02 PM | Feedback (0) | Filed Under [ C# ]

File Encryption/Decryption

Recently I needed to find a simple to way to encrypt and decrypt a file of any type (I actually needed to encrypt image and text files) and any size. I found hundreds of examples on the web, many of which just plain didn't work, or threw errors on certain file types.

Eventually I put together the following two methods using the Rijndael encryption algorithm, they simply require that you pass them the full path to the original and target files. They both require the System.Security, System.Security.Cryptography, System.Runtime.InteropServices and System.Text.RegularExpressions namespaces.

Hope they are some use to someone...

        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Encrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void EncryptFile(string inputFile, string outputFile)
        {
 
            try
            {
                string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);
 
                FileStream fsIn = new FileStream(inputFile, FileMode.Open);
 
                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);
 
               
                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
            }
            catch
            {
                MessageBox.Show("Encryption failed!", "Error");
            }
        }
        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Decrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void DecryptFile(string inputFile, string outputFile)
        {
 
            {
                string password = @"myKey123"; // Your Key Here
 
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);
 
                FileStream fsOut = new FileStream(outputFile, FileMode.Create);
 
                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);
 
                fsOut.Close();
                cs.Close();
                fsCrypt.Close();
 
            }
        }

posted @ Monday, May 12, 2008 10:51 PM | Feedback (0) | Filed Under [ C# ]

Persist AutoPostback DropDownLists on Page Refresh


Here we go for starters. ;)

The following C# code will allow you to persist AutoPostback DropDownList values on an ASP.Net page, without the use of an AJAX partial page update or a database. It simply uses session variables to persist the values which would otherwise be lost upon navigating away from and back to a page or by redirecting the browser to itself to refresh a databound control, such as a GridView.

This was a problem for me on a page that contained three DropDownLists, each of which was populated as a result of the SelectedValue on AutoPostback of the DropDownList above. Once the third DropDownList was selected a GridView was populated, then a details panel containing various user input controls and a 'Save' button was displayed on selection of a row in the GridView. When the 'Save' button was pressed the GridView was not updating and would only update if the page was refreshed. However, a simple redirect to the page as part of the Save button click event meant that the users selections in the three drop downs were lost. The following code was used to solve this problem and assumes three DropDownLists (DropDownList1, 2 & 3) and a Button (Button1).

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
///<summary>
/// Steve Lydford - 12th May 2008.
///
/// This class demonstrates how to persist AutoPostback DropDownLists
/// without the use of an AJAX partial page update or database. This
/// means that you are able to redirect to a page to refresh a GridView
/// or navigate away and back to a page and persist DropDownList values.
///</summary>
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Session["fillForm"] != null) && (Session["fillForm"].ToString() == "true"))
        {
            // fill dropdowns first then set the selectedValue.
 
            // DropDownList1 items collection filled at design time.
            fillDropDown(DropDownList2);
            fillDropDown(DropDownList3);
           
            DropDownList1.SelectedValue = Session["ddl1"].ToString();
            DropDownList2.SelectedValue = Session["ddl2"].ToString();
            DropDownList3.SelectedValue = Session["ddl3"].ToString();
 
            Session["fillForm"] = "false";
        }
       
    }
 
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["ddl1"] = DropDownList1.SelectedValue;
        fillDropDown(DropDownList2);
        if ((Session["ddl2"] != null) && (Session["ddl2"].ToString() != ""))
            DropDownList2.SelectedValue = Session["ddl2"].ToString();
    }
 
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["ddl2"] = DropDownList2.SelectedValue;
        fillDropDown(DropDownList3);
        if ((Session["ddl3"] != null) && (Session["ddl3"].ToString() != ""))
            DropDownList3.SelectedValue = Session["ddl3"].ToString();
    }
 
    ///<summary>
    /// Fills a DropDownList with the numbers 1 to 10.
    ///</summary>
    protected void fillDropDown(DropDownList ddl)
    {
        ddl.Items.Clear();
        for (int i = 1; i <= 10; i++)
            ddl.Items.Add(i.ToString());
    }
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["fillForm"] = "true";
        Session["ddl3"] = DropDownList3.SelectedValue;
 
        Response.Redirect("default.aspx");
    }
}

posted @ Monday, May 12, 2008 1:56 PM | Feedback (0) | Filed Under [ C# ASP.Net ]

Powered by: