Showing posts with label asp.net. Show all posts
Showing posts with label asp.net. Show all posts

07 August 2017

ViewBag vs TempData vs Session




ViewData



  1. ViewData is a dictionary object that is derived from ViewDataDictionary class.

    1. public ViewDataDictionary ViewData { get; set; }



  2. ViewData is a property of ControllerBase class.

  3. ViewData is used to pass data from controller to corresponding view.

  4. It’s life lies only during the current request.

  5. If redirection occurs then it’s value becomes null.

  6. It’s required typecasting for getting data and check for null values to avoid error.


ViewBag



  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

  2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.

    1. public Object ViewBag { get; }



  3. ViewBag is a property of ControllerBase class.

  4. It’s life also lies only during the current request.

  5. If redirection occurs then it’s value becomes null.

  6. It doesn’t required typecasting for getting data.



TempData



  1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

    1. public TempDataDictionary TempData { get; set; }



  2. TempData is a property of ControllerBase class.

  3. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).

  4. It’s life is very short and lies only till the target view is fully loaded.

  5. It’s required typecasting for getting data and check for null values to avoid error.

  6. It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article: Persisting Data with TempData


Session



  1. In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.

    1. public HttpSessionStateBase Session { get; }



  2. Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).

  3. Session is valid for all requests, not for a single redirect.

  4. It’s also required typecasting for getting data and check for null values to avoid error.

14 May 2014

Cannot open database requested by the login. The login failed

This error occurs when you have configured your application with IIS, and IIS goes to SQL Server and tries to login with credentials that do not have proper permissions

1. Go to SQL Server > Security > Logins > right click on 'Your user error name' > Properties

In opened screen of Login Properties, go to the “User Mapping” tab.

2. Select map checkbox appropriate to your database, And change user dropdown to sa (if necessary)

3. Then change user membership to dbo.owner

Then click on OK

In almost all such cases, this should fix your problem.

 

 

21 December 2013

Difference between String and string

1. String stands for System.String and it is a .NET Framework type.
2. string is a type in C#. System.String is a type in the CLR.
3. string is an alias for System.String in the C# language. Both of them are compiled to System.String in IL (Intermediate Language),
4. So there is no difference. Choose what you like and use that.
5. For code in C#, its prefer to use string as it's a C# type alias and well-known by C# programmers.


6. string is a reserved word, but String is just a class name.This means that 'string' cannot be used as a variable name by itself.


StringBuilder String = new StringBuilder(); // compiles
StringBuilder string = new StringBuilder(); // doesn't compile


7. If you really want a variable name called 'string' you can use @ as a prefix :
StringBuilder @string = new StringBuilder(); this applies to string also.


8. So String is not a keyword and it can be used as Identifier whereas string is a keyword and cannot be used as Identifier. And in function point of view both are same.
9. You can't use String without using System; but string can use without that namespace.
10. Static functions such as String.Format, String.Join, String.Concat, String.isNullOrWhitespace etc... are from String.



I can say the same about (int, System.Int32) etc..

20 December 2013

default Timeouts in c#

SqlConnection.ConnectionTimeout - 15 sec

- Gets the time to wait while trying to establish a connection before terminating the attempt.

SqlCommand.CommandTimeout - 30 seconds

- Gets or sets the wait time before terminating the attempt to execute a command

Session Timeout - 20 mins

<system.web>
<SessionState timeout=”10”></SessionState>

Cookies per Domain - 20 - 1KB

 

String Vs StringBuilder

System.String
-------------
1. String is immutable. It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string
2. many actions that you do with string
3. Here concatenation is used to combine two strings by using String object
4. The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted
5. string is non updatable
6. everytime a object has to be created for Operations like append,Insert etc. at runtime

System.StringBuilder
--------------------
1. StringBuilder is mutable. It can be modified in any way and it doesn't require creation of new instance.
2. if you try to do some other manipulation (like removing a part from the string, replacing a part in the string, etc.), then it's better not to use StringBuilder at those places. This is because we are anyway creating newstrings.
3. system.stringbuilder is updateble
4. string builder is faster than the string object
5.String builder is more efficient in case large amount of string operations have to be perform.
6.Insertion is done on the existing string.
7. At the end, we can get the string by StringBuilder.ToString()
dis-adv:
1. We must be careful to guess the size of StringBuilder. If the size which we are going to get is more than what is assigned, it must increase the size. This will reduce its performance.
2. many actions can't be done with StringBinder.
3. When initializing a StringBuilder, you are going down in performance.
4. StringBuilder can be used where more than four or more string concatenations take place.

10 February 2013

9 February

i). Machine. Config

ii). Web.Config (For desktops app.Config)

Common paints for confn files:

  • These are simple text files & can be edited using any simple text editor.

  • These are xml formatted (case sensitive) & any xml programs can use these files or they can be directly edited because xml is human readable.

  • * They are automatically cached on memory for faster retrieval of settings (Cache memory àprogrammed memory area).

  • * Processed in hierarchical manner which means every configuration file inherits its parent configuration file settings. The root for all these files is Machine.Config.

  • Also called as configuration inheritance apart from this configuration is also hierarchical as xml is hierarchical.


Machine.Config points:

  • It is called per-server basis file. Only one machine.config is allowed for one runtime/server.

  • Located .NET framework folder not on our project & all settings are common to all websites running in that system. * 4 MB (default)(more than 4.0 go to machine.config – one file- change)

  • Most of the settings are maintained by administrator but not by application developers.

  • here we find all website settings(default) i.e., namespaces, services of support, net support, compileation settings, deploy settings, db settings ......


Web.Config points:

  • It is called as application Configuration file.

  • **** It is optional today also to have web.config in our application located in root & can be created sub folders also. We can create multiple web.config’s on our site maximum is how many folders we have in our project.

  • we can perform the following functionalities in web.config file:



  1.  Maintain connection strings

  2. Custom errors

  3. Security

  4. Debugging

  5. Tracing


----------------------------

The Cursor Process has the following steps involved in it: (exception handling in sp)

  • Declare a Cursor

  • Open a Cursor

  • Fetch data from the Cursor

  • Close the Cursor

  • De-allocate the Cursor


----------------------------

When a client, makes a request for an aspx page, it will be processed at server & all the result produced is concatenated as a single string along with some hash values in it.

These concatenated values are converted into base 64 format***. These base 64 values are stored in one or more hidden fields*** by server sent to client along with other from contents.

User adds/modifies the content & resubmits the form to server. Server first reads the hidden field values so that it retains the last given values (act as stateful) &responds the same process with new repeated as long as user is working with current page....

---------------------------

What is the scope of application variable?

  1. Accessible to all users of application, irrespective of the user who created it.

  2. The common memory area which is created in the webserver, which is common for all the users is k.led as App. Memory.

  3. Storing the data in this app.memory is k.ed App. state in State mngt. sys      

  4. .: The values stord by the webuser in the app memory, can be accessed by the other users also.                  

  5. The App State can store obj data types.

  6. App.State have to be used to store the Data which will be common for all the users of website.


---------------------------

All session variables are accessible to current user only.

Session variable are also of type object which means they can store any type of data (Load on server should be considered).

Session data will be stored @ server only & only session id travels. This data will be available as long as session is preserved by server. Sessions are normally ended based on timeout***.

In ASP.NET by default 20 min’s it the timeout (idle timeout) using configuration settings as well as programmatically with session object we can change this default time.

A session can be ended programmatically also. Session object has a method called Abandon () which kills the current session.

<system.web>

<SessionState timeout=”10”></SessionState>

-------------------------------

Untitled





Non.Persistent Cookies: These Cookies will be created in the browser's process area. They r not mentioned with Time duration. These Cookies will be destroyed when the app is closed

Persistent Cookies: The Cookies which are created & exists for a given time duration., is k.ld as the Persistent Cookie. They are created in the Client machine

Query string:                                                                                                                                                               Query string is Client side st.mngt sys. It can hold only strings. The Query string Memory will destroyed, when the app is closed.                                                                                                                                                The values Stored in Query string can be accessed from any page through out the app. In general Query string is used 2 carry small values from one to another page.

----------------------------

  1. Caching is the process of storing the page or objects in the cache memory of browse, proxy servers or webserver.      

  2. in general, caching is used to improve the performance i.e., the page or object that is cached will be accessed from the cache memory tor the next request with out fetching it from the db server.

  3. caching can be done at client side as well as server side.


These are 3 types of caching:

client side caching:

  • output page caching (or) entire page caching

  • fragment caching (or) partial page caching


server side caching:

  • data caching (or) object caching.


using system.web.caching;

//create{                                                                                                                                                                                                            CacheDependency cd = new Cache Dependency(Server.MapPath("XMLfile.xml"), Cache.Insert("key1",ds.Tables[0]),cd,DateTime.Now.AddMinutes(10),Cache.NoSlidingExpression);              }

//get{                                                                                                                                                                                         gv1.DataSource = (DataTable)Cache.Get("key1");                                                                                                                      gv1.DataBind();                                                                                                                                                                                             }

  1. Obj caching or data caching is server side State Management Sys.

  2. we can create this kind of caching in 2 cryterious



  • cache dependency: By using this, cache memory will be destroyed if the dependent file is modified.

  • cache expiration: By using this parameter, cache mem. will be destroyed with in a given time after the creation.


-----------------------------

Primary Key:
Primary Key enforces uniqueness of the column on which they are defined.
Primary Key creates a clustered index on the column.
Primary Key does not allow Nulls.

CREATE TABLE EMP (eID INT NOT NULL PRIMARY KEY,
eName VARCHAR(100) NOT NULL)

Alter table with Primary Key:
ALTER TABLE EMP
ADD CONSTRAINT pk_eID PRIMARY KEY (eID)

Unique Key:
Unique Key enforces uniqueness of the column on which they are defined.
Unique Key creates a non-clustered index on the column.
Unique Key allows only one NULL Value.

Alter table to add unique constraint to column:
ALTER TABLE EMP ADD CONSTRAINT UK_empName UNIQUE(empName)

25 January 2013

Create virtual files in asp

    private void virfile()
    {
        if (!Directory.Exists(Server.MapPath("download/")))
            Directory.CreateDirectory(Server.MapPath("download/"));
        string filpath = Server.MapPath("download/" + "data.txt");
        string filedir = filpath.Substring(0, filpath.LastIndexOf('.'));
        string fileext = System.IO.Path.GetExtension(filpath);
        if (!File.Exists(filpath))
        {
            File.AppendAllText(filpath, "file downloaded on : " + DateTime.Now.ToString() + "\r\n");
        }
        else
        {
            int i = 1;
            while (true)
            {
                filpath = filedir + "(" + i + ")" + fileext;
                if (!File.Exists(filpath))
                {
                    File.AppendAllText(filpath, "file downloaded on : " + DateTime.Now.ToString() + "\r\n");
                    break;
                }
                i++;
            }
        }
    }

20 January 2013

Image binary format c#

source:
    <div>

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        OnRowCommand="gv_command">

        <Columns>

            <asp:TemplateField HeaderText="files">

                <ItemTemplate>

                    <asp:LinkButton ID="l1" runat="server" Text='<%#Eval("filenam") %>' CommandArgument='<%#Eval("id") %>' CommandName="link"></asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>

            <asp:TemplateField HeaderText="image">

                <ItemTemplate>

                    <asp:ImageButton ID="i1" runat="server" ImageUrl='<%#"Handler.ashx?id=" + Eval("id")  %>' CommandName="image" CommandArgument='<%#Eval("id") %>'

                    Visible='<%#Convert.ToString(Eval("isimage")).Trim()=="yes"?true:false %>' Height="50px" Width="50px" />

                </ItemTemplate>

            </asp:TemplateField>

        </Columns>

        </asp:GridView>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="b1_click"/><br />

        <asp:Image ID="Image1" runat="server" Height="300px" Width="300px"/>

    </div>


aspx.cs:



using System.Data.SqlClient;

using System.Data;

using System.IO;



    SqlConnection con = new SqlConnection("Data Source=.;database=db;UID=sa;Pwd=sa123");

    SqlDataAdapter da = new SqlDataAdapter();

    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack) {

            GetData();

        }

    }

    private void GetData()

    {

        da = new SqlDataAdapter("select * from upld order by id", con);

        ds = new DataSet();

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

    protected void gv_command(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "link")

        {

            string path = "";

            byte[] a = getbyte(e.CommandArgument.ToString(), out path);

 

            if (!File.Exists(Server.MapPath(path)))

                //File.Delete(Server.MapPath(path));

                File.WriteAllBytes(Server.MapPath(path), a);

            System.Diagnostics.Process.Start(Server.MapPath(path));

        }

        else if (e.CommandName == "image")

        {

            string path = "";

            byte[] a = getbyte(e.CommandArgument.ToString(), out path);

            string fil = path.Substring(path.LastIndexOf('.') + 1).ToUpper();

            string[] files = new string[] { "GIF", "PNG", "JPG", "BMP", "ICO" };

            if (files.Contains(fil))

            {

                MemoryStream ms = new MemoryStream(a);

                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);

                if (!File.Exists(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString())))

                    //File.Delete(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString()));

                    bmp.Save(Server.MapPath("d/" + ds.Tables[0].Rows[0][1].ToString()), System.Drawing.Imaging.ImageFormat.Jpeg);

                Image1.ImageUrl = "d/" + ds.Tables[0].Rows[0][1].ToString();

            }

        }

    }

 

    byte[] getbyte(string s, out string p)

    {

        da = new SqlDataAdapter("select top 1 filebin,filenam from upld where id=" + s, con);

        ds = new DataSet();

        da.Fill(ds);

        string fil = ds.Tables[0].Rows[0][1].ToString().Substring(ds.Tables[0].Rows[0][1].ToString().LastIndexOf('.') + 1);

        p = "d/" + ds.Tables[0].Rows[0][1].ToString();

        return (byte[])ds.Tables[0].Rows[0][0];

    }

    protected void b1_click(object sender, EventArgs e) 

    {

        FileUpload1.PostedFile.SaveAs(Server.MapPath(FileUpload1.FileName));

        string sFileName = Server.MapPath(FileUpload1.FileName);

        byte[] fileData = File.ReadAllBytes(Server.MapPath(FileUpload1.FileName));

        SqlCommand cmd = new SqlCommand();

        cmd.Parameters.Add(new SqlParameter("@filenam", sFileName));

        cmd.Parameters.Add(new SqlParameter("@filebin", fileData));

 

        string fil = FileUpload1.PostedFile.ContentType.ToString();

        fil = fil.Substring(fil.LastIndexOf('/') + 1).ToUpper();

        string[] files = new string[] { "GIF", "PNG", "JPG", "BMP","ICO" };

        fil = files.Contains(fil) ? "yes" : "no";

 

        cmd.CommandText = "insert into upld(path,filebin,filenam,isimage) values(@filenam, @filebin,'" + FileUpload1.FileName + "','" + fil + "')";

        cmd.Connection = con;

        con.Open();

        cmd.ExecuteNonQuery();

        File.Delete(Server.MapPath(FileUpload1.FileName));

        GetData();

    }


ashx.cs:



using System.Data;

using System.Data.SqlClient;


public void ProcessRequest (HttpContext context)

{

    SqlConnection con = new SqlConnection("Data Source=.;database=db;UID=sa;Pwd=sa123");

        SqlDataAdapter da = new SqlDataAdapter();

        DataSet ds = new DataSet();

 

        da = new SqlDataAdapter("select top 1 filebin from upld where id=" + context.Request.QueryString["ID"].ToString(), con);

        ds = new DataSet();

        da.Fill(ds);

        context.Response.BinaryWrite((byte[])ds.Tables[0].Rows[0][0]);

}




db: with auto increment id


db


05 December 2012

Create a table named 'select' with column 'table'

SET QUOTED_IDENTIFIER ON
CREATE TABLE "SELECT" ("TABLE" int)

When SET QUOTED_IDENTIFIER is ON, all strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers. They can be reserved keywords and can include characters not usually allowed in Transact-SQL identifiers

Reference: http://msdn.microsoft.com/en-us/library/aa259228(v=sql.80).aspx

or

CREATE TABLE [SELECT] ([TABLE] INT)

06 October 2012

sort array of int values without using built-in functions (using Bubble sort)

string res = "";
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int k = 0; k < arr.Length; k++)
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
int hold = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = hold;
}
}
res += arr[k].ToString();
arr[k] = arr[k];
}

string s = "1,2,3,,3,2";
string[] ss = (s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
for (int k = 1; k < ss.Length; k++)
{
for (int i = 0; i < (ss.Length - 1); i++)
{
if (Convert.ToInt32(ss[i].Trim()) > Convert.ToInt32(ss[i + 1].Trim()))
{
string hold = ss[i];
ss[i] = ss[i + 1];
ss[i + 1] = hold;
}
}
}
s = string.Join(",", ss);

04 October 2012

split string in c# with regular expression instead of forloop

string s = "er32(s),re4'wr(a),f2.0(t)A(y),(a)";
        s = Regex.Replace(s, @"[\w\s';.&,:]+\(([\w\d.]+)\)", "$1");
        Response.Write(s);

11 September 2012

How to get the current row in the grid view rowcommand event

GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;

In RowDataBound for datakeys

GridView1.DataKeys[e.Row.RowIndex].Value.ToString()

((DataRowView)e.Row.DataItem)["mainid"].ToString()

20 August 2012

persistedselection property for a gridview control in asp

You can specify how row selection is persisted when the GridView control is in paging mode. By default, row selection is persisted by row index. For example, if the second row in a page is selected, the second row in all pages will be selected.

Alternatively, you can specify that row selection is persisted by data-row key. In that case, when a row is selected, rows in other pages are not selected. To enable this functionality, set the EnablePersistedSelection property to true as shown in the following example:

<asp:GridView id="GridView1" runat="server" PersistedSelection="true">
</asp:GridView>

16 July 2012

array conversions

using System;
using System.Collections.Generic;
---------------------------
arraylist to array
> string[] a = (string[])arraylist.toarray(typeof(string));
> arraylist.copyto(array,0);
list to array
> string[] a = list.toarray();
---------------------------
arraylist to arraylist
> arraylist.addrange(arraylist);
---------------------------
array to arraylist
> arraylist.addrange(array);
> arraylist a = new arraylist(array);
array to list
> list<string> l = new list<string>(array)
> list<string> l = array.tolist();
---------------------------
array to array
> string[]  a = (string[])array.clone();// Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array
---------------------------
array declaration and intilization methods
int[] a;
a = new int[3]{3,5,6};
int[] a = new int[]{3,4,5};
int[] a = new int[3]{3.4,5};
int[] a = new int[3];
a[0] = 2; a[1] = 3; a[2] = 4;
---------------------------
search arraylist
arraylist.sort();
arraylist.binaryseach(43);
arraylist.indexof(searchstr , 0);
---------------------------
string to bytearray
> byte[] = (new UnicodeEncoding()).GetBytes(stringToConvert);
---------------------------
bytearray to string
>char[] cs = new char[bs.Length];
for (int i = 0; i < cs.Length; ++i)
{
cs[i] = Convert.ToChar(bs[i]);
}
---------------------------

char array to string
string str = new string(chararray);

string to char array
string s = "hello";
char[] c = s.ToCharArray();
---------------------------

array to datatable

>DataTable dataTable = new DataTable();dataTable.LoadDataRow(array, true);//Pass array object to LoadDataRow methodreturn dataTable;
---------------------------
get array size
array.getlength(0).tostring();
array.getlowerbound(0).tostring();
---------------------------
better to use List instead of ArrayList
better to use Dictionary instead of HashTable

15 July 2012

General Page Life-Cycle Event Stages

The events occur in the following sequence.

Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :

PageRequest – The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled(therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start – In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

PreInit– This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
protected void Page_PreInit(object sender, EventArgs e)

Init – Each control in the control collection is initialized. i.e., During page Intialization, controls on the page are available and each control’s UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from viewstate.
protected void Page_Init(object sender, EventArgs e)

Init Complete* - Page is initialized and the process is completed.
protected void Page_InitComplete(object sender, EventArgs e)

PreLoad* - This event is called before the loading of the page is completed.
protected void Page_PreLoad(object sender, EventArgs e)

Load– This event is raised for the Page and then all child controls. The controls properties and view state and control state can be accessed at this stage. This event indicates that the controls have been fully loaded.
protected void Page_Load(object sender, EventArgs e)

LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
protected void Page_LoadComplete(object sender, EventArgs e)

PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
protected void Page_PreRender(object sender, EventArgs e)

Savestate

Rendering – Before rendering, viewstate is saved for the page and all controls. At this stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Response property.

PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
protected void Page_PreRenderComplete(object sender, EventArgs e)

SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.
protected void Page_SaveStateComplete(object sender, EventArgs e)

Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
protected void Page_Unload(object sender, EventArgs e)

 

The events marked with *  have been introduced in ASP.NET 2.0.

Untitled

page life cycle -- click to download the document

 

Comparison with Init and Load events in Master and content pages:











Page Init EventPage Load event
1. Execution sequence starts from Init event of Main master page--> Sub Master Page --> ……. -->Requested ASPX page init event.1. Execution sequence starts from Load event of Requested ASPX page --> Sub Master Page --> ……. --> Main master page load event.

 

28 June 2012

clear all cotrol values of a page

<script type="text/javascript">
    function allclear()
    {    //debugger
        var elements=document.getElementsByTagName("INPUT");
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="radio")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="checkbox")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
           if (elements[i].type=="text")
                elements[i].value="";
        var elements1=document.getElementsByTagName("SELECT");
        for(i=0;i<elements1.length;i++)
            if(elements1[i].id!="" && elements1[i].id!=null)
                elements1[i].selectedIndex=0;
     }
</script>
---------------------------------------------------------------------------------------
private void ClearControls(Control c)
    {
        if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
            ((TextBox)c).Text = "";
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButtonList))
        {
            RadioButtonList rbtl = (RadioButtonList)c;
            for (int j = 0; j < rbtl.Items.Count; j++)
                rbtl.Items[j].Selected = false;
        }
        if (c.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
            ((DropDownList)c).SelectedIndex = 0;
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButton))
            ((RadioButton)c).Checked = false;
        foreach (Control child in c.Controls)
            ClearControls(child);
}

------------------------------------------------------------------------------------------------------------------------

  private void DisableControls(Control c)
    {
        if ((c is TextBox) || (c is LinkButton) || (c is Button) || (c is CheckBox) || (c is CheckBoxList) || (c is RadioButtonList) || (c is DropDownList) || (c is Panel) || (c is ImageButton))
        {
            ((WebControl)c).Enabled = false;
        }
        foreach (Control child in c.Controls)
            DisableControls(child);
    }

make listbox items colorful

protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add("class", "optred");
            flag = false;
        }
        else
        {
            li.Attributes.Add("class", "optblue");
            flag = true;
        }
    }
}
<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;} 
</style>

String formats

String strVal = "a(1), a1(2), a.3(3), a'4 (4), a.5:(5)";
Regex.Replace(strVal, @"[\w\s';.&,:]+\((\d+)\)", "$1") = 1,2,3,4,5
-----------------------------------------------------------------------
string dNum = "32.123456";
string.Format("{0:c}", double.Parse(dNum)) = $32.12
string.Format("{0:n}", double.Parse(dNum)) = 32.12
string.Format("{0:D}", DateTime.Now) = Thursday, June 28, 2012
string.Format("{0:T}", DateTime.Now) = 10:59:28 AM
DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") = 28/06/2012 10:59:28
---------------------------------------------------------------------------------
decimal dNum = decimal.Parse("32.12345");
Response.Write(dNum.ToString("0.00"));

01 June 2012

image file path to byte[] format

private byte[] imgStream(string filePath)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{ Bitmap bmp = new Bitmap(filePath);
  bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { goto tryagain; }
return stream.ToArray();
}

System.Drawing.ColorTranslator.FromHtml("#D8BFD8");

25 May 2012

Email validation javascript

function emailCheck(str)
{
var at="@";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1)
    return false;
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
    return false;
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
    return false;
if (str.indexOf(at,(lat+1))!=-1)
    return false;
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
    return false;
if (str.indexOf(dot,(lat+2))==-1)
   return false;
if (str.indexOf(" ")!=-1)
   return false;
return true;
}