Pages

Thursday, November 28, 2013

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

Sunday, October 13, 2013

Display local date and time on the site using javascript

<div id="clock">&nbsp;</div>
<script type="text/javascript">

function init ( )
{
  timeDisplay = document.createTextNode ( "" );
  document.getElementById("clock").appendChild ( timeDisplay );
}

function updateClock ( )
{
  var currentTime = new Date ( );
  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );
  var currentDay = currentTime.getDate ( );
 
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
 
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

var month_name=new Array(12);
month_name[0]="January"
month_name[1]="February"
month_name[2]="March"
month_name[3]="April"
month_name[4]="May"
month_name[5]="June"
month_name[6]="July"
month_name[7]="August"
month_name[8]="September"
month_name[9]="October"
month_name[10]="November"
month_name[11]="December"

  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay+"  "+  month_name[currentTime.getMonth()]+" "+currentDay+","+" " +currentTime.getFullYear();
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
//  document.getElementById("clock").style.fontWeight = 'bold';
}
</script>
<script>
updateClock( );
setInterval('updateClock()', 1000 );
</script>

Thursday, October 10, 2013

Steps to configure MongoDB

Steps to configure MongoDB

Download Mongo
UnZip mongodb-win32-x86_64-2.4.6.zip file in any folder (E:\MongoDB)
Create E:\MongoDB\data\db folder to store database
Open command prompt and run


E:\MongoDB\mongodb\bin\mongod.exe --dbpath E:\MongoDB\data\db\localDB   ==== to set database path

The above command prompt window should remain open so that you can work on database.
Now open another command prompt and run E:\MongoDB\mongodb\bin\mongo   ---- if successfull the below text will appear with a command prompt as ">" here you can execute commands
MongoDB shell version: 2.4.6
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
       
http://docs.mongodb.org/
Questions? Try the support group
       
http://groups.google.com/group/mongodb-user
>Execute your commands here

Download Mongo Interface (Robomongo) http://robomongo.org/ This is a UI tool to execute queries

Folder Structure
All local database localtion E:\MongoDB\data\db\localDB
Backup Folder
E:\MongoDB\dump\localDB\mydb
E:\MongoDB\dump\staging\mongodump-2013-10-10\dbName


BACKUP
mongodump -d <our database name> -o <directory_backup>


Take backup of local database without running the mongod instance
Run on command prompt
E:\MongoDB\mongodb\bin\mongodump --dbpath E:\MongoDB\data\db\localDB -o E:\MongoDB\dump\localDB


Take backup of remote database without running the mongod instance
E:\MongoDB\mongodb\bin\mongodump --host <servername> --port 27017 --username <username> --password <password> -db <dbname> --out E:\MongoDB\dump\staging\mongodump-2013-10-10

RESTORE - From local existing DB
mongorestore <directory_backup>

The mongorestore utility restores a binary backup created by mongodump. By default, mongorestore looks for a database backup in the dump/ directory

Connect to the the mongod instance for local restore
Local
E:\MongoDB\mongodb\bin\mongod.exe --dbpath E:\MongoDB\data\db\localDB   === Instance connection to the database

E:\MongoDB\mongodb\bin\mongorestore E:\MongoDB\dump\localDB  === Run this to restore from backup directory
--Staging
E:\MongoDB\mongodb\bin\mongod.exe --dbpath E:\MongoDB\data\db\localDB   === Instance connection to the database

E:\MongoDB\mongodb\bin\mongorestore E:\MongoDB\dump\staging\mongodump-2013-10-10\dbName === === Run this to restore from backup directory


 

Monday, October 7, 2013

Proper Case or Title case in c#

string[] values = { "a tale of two cities", "gROWL to the rescue",
                          "inside the US government", "sports and MLB baseball",
                          "The Return of Sherlock Holmes", "UNICEF and children"};

      TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
      foreach (var value in values)
         Console.WriteLine("{0} --> {1}", value, ti.ToTitleCase(value));


// The example displays the following output:
// a tale of two cities --> A Tale Of Two Cities
// gROWL to the rescue --> Growl To The Rescue
// inside the US government --> Inside The US Government
// sports and MLB baseball --> Sports And MLB Baseball
// The Return of Sherlock Holmes --> The Return Of Sherlock Holmes
// UNICEF and children --> UNICEF And Children