C# Snippets

"Remember Me" for login ( Using cache) :


In Login Button click event :


                   if (chkRemLoginID.Checked == true)
                    {
                        HttpCookie myCookie = new HttpCookie("myCookie ");
                        Response.Cookies.Remove("myCookie");
                        Response.Cookies.Add(myCookie);
                        myCookie.Values.Add("txtUserName", txtUserName.Text);
                        myCookie.Values.Add("txtPassword", txtPassword.Text);
                        myCookie.Values.Add("orgId", user.OrganizationDetails.Organizationid.ToString());
                        myCookie.Expires = DateTime.Now.AddDays(30);
                     }

In Page_Load event :



               if (!IsPostBack)
                {
                    if (HttpContext.Current.Request.Cookies["myCookie"] != null)
                    {
                        txtUserName.Text = HttpContext.Current.Request.Cookies["myCookie"]              ["txtUserName"].ToString();
                        txtPassword.Text = HttpContext.Current.Request.Cookies["myCookie"]["txtPassword"].ToString();
                        txtPassword.Attributes.Add("value", txtPassword.Text);
                    }                 
                }

Javascript Alert message box using C# :



public static void ShowAlertMessage(string message)
        {
            Page page = HttpContext.Current.Handler as Page;
            if (page != null)
            {
                message = message.Replace("'", "\'");
                System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + message + "');", true);
            }
        }

Setting Thread for Culture info:


Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Open Word Document on click or on load:



 Response.Clear();
            Response.ContentType = "application/vnd.openxmlformats";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + "<DocName>");


            string path = HttpContext.Current.Request.PhysicalApplicationPath + @"\Documents\<DocName>";

            using (FileStream fs = File.OpenRead(path))
            {
                byte[] b = new byte[fs.Length];

                if (fs.Read(b, 0, b.Length) >0)
                    Response.OutputStream.Write(b, 0, b.Length);
            }
            Response.End();

Reading from XML: 


XmlDocument xDoc = new XmlDocument();
matchdata = drSubscription["MatchData"].ToString()  // Get the xml doc
xDoc.LoadXml(matchdata);

if (xDoc.DocumentElement.ChildNodes[0].InnerText != null)
   objReportSchedule.StartTime = Convert.ToDateTime(xDoc.DocumentElement.ChildNodes[0].InnerText).ToShortDateString(); // Start Reading



Base64 Encryption Class: 

public static class Encryption
    {
        public static string Encode(string str)
        {
            byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
            return Convert.ToBase64String(encbuff);

        }
        public static string Decode(string str)
        {
            byte[] decbuff = Convert.FromBase64String(str);
            return System.Text.Encoding.UTF8.GetString(decbuff);
        }
    }


To check whether the file exists on FTP :

private static bool FtpDirectoryExists(string directory, string username, string password)
        {
            try
            {
                var request = (FtpWebRequest)WebRequest.Create(directory);
                request.Credentials = new NetworkCredential(username, password);
                request.Method = WebRequestMethods.Ftp.ListDirectory;


                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    return false;
                else
                    return true;
            }
            return true;

        }

Code to Move/Rename file from FTP:




-- To Rename or Move the file on FTP location

public void Main()
        {
            //Creating directory
            if (!FtpDirectoryExists(@<FTPLocationDrive>, <FTPUserName>, <FTPPassword>)
            {
                var reqFolder = (FtpWebRequest)WebRequest.Create(@<FTPLocationDrive>);
                reqFolder.Credentials = new NetworkCredential(<FTPUserName>, <FTPPassword>);
                reqFolder.Method = WebRequestMethods.Ftp.MakeDirectory;
                //reqFolder.Method = WebRequestMethods.Ftp.ListDirectory;
           
                using (var resp = (FtpWebResponse)reqFolder.GetResponse())
                {
                    Console.WriteLine(resp.StatusCode);
                }
            }
            var req = (FtpWebRequest)WebRequest.Create(@<FTPLocationDrive>);
            req.Proxy = null;
            req.Credentials = new NetworkCredential(<FTPUserName>, <FTPPassword>);
            req.Method = WebRequestMethods.Ftp.Rename;

            req.RenameTo = "Archive3/CO1203Y.txt";
            req.GetResponse().Close();
            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
        }

Compress/Decompress a file using C#:


public static void Compress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing hidden and
                // already compressed files.
                if ((File.GetAttributes(fi.FullName)
                    & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    // Create the compressed file.
                    using (FileStream outFile =
                                File.Create(fi.FullName + ".gz"))
                    {
                        using (GZipStream Compress =
                            new GZipStream(outFile,
                            CompressionMode.Compress))
                        {
                            // Copy the source file into
                            // the compression stream.
                            inFile.CopyTo(Compress);

                            Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                                fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                        }
                    }
                }
            }
        }

        public static void Decompress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.
                string curFile = fi.FullName;
                string origName = curFile.Remove(curFile.Length -
                        fi.Extension.Length);

                //Create the decompressed file.
                using (FileStream outFile = File.Create(origName))
                {
                    using (GZipStream Decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream
                        // into the output file.
                        Decompress.CopyTo(outFile);

                        Console.WriteLine("Decompressed: {0}", fi.Name);
                    }
                }
            }
        }

// Path to directory of files to compress and decompress.
        public static string dirpath = @"E:\MyLab\ZipTest";
        DirectoryInfo di = new DirectoryInfo(dirpath);

protected void btnZip_Click(object sender, EventArgs e)
        {
           

            // Compress the directory's files.
            foreach (FileInfo fi in di.GetFiles())
            {
                Compress(fi);
            }
        }

        protected void btnUnZip_Click(object sender, EventArgs e)
        {
            // Decompress all *.gz files in the directory.
            foreach (FileInfo fi in di.GetFiles("*.gz"))
            {
                Decompress(fi);
            }
        }

Namespaces Used : 

using System.IO;
using System.IO.Compression;