Pages

Thursday, November 28, 2013

Export To Excel with Cell Formating

 using System.Text;
          using System.IO;
          using System.Drawing;

           Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition",
            "attachment;filename=GridViewExport.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView GridView1 = new GridView();
            GridView1.DataSource = ds;
            GridView1.DataBind();
            GridView1.AllowPaging = false;

            GridView1.DataBind();
            //Change the Header Row back to white color
            GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
            //Apply style to Individual Cells

            GridView1.HeaderRow.Style.Add("background-color", "green");
            //GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
            //GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
            //GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                //Change Color back to white
                row.BackColor = System.Drawing.Color.White;
                //Apply text style to each Row

               // row.Attributes.Add("class", "textmode");

                //Apply style to Individual Cells of Alternating Row
                if (i % 2 != 0)
                {
                    row.Style.Add("background-color", "#C2D69B");
                    //row.Cells[1].Style.Add("background-color", "#C2D69B");
                }

            }
            GridView1.RenderControl(hw);
            //style to format numbers to string
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

Format Class object into JSON or XML

protected void FormatOutgoingMessage<T>(T graph, string format)
{
    if (format == null)
    {
        format = "json";
    }
    bool flag = format.ToUpper() == "XML";
    WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers;
    string s = string.Empty;
    string str2 = headers.Get("Accept");
    if (str2 != null)
    {
        bool flag2 = str2.ToLower().Contains("application/json");
        if ((format.ToUpper() == "JSON") || (flag2 && !flag))
        {
            s = Utility.ToJson<T>(graph);
            HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
            HttpContext.Current.Response.Write(s);
        }
        else
        {
            s = Utility.SerializeDataContract<T>(graph);
            HttpContext.Current.Response.ContentType = "application/xml";
            HttpContext.Current.Response.Write(s);
        }
    }
    else
    {
        s = Utility.SerializeDataContract<T>(graph);
        HttpContext.Current.Response.ContentType = "application/xml";
        HttpContext.Current.Response.Write(s);
    }
}

public static string ToJson<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream stream = new MemoryStream();
    serializer.WriteObject(stream, obj);
    return Encoding.Default.GetString(stream.ToArray());
}

public static string SerializeDataContract<T>(T graph)
{
    return Serialize<T>(graph, Encoding.UTF8);
}

 

Export To XLS

protected void Page_Load(object sender, EventArgs e)
    {
     
               try
               {

                   SqlDataAdapter da = new SqlDataAdapter("Select * from Features", "Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=;");
                   DataSet ds = new DataSet();
                   da.Fill(ds);

                 
                   string date = string.Format("{0:dd-MM-yyyy}", DateTime.Now);
                   string strFileName = "Test";
                   string path = strFileName  + "_" + date + ".xls";


                   Directory.SetCurrentDirectory(Server.MapPath("~/"));// Changed the default location of the storage of the file.
                   StreamWriter sw = File.AppendText(Path.Combine(strFileName + "_" + date + ".xls")); //Append the file name with the file path.
                   for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                   {

                       sw.AutoFlush = true;
                       sw.Write(ds.Tables[0].Columns[i].ToString() + "\t");
                   }
                   sw.Write("\n");
                   for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                   {
                       for (int x = 0; x < ds.Tables[0].Columns.Count; x++)
                       {
                           sw.Write(ds.Tables[0].Rows[i][ds.Tables[0].Columns[x].ToString()].ToString() + "\t");
                       }
                       sw.Write("\n");
                   }

                   sw.Write("\n");
               }

               catch (Exception)
               {

                   throw;
               }
               finally
               {

                 
               }
    }

Encrypt Decrypt string in C# - ASP.Net

public class EncryptDecryptUtil
{
 public static string Decrypt(string strData)
 {
  if (strData.Length > 0)
   return DecodeFrom64(strData);
  else
   return strData;
 }

 public static string Encrypt(string strData)
 {
  if (strData.Length > 0)
   return EncodeBase64(strData);
  else
   return strData;
 }

 internal static string DecodeFrom64(string encodedData)
 {
  try
  {
   byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
   string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
   return returnValue;
  }
  catch (Exception e)
  {
   throw new Exception("Error in EncodeBase64" + e.Message);
  }
 }

 internal static string EncodeBase64(string data)
 {
  try
  {
   byte[] toencode_byte = System.Text.ASCIIEncoding.ASCII.GetBytes(data);
   string result = Convert.ToBase64String(toencode_byte);
   return result;
  }
  catch (Exception e)
  {
   throw new Exception("Error in EncodeBase64" + e.Message);
  }
 }
}

Validate user to on windows user account - Windows Identity Impersonation


IntPtr accessToken = IntPtr.Zero;
WindowsImpersonationContext impersonationContext = null;
try
{
 if (iFormsServiceUtil.ImpersonateValidUser(userName, domain, password, out impersonationContext))
 {
 }
}
catch (Exception ex)
{

}
finally
{
 if(impersonationContext != null)
  iFormsServiceUtil.UndoImpersonation(ref impersonationContext);
}


#region Windows Identity Impersonation

 private const int LOGON32_LOGON_INTERACTIVE = 2;
 private const int LOGON32_PROVIDER_DEFAULT = 0;

 //private WindowsImpersonationContext impersonationContext;
 [DllImport("advapi32.dll")]
 private static extern int LogonUserA(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

 [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 private static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

 [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
 private static extern bool RevertToSelf();

 [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
 private static extern bool CloseHandle(IntPtr handle);

 internal static bool ImpersonateValidUser(String userName, String domain, String password, out WindowsImpersonationContext impersonationContext)
 {
  WindowsIdentity tempWindowsIdentity;
  IntPtr token = IntPtr.Zero;
  IntPtr tokenDuplicate = IntPtr.Zero;
  impersonationContext = null;

  if (RevertToSelf())
  {
   if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
   {
    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
    {
     tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
     impersonationContext = tempWindowsIdentity.Impersonate();
     if (impersonationContext != null)
     {
      CloseHandle(token);
      CloseHandle(tokenDuplicate);
      return true;
     }
    }
   }
  }
  if (token != IntPtr.Zero)
   CloseHandle(token);
  if (tokenDuplicate != IntPtr.Zero)
   CloseHandle(tokenDuplicate);

  return false;
 }

 internal static void UndoImpersonation(ref WindowsImpersonationContext impersonationContext)
 {
  impersonationContext.Undo();
 }

#endregion