Thursday, October 13, 2011

Date Formatting in C# with region and sql compatible

 public string myDateFormat(string p)
    {
        // throw new NotImplementedException();

        IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
        String datetime = p.ToString();
        DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
        return dt.ToString();
    }

Wednesday, October 12, 2011

Static Classes and Static Class Members (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx

Static Constructors (C# Programming Guide)

The following list provides the main features of a static class:
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization. For more information, see Static Constructors (C# Programming Guide).
-----------------------------------------------------------------------



A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.
Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object instance is required.
C# does not support static local variables (variables that are declared in method scope).
You declare static class members by using the static keyword before the return type of the member, as shown in the following example:
public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;

    // Other non-static fields and properties...
}

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member, as shown in the following example:
Automobile.Drive();
int i = Automobile.NumberOfWheels;

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.

Monday, October 10, 2011

Javascript Trim Member Functions


function trim(stringToTrim) {
 return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
 return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
 return stringToTrim.replace(/\s+$/,"");
}

// example of using trim, ltrim, and rtrim
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");
 
 
----------------------------------------------------
 

function ltrim(str) { 
 for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++);
 return str.substring(k, str.length);
}
function rtrim(str) {
 for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j--) ;
 return str.substring(0,j+1);
}
function trim(str) {
 return ltrim(rtrim(str));
}
function isWhitespace(charToCheck) {
 var whitespaceChars = " \t\n\r\f";
 return (whitespaceChars.indexOf(charToCheck) != -1);
} 

Friday, September 30, 2011

Date Formatting in C#

Date Formatting in C#




<%= String.Format("{specifier}", DateTime.Now) %>
Specifier Description Output
d Short Date 08/04/2007
D Long Date 08 April 2007
t Short Time 21:08
T Long Time 21:08:59
f Full date and time 08 April 2007 21:08
F Full date and time (long) 08 April 2007 21:08:59
g Default date and time 08/04/2007 21:08
G Default date and time (long) 08/04/2007 21:08:59
M Day / Month 08 April
r RFC1123 date Sun, 08 Apr 2007 21:08:59 GMT
s Sortable date/time 2007-04-08T21:08:59
u Universal time, local timezone 2007-04-08 21:08:59Z
Y Month / Year April 2007
dd Day 08
ddd Short Day Name Sun
dddd Full Day Name Sunday
hh 2 digit hour 09
HH 2 digit hour (24 hour) 21
mm 2 digit minute 08
MM Month 04
MMM Short Month name Apr
MMMM Month name April
ss seconds 59
tt AM/PM PM
yy 2 digit year 07
yyyy 4 digit year 2007
: seperator, e.g. {0:hh:mm:ss} 09:08:59
/ seperator, e.g. {0:dd/MM/yyyy} 08/04/2007

Tuesday, September 20, 2011

Change master page in page init event

File: Default.aspx

<%@ Page Language="C#" 
         MasterPageFile="~/Default.master" 
         AutoEventWireup="true" 
         CodeFile="DynamicContentPage.aspx.cs" 
         Inherits="DynamicContentPage_aspx" 
         Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">Sample content</asp:Content>


File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DynamicContentPage_aspx : System.Web.UI.Page
{
  protected void Page_PreInit(object sender, EventArgs e)
  {
    this.MasterPageFile = "TableMaster.master";

  } 
}



File: Default.master

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Default.master.cs" Inherits="SiteTemplate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
        <i>This is a simple footer.</i></div>
    </form>
</body>
</html>


File: Default.master.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SiteTemplate : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

}


File: TableMaster.master


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Default.master.cs" Inherits="TableMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <table width="100%">
    <tr>
        <td colspan="2" style="background: #ffccff">
            <h1>My Header</h1>
        </td>
    </tr>
    <tr>
        <td style="background: #ffffcc" >
            <asp:treeview ID="Treeview1" runat="server" Width="150px">
                <Nodes>
                    <asp:TreeNode Text="Root" Value="New Node">
                        <asp:TreeNode Text="Page 1" Value="Page 1"></asp:TreeNode>
                        <asp:TreeNode Text="Page 2" Value="Page 2"></asp:TreeNode>
                    </asp:TreeNode>
                </Nodes>
            </asp:treeview>
        </td>
        <td>
            <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
            </asp:contentplaceholder>
        </td>
    </tr>
    <tr>
        <td colspan="2" style="background: #ccff33">
            <i>My Footer</i>
        </td>
    </tr>
    </table>
    </form>
</body>
</html>


File: TableMaster.master.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class TableMaster : System.Web.UI.MasterPage
{


    public bool ShowNavigationControls
  {
    set { Treeview1.Visible = value; }
    get { return Treeview1.Visible; }
  }

}

Tuesday, September 6, 2011

access master page element in content page

I have a  <div> in Master page as below:

<div id="menu">
<a href="Records.aspx">Records</a>
</div>

I want to hide this div in Login.aspx, this can can be achieved using below code from
Login code behind page.


//Hide navigation div from Login page
       
 HtmlContainerControl navDiv = (HtmlContainerControl)this.Master.FindControl("menu");
 navDiv.Visible = false;



To access this <Div> from MasterPage, it should be set to <div id="menu" runat="server">.

How to pass multiple value in command argument

<radg:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Zip Code Count" DataField="ZipCount" >

   <ItemTemplate>

     <asp:LinkButton runat="server" ID="lnkZipCount" Text='<%#Eval("ZipCount") %>' CommandArgument='<%#Eval("CityID") + ";" +Eval("Sname")%>' OnClick="lnkZipCount_Click"></asp:LinkButton>

   </ItemTemplate>

 </radg:GridTemplateColumn>



protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Test")
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });

       Label1.Text= commandArgs[0];
       Label2.Text = commandArgs[1];

        }
    }












-------------------------------------------------------------------------------------
how to extract separate month 

string yyyy = dt.Year.ToString();

        int mon = dt.Month;
        string mont = null;
        String[] Months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
        for (int i = 0; i < Months.Length; i++)
        {
            if (i == mon - 1)
            {
                mont = Months[i].ToString();
                break;
            }
        }

        string str = mont;

***********************************************************************************



Complete Demo



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultipleCommandArgument.aspx.cs"
   Inherits="MultipleCommandArgument" %>

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
               <Columns>
                   <asp:BoundField DataField="carid" HeaderText="Card Id" />
                   <asp:BoundField DataField="Year" HeaderText="year" />
                   <asp:TemplateField>
                       <ItemTemplate>
                           <asp:Button ID="btnTest" runat="Server" CommandName="Test" Text="Select" CommandArgument='<%#Eval("carid") + ","+Eval("year") %>' />
                       </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
           <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
   </form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MultipleCommandArgument : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
      

    }
  
    DataTable data;
    DataTable GetData()
    {
        data = Session["data"] as DataTable;
        if (data != null)
        {
            return data;
        }
        data = new DataTable();
        DataColumn primaryColumn
        = new DataColumn("carid", typeof(Int32));
        data.Columns.Add(primaryColumn);
        data.Columns.Add(new DataColumn("year", typeof(Int32)));
        data.Columns.Add(new DataColumn("make", typeof(string)));
        data.Columns.Add(new DataColumn("model", typeof(string)));
        DataRow dr;
        dr = data.NewRow();
        dr[0] = 1;
        dr[1] = 1998;
        dr[2] = "Isuzu";
        dr[3] = "Trooper";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 2;
        dr[1] = 2000;
        dr[2] = "Honda";
        dr[3] = "Civic";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 3;
        dr[1] = 2000;
        dr[2] = "BMW";
        dr[3] = "GM";
        data.Rows.Add(dr);
        dr = data.NewRow();
        dr[0] = 4;
        dr[1] = 2000;
        dr[2] = "Swift";
        dr[3] = "Tata";
        data.Rows.Add(dr);
        DataColumn[] primaryColumns = new DataColumn[1];
        primaryColumns[0] = primaryColumn;
        data.PrimaryKey = primaryColumns;
        Session["data"] = data;
        return data;
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Test")
        {
            string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });

       Label1.Text= commandArgs[0];
       Label2.Text = commandArgs[1];

        }
    }
}