How to compress and decompress data in c#

In this post,I will show you how to compress and decompress data in c# using GzipStream class.Below is the code for the same

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.IO.Compression;
namespace CompressDecompress
{
    class Program
    {
    const string CompressFilePath = @"C:\temp\data.zip";
    const string Filename = @"C:\temp\data.txt";
    private const string DeCompressFilePath = @"C:\temp\data1.txt";
    static void Main(string[] args)
        {
            Compress(Filename);
            Decompress(CompressFilePath);
        }
    private static void Decompress(string compressFilePath)
        {
    using (FileStream inputStream = new FileStream(compressFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
    using (FileStream outputStream = new FileStream(DeCompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
    using (GZipStream gZipStream = new GZipStream(inputStream, CompressionMode.Decompress))
                    {
                        gZipStream.CopyTo(outputStream);
                    }
                }
            }
        }
    private static void Compress(string filename)
        {
    using (FileStream inputStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                Console.WriteLine("Size Before Compression:{0} KB", inputStream.Length / 1024);
    using (FileStream outputStream = new FileStream(CompressFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
    using (GZipStream gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
                    {
                        inputStream.CopyTo(gZipStream);
                        Console.WriteLine("Size after Compression:{0} KB", outputStream.Length / 1024);
                    }
                }
            }
        }
    }
}

How to read pdf document properties in asp.net

In this post, I will show you how to read the pdf document properties in asp.net.As we know that there is no- such  in-built class in .net framework that read the pdf document.So,for this demo,I will used third-party library iTextSharp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PdfPropertiesReader.aspx.cs"
    Inherits="PdfPropertiesReader" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="pdfProperties" runat="server">
        </div>
    </div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Read Pdf Properties" />
    </form>
</body>
</html>
using System;
using System.Collections;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;

public partial class PdfPropertiesReader : System.Web.UI.Page
{
    private const string FileNmae = @"C:\\temp\\asp.pdf";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder stringBuilder = new StringBuilder();
            // create a reader (constructor overloaded for path to local file or URL)
            PdfReader reader = new PdfReader(FileNmae);
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
            // file properties
            Hashtable infodict = reader.Info;
            foreach (DictionaryEntry kvp in infodict)
            {
                stringBuilder.Append(kvp.Key + "=>" + kvp.Value + "</br>");
            }

            pdfProperties.InnerHtml = stringBuilder.ToString();
        }
        catch (Exception exception)
        {

            Response.Write(exception.Message);
        }
    }
}

How to convert IEnumerable to Html table in asp.net

In this post I will show how to convert IEnumerable to string (Html table).Assume you have a customer class which has three properties named FirstName,LastName and Age.Now,you want to display customer collection on UI.
For this I have created following method which retrives propertyname and value dynamically (using reflection) and return result as string
public static string ToHtmlTable(IEnumerable list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .headerStyle
        {
            background-color: #abc;
        }
        .rowStyle
        {
            background-color: #def;
        }
        .alternateRowStyle
        {
            background-color: #aabbcc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="table" runat="server">
        </div>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        table.InnerHtml = ToHtmlTable(EmployeeDAL.Employees, "", "headerStyle", "rowStyle", "alternateRowStyle");
    }

    public static string ToHtmlTable<T>(IEnumerable<T> list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)
    {

        var result = new StringBuilder();
        if (String.IsNullOrEmpty(tableSyle))
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\">");
        }
        else
        {
            result.Append("<table id=\"" + typeof(T).Name + "Table\" class=\"" + tableSyle + "\">");
        }

        var propertyArray = typeof(T).GetProperties();
        foreach (var prop in propertyArray)
        {
            if (String.IsNullOrEmpty(headerStyle))
            {
                result.AppendFormat("<th>{0}</th>", prop.Name);
            }
            else
            {
                result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, prop.Name);
            }
        }

        for (int i = 0; i < list.Count(); i++)
        {
            if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle))
            {
                result.AppendFormat("<tr class=\"{0}\">", i % 2 == 0 ? rowStyle : alternateRowStyle);
            }
            else
            {
                result.AppendFormat("<tr>");
            }

            foreach (var prop in propertyArray)
            {
                object value = prop.GetValue(list.ElementAt(i), null);
                result.AppendFormat("<td>{0}</td>", value ?? String.Empty);
            }
            result.AppendLine("</tr>");
        }
        result.Append("</table>");
        return result.ToString();
    }
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

}
public class EmployeeDAL
{
    public static List<Employee> Employees
    {
        get
        {
            return new List<Employee>()
                       {
                           new Employee(){FirstName = "F001",LastName = "L001",Age = 31},
                           new Employee(){FirstName = "F002",LastName = "L002",Age = 32},
                           new Employee(){FirstName = "F003",LastName = "L003",Age = 33},
                           new Employee(){FirstName = "F004",LastName = "L004",Age = 34},
                       };
        }
    }
}

How to fetch header info from given url

In this post I will show how to fetch header info from given url
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace SNIPPET_CS
{
    public class HeaderInfo
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public static List<HeaderInfo> GetHttpResponseHeaders(string url)
        {
            List<HeaderInfo> headerList = new List<HeaderInfo>();
            WebRequest webRequestObject = WebRequest.Create(url);
            WebResponse responseObject = webRequestObject.GetResponse();
            if (responseObject != null)
            {
                headerList.AddRange(from string headerKey in responseObject.Headers
                                    select new HeaderInfo()
                                               {
                                                   Key = headerKey,
                                                   Value = responseObject.Headers[headerKey]
                                               });
                responseObject.Close();
            }

            return headerList;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {

            // Retrieve headers:
            var headers = HeaderInfo.GetHttpResponseHeaders("http://www.google.com");

            // And output them:
            foreach (HeaderInfo headerKey in headers)
                Console.WriteLine("{0}: {1}", headerKey.Key, headerKey.Value);
        }
    }
}

How to send output of console application to file

In this example,I will show how to send console output to file in c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace SNIPPET_CS
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleOutput();
            Console.WriteLine("Console output saved successfully");
            Console.ReadLine();
        }
        private static void ConsoleOutput()
        {
            const string applicationPath = @"D:\Windows\System32\ipconfig.exe";
            //string ApplicationArguments = "-c -x";

            // Create a new process object
            Process processObj = new Process();

            // StartInfo contains the startup information of
            // the new process
            processObj.StartInfo.FileName = applicationPath;
            //ProcessObj.StartInfo.Arguments = ApplicationArguments;

            // These two optional flags ensure that no DOS window
            // appears
            processObj.StartInfo.UseShellExecute = false;
            processObj.StartInfo.CreateNoWindow = true;

            // If this option is set the DOS window appears again :-/
            // ProcessObj.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            // This ensures that you get the output from the DOS application
            processObj.StartInfo.RedirectStandardOutput = true;

            // Start the process
            processObj.Start();

            // Wait that the process exits
            processObj.WaitForExit();

            // Now read the output of the DOS application
            string result = processObj.StandardOutput.ReadToEnd();
            WriteToFile(result);
        }
        private static void WriteToFile(string result)
        {
            using (FileStream stream = new FileStream(@"C:\temp\a.txt", FileMode.OpenOrCreate, FileAccess.Write))
            {

                byte[] buffer = Encoding.Default.GetBytes(result);
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();
            }
        }
    }
}