Pages

Tuesday, December 31, 2013

Convert XmlNodeList to DataTable


XmlDocument xmlDoc = new XmlDocument();
XmlNodeList nodes;
string xmlResp;
// convert string to stream            
byte[] byteArray = Encoding.ASCII.GetBytes(xmlResp);
MemoryStream stream = new MemoryStream(byteArray);
xmlDoc = ConvertStreamToXMLDocument(stream);
nodes = xmlDoc.GetElementsByTagName("Items");
DataTable dt = Utility.ConvertXmlNodeListToDataTable(nodes);

public static DataTable ConvertXmlNodeListToDataTable(XmlNodeList xnl)
{
    DataTable dt = new DataTable();
    int TempColumn = 0;

    foreach (XmlNode node in xnl.Item(0).ChildNodes)
    {
        TempColumn++;
        DataColumn dc = new DataColumn(node.Name, System.Type.GetType("System.String"));
        if (dt.Columns.Contains(node.Name))
        {
            dt.Columns.Add(dc.ColumnName = dc.ColumnName + TempColumn.ToString());
        }
        else
        {
            dt.Columns.Add(dc);
        }
    }

    int ColumnsCount = dt.Columns.Count;
    for (int i = 0; i < xnl.Count; i++)
    {
        DataRow dr = dt.NewRow();
        for (int j = 0; j < ColumnsCount; j++)
        {
            //dr[j] = xnl.Item(i).ChildNodes[j].InnerText;
            if (xnl.Item(i).ChildNodes[j] != null)
                dr[j] = xnl.Item(i).ChildNodes[j].InnerText;
            else
                dr[j] = null;
        }
        dt.Rows.Add(dr);
    }
    return dt;
}

Read values from cookies

const string COOKIE_NAME = "xyz";
string subject = "";
if (HttpContext.Current.Request.Cookies[COOKIE_NAME] != null)
{
    allClaims = new Dictionary<String, String>();

    HttpCookie authCookie = HttpContext.Current.Request.Cookies[COOKIE_NAME];

    NameValueCollection col = new NameValueCollection(authCookie.Values);
    String[] keyNames = col.AllKeys;
    foreach (string key in keyNames)
    {
        allClaims.Add(key, col.GetValues(key)[0]);
    }

    subject = authCookie["subject"].ToString();
}   

Write DataTable to Excel

public void WriteToExcel(Excel.Worksheet worksheet, DataTable dataTable)
{
    var columns = dataTable.Columns.Count;
    var rows = dataTable.Rows.Count;
    var startCell = (Excel.Range)worksheet.Cells[1, 1];
    var endCell = (Excel.Range)worksheet.Cells[rows + 1, columns];
    var writeRange = (Excel.Range)worksheet.get_Range(startCell, endCell);
    var data = new object[rows + 1, columns];
    //Header                   
    for (var column = 0; column < columns; column++)
    {
        data[0, column] = dataTable.Columns[column].ColumnName;
    }
    for (var row = 1; row <= rows; row++)
    {
        for (var column = 0; column < columns; column++)
        {
            data[row, column] = dataTable.Rows[row - 1][column].ToString();
        }
    }
    worksheet.Rows.Clear();
    writeRange.Value = data;
    worksheet.Name = "test";   
}

Convert JSON to XML

Run below command in Visual Studio for the project
PM> Install-Package Newtonsoft.Json

XmlDocument xmlDoc = new XmlDocument();
xmlDoc = JsonConvert.DeserializeXmlNode("{records:{items:" + xmlResp + "}}");

Convert string to stream to XML document

// convert string to stream       
XmlDocument xmlDoc = new XmlDocument();    
byte[] byteArray = Encoding.ASCII.GetBytes(xmlResp);
MemoryStream stream = new MemoryStream(byteArray);
xmlDoc = ConvertStreamToXMLDocument(stream);
private XmlDocument ConvertStreamToXMLDocument(Stream stream)
{
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument = new XmlDocument();
    //load into XDocument
    XDocument xDocument = XDocument.Load(stream);

    //scrub the namespaces out!
    xDocument.Descendants().Attributes().Where(x => x.IsNamespaceDeclaration).Remove();
    // convert to xml document
    using (var xmlReader = xDocument.CreateReader())
    {
        xmlDocument.Load(xmlReader);
    }

    // remove default namespace
    xmlDocument.LoadXml(xmlDocument.OuterXml.Replace(xmlDocument.DocumentElement.NamespaceURI, ""));
    xmlDocument.DocumentElement.RemoveAllAttributes();

    return xmlDocument;
}

Calling & receiving response of any webpage C# - ASP.Net

public void CallWebPage(string url)
{
    WebRequest request = WebRequest.Create(url);
    //WebProxy proxy = new WebProxy("fresproxy1:8080");
    //proxy.UseDefaultCredentials = true;
    //request.Proxy = proxy;
    request.Headers.Add("Key", Value);
    request.Headers.Add("Key", Value);
    WebResponse objWebResponse = request.GetResponse();
    Stream objWebStream = objWebResponse.GetResponseStream();
    string response = "";
    string OAuthToken="";
    using (StreamReader objStreamReader = new StreamReader(objWebStream))
    {
        response = objStreamReader.ReadToEnd();
    }
    //if response is json - deserialize that into dictionaries for easier operation - System.Web.Extensions.dll
   JavaScriptSerializer desSSO = new JavaScriptSerializer();
   IDictionary userInfo = desSSO.Deserialize<Dictionary<string, string>>(response);
   foreach (DictionaryEntry entry in userInfo)
   {
       if (entry.Key.ToString() == "abc")
       {
           OAuthToken = entry.Value.ToString();
       }
   }
}

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

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

Wednesday, September 11, 2013

Async function Call on button click or page load

public delegate string LoadDelegateR(string userName, string reportingDate, Dictionary<string, string> functions, string jobNumber, out string message);

protected void Page_Load(object sender, EventArgs e)
{
 // call asynchronously                       
 LoadDelegateR d = new LoadDelegateR(ImportData);
 d.BeginInvoke(user, txtPeriod.Text.Trim(), functions, txtJobNumber.Text.Trim(), out message, new System.AsyncCallback(SendNotification), null);
}

public override string ImportData(string username, string reportingDate, Dictionary<string, string> functions, string jobNumber, out string message)
{
}

public void SendNotification(IAsyncResult iRes)
{
 try
 {
  AsyncResult ar = (AsyncResult)iRes;
  LoadDelegateR bp = (LoadDelegateR)ar.AsyncDelegate;
  string result = bp.EndInvoke(out message, iRes);
 }
 catch (Exception ex)
 {
  message = "Error in loading the data.Please contact admin.";
 }
}

Sort the IEnumerable list using Linq

var sortedEngData = engData.OrderByDescending(c => c.CausalCountPeriod).ThenByDescending(c => c.CausalCountToDate); 

Get distinct rows from datatable using Linq

var engData = (from dr in dtEng.AsEnumerable()
       where Convert.ToString(dr["job_number"]) == jobNumber
       && Convert.ToString(dr["period"]) == per.Periods
       && Convert.ToString(dr["office_short_name"]) == off.OfficeShortName
       select new
       {
        GroupCode = Convert.ToString(dr["group_code"]),
        GroupShortName = Convert.ToString(dr["group_short_name"]),
        CausalCountPeriod = (dr["casual_count_period"] == DBNull.Value || Convert.ToString(dr["casual_count_period"]) == "") ? Convert.ToInt32("0") : Convert.ToInt32(dr["casual_count_period"]),
        CausalCountToDate = (dr["casual_count_to_date"] == DBNull.Value || Convert.ToString(dr["casual_count_to_date"]) == "") ? Convert.ToInt32("0") : Convert.ToInt32(dr["casual_count_to_date"]),
        ReportingPeriod = Convert.ToString(dr["reporting_period"])

       }).Distinct();

Filter data and store it in datatable

DataTable dtEng = new DataTable();
DataRow[] drEngg = dt.Select("work_type = 'Engineering'");
if (drEngg.Length > 0)
{
 dtEng = drEngg.CopyToDataTable();
}

Friday, September 6, 2013

Remove totally blank rows from datatable

Below code will remove totally blank rows from datatable that were fetched from excel during upload

DataTable dtStupByDate = dtStupByDate.Rows.Cast<DataRow>().Where(row => !row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).CopyToDataTable();

Useful Jquery syntax

// Checks the count of the checkboxes checked
var n = $("input[type=checkbox]:checked").length;
//Prevents the button submit
$("#btnUpload").click(function (event) { event.bubbles = false; });
//Checks if radio button is checked
$('#radConst_0').is(':checked')
//Checks if check box is checked
$('#chkConst').is(':checked')
// Makes the control disable
$("#divRwkFunctions").attr("disabled", "disabled");
// clears all the checked boxes
var m = $("input[type=checkbox]").removeAttr('checked');
// Select the radio button
$('#ctl00_MainContent_radConst_1').attr('checked', 'checked');
// Adds the click event on all the checkboxes
$("input[type=checkbox]").click(function () {
                chkFunctionStatus();
            });
//Clear the File upload control//For IE
$("#fUpload").replaceWith($("#ctl00_MainContent_fUpload").clone(true));
//For other browsers
$("#fUpload").val("");

Show loading image for 5 secs after button click

function showLoading() {
 document.getElementById('myHiddenDiv').style.display = "";
 setTimeout('document.images["myAnimatedImage"].src="work.gif"', 500000000);  
}


<span id='myHiddenDiv' style='display: none;' align="Center">
 <img id="myAnimatedImage" src="Images/ajax-loader.gif" align="middle" alt="" />
</span>


<asp:Button ID="btnUpload" runat="server" Text="Submit" CssClass="button" OnClientClick="return showDiv();" />

Jquery datepicker with month and year only


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml" xml:lang="en">
<head><title>
 Home Page
</title><link href="Styles/Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
        $(document).ready(
    function () {
        $('#txtPeriod').datepicker(
        {
            changeMonth: true,
            changeYear: true,
            dateFormat: 'MM yy',
            onClose: function () {
                var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
            },
            beforeShow: function () {
                if ((selDate = $(this).val()).length > 0) {
                    iYear = selDate.substring(selDate.length - 4, selDate.length);
                    iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));
                    $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
                    $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
                }
            }
        });
    });
</script>
<style>
        .ui-datepicker-calendar
        {
            display: none;
        }
        .red
        {
            color: Red;
            font-size: 10px;
        }
       
        td
        {
            text-align: left;
        }
        #divValidate
        {
            text-align: center;
        }
    </style>
<div id="divPeriod" style="display: none;">
 Period :
 <asp:TextBox ID="txtPeriod" runat="server" Width="100px" onkeydown="return false;"></asp:TextBox>
</div>
</body>
</html>

Tuesday, May 21, 2013

405 method not allowed web api (PUT & DELETE)

Just add these lines to the web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

Wednesday, May 8, 2013

Passing sorting parameter to stored procedure


In Data-driven application or website, dynamic sorting is common need. Ideally we should write stored procedure for dynamic sorting.
We found nice solution for above problem. Bellow stored procedure fetch ordered data with passed parameter. There two parameters for dynamic sorting stored procedure. Parameter @sortDirection pass for order direction (asc or desc). Second parameter @sortCol for pass sorting field name.


Code
=====================================================-
  -- Description:   Example of Fetch Data With Sorting Parameter
 =====================================================
 Create PROCEDURE Product_Sorting_Parameter
     -- Add the parameters for the stored procedure here
     @sortDirection as varchar(5),
     @sortCol as varchar(50)
 AS
 BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from

    SET NOCOUNT ON;
     -- Select Query
    SELECT
         [ProductID] ,[Name],[ProductNumber],[Color],[ListPrice],[Size]     
     FROM         [AdventureWorks2008R2].[Production].[Product]
     ORDER BY
      -- Name
      Case WHEN @sortCol = 'Name' and @sortDirection = 'asc' THEN Name end,
      Case WHEN @sortCol = 'Name' and @sortDirection = 'desc' THEN Name end desc,
      -- Size
      Case WHEN @sortCol = 'Size' and @sortDirection = 'asc' THEN Size end,
      Case WHEN @sortCol = 'Size' and @sortDirection = 'desc' THEN Size end desc,
      -- Color
      Case WHEN @sortCol = 'Color' and @sortDirection = 'asc' THEN Color end,
      Case WHEN @sortCol = 'Color' and @sortDirection = 'desc' THEN Color end desc,
      -- Price
      Case WHEN @sortCol = 'Price' and @sortDirection = 'asc' THEN ListPrice end,
      Case WHEN @sortCol = 'Price' and @sortDirection = 'desc' THEN ListPrice end desc
 END
 GO


Execution
exec Product_Sorting_Parameter 'asc', 'Name'

Thursday, April 4, 2013

Without opening popup window Print Part Of A Web Page With jQuery


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test1.aspx.cs" Inherits="WebApplication1.Test1" %>

<!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 id="Head1" runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.print.js" type="text/javascript"></script>
    <script type="text/javascript">

        // When the document is ready, initialize the link so
        // that when it is clicked, the printable area of the
        // page will print.
        $(function () {
            // Hook up the print link.
            $("a")
.attr("href", "javascript:void( 0 )")
.click(
function () {
    // Print the DIV.
    $(".printable").print();
    // Cancel click event.
    return (false);
}
);
        }
);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        Print Part of a Page With jQuery
    </h1>
    <p>
        <a>Print Bio</a>
    </p>
    <div class="printable">
        <h2>
            Jen Rish
        </h2>
        <p>
            Jen Rish, upcoming fitness and figure model has some crazy developed legs!
        </p>
        <p>
            <img src="Form2.png" width="380" height="570" alt="Jen Rish Has Amazing Legs!" />
        </p>
        <p>
            I bet she does some <strong>serious squatting</strong>!
        </p>
    </div>
    </form>
</body>
</html>

=====================jQuery.print.js===========


// Create a jquery plugin that prints the given element.
jQuery.fn.print = function(){
// NOTE: We are trimming the jQuery collection down to the
// first element in the collection.
if (this.size() > 1){
this.eq( 0 ).print();
return;
} else if (!this.size()){
return;
}

// ASSERT: At this point, we know that the current jQuery
// collection (as defined by THIS), contains only one
// printable element.

// Create a random name for the print frame.
var strFrameName = ("printer-" + (new Date()).getTime());

// Create an iFrame with the new name.
var jFrame = $( "<iframe name='" + strFrameName + "'>" );

// Hide the frame (sort of) and attach to the body.
jFrame
.css( "width", "1px" )
.css( "height", "1px" )
.css( "position", "absolute" )
.css( "left", "-9999px" )
.appendTo( $( "body:first" ) )
;

// Get a FRAMES reference to the new frame.
var objFrame = window.frames[ strFrameName ];

// Get a reference to the DOM in the new frame.
var objDoc = objFrame.document;

// Grab all the style tags and copy to the new
// document so that we capture look and feel of
// the current document.

// Create a temp document DIV to hold the style tags.
// This is the only way I could find to get the style
// tags into IE.
var jStyleDiv = $( "<div>" ).append(
$( "style" ).clone()
);

// Write the HTML for the document. In this, we will
// write out the HTML of the current element.
objDoc.open();
objDoc.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" );
objDoc.write( "<html>" );
objDoc.write( "<body>" );
objDoc.write( "<head>" );
objDoc.write( "<title>" );
objDoc.write( document.title );
objDoc.write( "</title>" );
objDoc.write( jStyleDiv.html() );
objDoc.write("<style type=\"text/css\"> @import url(\"./CSS.css\") </style>");
//console.log(this.html());
objDoc.write( "</head>" );
objDoc.write( this.html() );
objDoc.write( "</body>" );
objDoc.write( "</html>" );
objDoc.close();

// Print the document.
objFrame.focus();
objFrame.print();

// Have the frame remove itself in about a minute so that
// we don't build up too many of these frames.
setTimeout(
function(){
jFrame.remove();
},
(60 * 1000)
);
}

======================

Wednesday, April 3, 2013

Zoom In Zoom Out Contents of Page using JQuery


// Include JQuery File 
<script type="text/javascript">
        $(document).ready(function () {
            var currZoom = $("#divpnlChart").css("zoom");
            if (currZoom == 'normal') currZoom = 1; // For IE


            $(".zoomIn").click(function () {
                currZoom *= 1.2;
                $("#divpnlChart").css("zoom", currZoom);
                $("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
                $("#divpnlChart").css("-moz-transform-origin", "0 0");


            });
            $(".zoomOff").click(function () {
            $("#divpnlChart").css("zoom", 1);
$("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
            $("#divpnlChart").css("-moz-transform-origin", "0 0");


            });
            $(".zoomOut").click(function () {
                currZoom *= .8;
              $("#divpnlChart").css("zoom", currZoom);
              $("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
              $("#divpnlChart").css("-moz-transform-origin", "0 0");


            });
        });
</script>


//  HTML Code


<span class="zoomIn" style="font-size:120%">A</span>
<span class="zoomOff">A</span>
<span class="zoomOut" style="font-size:80%">A</span>


<div id="divpnlChart" runat="server" style="float: left; width: 85%;">
    //  your content
</div>

Move div up / down / left / right zoom in zoom out using button - jQuery


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="WebApplication1.Demo" %>

<!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>
    <title></title>
    <style type="text/css">
        .block
        {
            background-image:url('Form.png');
            width: 263px;
            height: 103px;
            position: relative;
            left: 50px;
            top: 50px;
        }
        .innerblock
        {
            background-color: yellow;
            position: relative;
            left: 5px;
            top: 5px;
        }
    </style>
   <%-- <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>--%>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  
      

</head>
<body>
    <button id="top">
        Shift Down</button>
    <input type="text" id="txtTopBottom" value="5" />
    <button id="bottom">
        Shift Up</button>
    <button id="left">
        Shift Left</button>
    <input type="text" id="txtLeftRight" value="5" />
    <button id="right">
        Shift Right</button>

<div align="left"><br>
<input type="radio" id="BothTextAndImage" name="group1" value="BothTextAndImage" checked="checked"/> Both Text and Image<br/>
<input type="radio" id="ChangeColor" name="group1" value="ChangeColor" /> Change Color<br/>
<input type="radio" id="OnlyText" name="group1" value="OnlyText" /> Only Text<br/>
<hr />
</div>

<div align="left"><br>
<input type="radio" id="z100" name="group2" value="100" checked="checked"/> 100%<br/>
<input type="radio" id="z80" name="group2" value="80" /> 80%<br/>
<input type="radio" id="z60" name="group2" value="60" /> 60%<br/>

</div>



    <div class="block">
        <div class="innerblock">
            <div class="html">
                <div style="float:left"><input type="text" id="Text2" value="N" style="width:50px" /></div>
                <div style="float:left"><input type="text" id="Text1" value="A" style="width:50px" /></div>
                <div style="float:left"><input type="text" id="Text3" value="C" style="width:50px" /></div>
                <div style="float:left"><input type="text" id="Text4" value="L" style="width:50px" /></div>                
            </div>
        </div>
    </div>
    <br />
    
   <script type="text/javascript">


             $("#right").click(function () {
                 var currentVal = parseInt($("#txtLeftRight").val());
                 if (currentVal != NaN) {
                     $("#txtLeftRight").val(currentVal + 1);
                     $(".block").animate({ "left": "+=5px" }, "slow");
                 }
             });
             $("#left").click(function () {
                 var currentVal = parseInt($("#txtLeftRight").val());
                 if (currentVal != NaN) {
                     $("#txtLeftRight").val(currentVal - 1);
                     $(".block").animate({ "left": "-=5px" }, "slow");
                 }
             });
             $("#top").click(function () {
                 var currentVal = parseInt($("#txtTopBottom").val());
                 if (currentVal != NaN) {
                     $("#txtTopBottom").val(currentVal + 1);
                     $(".block").animate({ "top": "+=5px" }, "slow");
                 }
             });
             $("#bottom").click(function () {
                 var currentVal = parseInt($("#txtTopBottom").val());
                 if (currentVal != NaN) {
                     $("#txtTopBottom").val(currentVal - 1);
                     $(".block").animate({ "top": "-=5px" }, "slow");
                 }
             });

             $("#BothTextAndImage").click(function () {
                 $(".block").css({ 'background-image': 'url("Form.png")' });
                 }
             );
             $("#ChangeColor").click(function () {
                 $(".block").css({ 'background-image': 'url("Form2.png")' });
             }
             );
             $("#OnlyText").click(function () {
                 $(".block").css({ 'background-image': 'none' });
                 }
             );
             ////////////////

             $("#z100").click(function () {
                 $(".block").animate({ zoom: 1.5 });
             }
             );
             $("#z80").click(function () {
                 $(".block").animate({ zoom: 1 });
             }
             );
             $("#z60").click(function () {
                 $(".block").animate({ zoom: 0.6 });
             }
             );



     ///////////
    </script>
</body>
</html>