Saturday, 20 October 2012

Validation Expressions for regular Expressions in asp.net c#


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

Validation Expressions
These are so often hard to find so I am posting them here:



Metacharacter Match
\ the escape character - used to find an instance of a metacharacter like a period, brackets, etc.
. (period) match any character except newline
x match any instance of x
^x match any character except x
[x] match any instance of x in the bracketed range - [abxyz] will match any instance of a, b, x, y, or z
| (pipe) an OR operator - [x|y] will match an instance of x or y
() used to group sequences of characters or matches
{} used to define numeric quantifiers
{x} match must occur exactly x times
{x,} match must occur at least x times
{x,y} match must occur at least x times, but no more than y times
? preceding match is optional or one only, same as {0,1}
* find 0 or more of preceding match, same as {0,}
+ find 1 or more of preceding match, same as {1,}
^ match the beginning of the line
$ match the end of a line


POSIX Class Match
[:alnum:] alphabetic and numeric characters
[:alpha:] alphabetic characters
[:blank:] space and tab
[:cntrl:] control characters
[:digit:] digits
[:graph:] non-blank (not spaces and control characters)
[:lower:] lowercase alphabetic characters
[:print:] any printable characters
[:punct:] punctuation characters
[:space:] all whitespace characters (includes [:blank:], newline, carriage return)
[:upper:] uppercase alphabetic characters
[:xdigit:] digits allowed in a hexadecimal number (i.e. 0-9, a-f, A-F)



Character class Match
\d matches a digit, same as [0-9]
\D matches a non-digit, same as [^0-9]
\s matches a whitespace character (space, tab, newline, etc.)
\S matches a non-whitespace character
\w matches a word character
\W matches a non-word character
\b matches a word-boundary (NOTE: within a class, matches a backspace)
\B matches a non-wordboundary



\
The backslash escapes any character and can therefore be used to force characters to be matched as literals instead of being treated as characters with special meaning. For example, '\[' matches '[' and '\\' matches '\'.
.
A dot matches any character. For example, 'go.d' matches 'gold' and 'good'.
{ }
{n} ... Match exactly n times
{n,} ... Match at least n times
{n,m} ... Match at least n but not more than m times
[ ]
A string enclosed in square brackets matches any character in that string, but no others. For example, '[xyz]' matches only 'x', 'y', or 'z', a range of characters may be specified by two characters separated by '-'. Note that '[a-z]' matches alphabetic characters, while '[z-a]' never matches.
[-]
A hyphen within the brackets signifies a range of characters. For example, [b-o] matches any character from b through o.
|
A vertical bar matches either expression on either side of the vertical bar. For example, bar|car will match either bar or car.
*
An asterisk after a string matches any number of occurrences of that string, including zero characters. For example, bo* matches: bo, boo and booo but not b.
+
A plus sign after a string matches any number of occurrences of that string, except zero characters. For example, bo+ matches: boo, and booo, but not bo or be.
\d+
matches all numbers with one or more digits
\d*
matches all numbers with zero or more digits
\w+
matches all words with one or more characters containing a-z, A-Z and 0-9. \w+ will find title, border, width etc. Please note that \w matches only numbers and characters (a-z, A-Z, 0-9) lower than ordinal value 128.
[a-zA-Z\xA1-\xFF]+
matches all words with one or more characters containing a-z, A-Z and characters larger than ordinal value 161 (eg. ä or Ü). If you want to find words with numbers, then add 0-9 to the expression: [0-9a-zA-Z\xA1-\xFF]+


Typical examples

(bo*)
will find "bo", "boo", "bot", but not "b"
(bx+)
will find "bxxxxxxxx", "bxx", but not "bx" or "be"
(\d+)
will find all numbers
(\d+ visitors)
will find "3 visitors" or "243234 visitors" or "2763816 visitors"
(\d+ of \d+ messages)
will find "2 of 1200 messages" or "1 of 10 messages"
(\d+ of \d+ messages)
will filter everything from the last occurrence of "2 of 1200 messages" or "1 of 10 messages" to the end of the page
(MyText.{0,20})
will find "MyText" and the next 20 characters after "MyText"
(\d\d.\d\d.\d\d\d\d)
will find date-strings with format 99.99.9999 or 99-99-9999 (the dot in the regex matches any character)
(\d\d\.\d\d\.\d\d\d\d)
will find date-strings with format 99.99.9999
(([_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+))
will find all e-mail addresses

asp.net validations


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

*******************************
REQUIREDFIELD VALIDATOR:-->
******************************

<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtUsername"
Text="Required!"
Runat="Server" />

<b>Password</b>
<br />
<asp:TextBox
ID="txtPassword"
Maxlength="20"
TextMode="Password"
CssClass="formfield"
Runat="Server" />
-------------------------------------------------------------------------------

**************************
COMPARE VALIDATOR:-->
**************************

<asp:CompareValidator ID="CompareValidator1"
ControlToValidate = "txtPassword"
ControlToCompare = "txtPassword2"
Type = "String"
Operator="Equal"
Text="Passwords must match!"
Runat = "Server" />

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

**************************
RANGE VALIDATOR:-->
**************************


<asp:TextBox ID="txtQty"
MaxLength="15" runat="server" />
<asp:RangeValidator
id="ValQty"
Type="Integer"
Text="Qty should be enter between 100 and 1000"
ControlToValidate="txtQty"
MaximumValue="1000"
MinimumValue="100"
runat="server"/>

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


*********************************
RAGULAREXPRESSION VALIDATOR:-->
*********************************
For (E-Mail)

<asp:regularexpressionvalidator
id="RegularExpressionValidator1"
runat="server"
xmlns:asp="#unknown">
ControlToValidate="txtEmail"
ErrorMessage="Invalid Email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
all validation in asp.net

For (Phone)
     
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>      
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"ErrorMessage="Enter only Numbers"
ValidationExpression="[0-9]*">
</asp:RegularExpressionValidator>      


For (Mobile No)

^([9]{1})([02346789]{1})([0-9]{8})$

-----------------------------------------------------------------------------------
^\d+$ (---for Numbers Only---)

-----------------------------------------------------------------------------------
^[-+]?[0-9]*\.?[0-9]+$   (---for Putting number with or without decimal---)

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

alpha Numeric validation in javascript


// check the user id
 function IsalphaNumericValidate(e)
 {
       var key;  
        if (e.keyCode)
          key = e.keyCode;
        else if (e.which)
          key = e.which;
         
          if (/[^A-Za-z0-9.]/.test(String.fromCharCode(key)))
          {          //fails test
            alert("invalid");
                         document.getElementById("<%=txtUserName.ClientID %>").focus();
                           return false;
          }
                     
                        return true;
                       
                }


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

onkeypress="Javascript:return IsalphaNumericValidate(event)"

viewstate in asp.net c#






------------------------------------
ViewState["a"] = txt_password.Text;
----------------------------------


------------------------------------
password = ViewState["a"].ToString();
------------------------------------







urlMappings in webconfig in asp.net c#



----------------------------------------
IN WEB Config...........>
---------------------------------------------

<urlMappings enabled="true">

<add url="~/operatorlogin.aspx" mappedUrl="~/adminlogin.aspx?id=op"/>
<add url="~/adminlogin.aspx" mappedUrl="~/adminlogin.aspx"/>
<add url="~/superadmin.aspx" mappedUrl="~/adminlogin.aspx?id=sa"/>
<add url="~/accounts.aspx" mappedUrl="~/adminlogin.aspx?id=ac"/>
</urlMappings>

</system.web>

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

urlMappings in asp.net c#


<system.web>
<urlMappings enabled="true">
<add
url="~/Clubs/Computer Club.aspx"
mappedUrl="~/ShowPage.aspx?PageID=1" />
<add
url="~/Clubs/Eco Club.aspx"
mappedUrl="~/ShowPage.aspx?PageID=2" />
</urlMappings >
</system.web>

update data from dataset into database table from asp.net c#


  private void LoadData()

                    {

                             if(ds != null)

                                       ds.Clear();

                             adap = new SqlDataAdapter("select id,title, description from testtable", con);

                             ds = new DataSet();

                             adap.Fill(ds);

                             dataGrid1.DataSource = ds.Tables[0];

                    }

                    //This click will update one of the field in the database using adapter update() method on

                    dataset.

                    private void btnUpdate_Click(object sender, System.EventArgs e)

                    {

                             SqlCommandBuilder com = new SqlCommandBuilder(adap);

                             foreach(DataRow dr in ds.Tables[0].Rows)

                                       dr["title"] = txtTitle.Text;

                             adap.Update(ds);

                    }

          }

try catch in sql server or exception handling in sql server


BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

====
BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

apply Transaction in asp.net c#


<connectionStrings><add name="myConnectionString" connectionString="data source=.; initial catalog=myDB; user id=sa; password=sa"/></connectionStrings>

Next in the button click event:

string name = txtName.Text;
string email = txtEmail.Text;
SqlConnection myConnection = new SqlConnection(connectionString);
SqlTransaction myTransaction = null;
try{

   myConnection.Open();
        myTransaction = myConnection.BeginTransaction();
         SqlCommand myCommand = new SqlCommand();
       myCommand.CommandType = CommandType.StoredProcedure;
       myCommand.Connection = myConnection;
        myCommand.CommandText = "maillist_insert";
        myCommand.Transaction = myTransaction;
       SqlParameter myParameter1 = new SqlParameter("@uname", name);
        SqlParameter myParameter2 = new SqlParameter("@email", email);
        myCommand.Parameters.Add(myParameter1);  
     myCommand.Parameters.Add(myParameter2);
       int rowsAffected = myCommand.ExecuteNonQuery();
        myTransaction.Commit();
        lblMsg.Text = "Transaction Committed";
}
catch
(SqlException ex){

   myTransaction.Rollback();
         lblMsg.Text = "Transaction Rollbacked due to " + ex.Message;
 }
finally{    myConnection.Close();}

Transaction in asp.net c#


Anywhoo, I thought I would share some basic information about SQL Server Transactions for those who are new to ADO.NET.  The book does a good job of providing an overview of transactions and a basic template for how to execute local transactions in code.  Here is the basic template for an ADO.NET 2.0 Transaction:

using (SqlConnection connection =
            new SqlConnection(connectionString))
{
    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction = null;
   
    try
    {
        // BeginTransaction() Requires Open Connection
        connection.Open();
       
        transaction = connection.BeginTransaction();
       
        // Assign Transaction to Command
        command.Transaction = transaction;
       
        // Execute 1st Command
        command.CommandText = "Insert ...";
        command.ExecuteNonQuery();
       
        // Execute 2nd Command
        command.CommandText = "Update...";
        command.ExecuteNonQuery();
       
        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
    finally
    {
        connection.Close();
    }
}
A c# using statement wraps up the connection, because SqlConnection implements IDisposable.  The using statement makes sure that Dispose() gets called on the connection object so it can free up any unmanaged resources.

Before you can begin a transaction, you must first open the connection.  You begin your transaction and then assign any newly created command objects to that transaction and perform queries as necessary.  Commit the transaction.  If an error occurs, Rollback the transaction in a catch statement to void out any changes and then rethrow the error so that the application can deal with it accordingly.  The connection is properly closed in the finally statement, which gets called no matter what, and any unmanaged resources are disposed when the using statement calls Dispose() on the connection.  Pretty simple solution to a fairly advanced topic.

The above template could actually implement a second c# using statement around command, because SqlCommand also implements IDisposable.  I don't know that it is really necessary, however.  More theoretical than probably anything.  I just like to see using statements around anything that implements IDisposable:

using (SqlConnection connection =
            new SqlConnection(connectionString))
{
    using (SqlCommand command =
            connection.CreateCommand())
    {
        SqlTransaction transaction = null;
       
        try
        {
            // BeginTransaction() Requires Open Connection
            connection.Open();
           
            transaction = connection.BeginTransaction();
           
            // Assign Transaction to Command
            command.Transaction = transaction;
           
            // Execute 1st Command
            command.CommandText = "Insert ...";
            command.ExecuteNonQuery();
           
            // Execute 2nd Command
            command.CommandText = "Update...";
            command.ExecuteNonQuery();
           
            transaction.Commit();
        }
        catch
        {
            transaction.Rollback();
            throw;
        }
        finally
        {
            connection.Close();
        }
    }
}

Transaction Scope in asp.net c#


add ddl from dialog box on right click on bin ->add refrences

using System.Transactions;


  TransactionOptions options = new TransactionOptions();
        options.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead ;
        options.Timeout = new TimeSpan(0, 5, 0);
        using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required, options))
        {
            DoWork();
            transactionScope.Complete(); //Tell the transaction to commit
        }

ToString Date Formates in asp.net c#


Format Style Output
MM-dd-yyyy : 02-07-2011
MMM dd, yyyy : Feb 07, 2011
ddd MM, yyyy : Mon 02, 2011
dddd MM, yyyy : Monday 02, 2011
MMM ddd dd, yyyy : Feb Mon 07, 2011
MMMM ddd dd, yyyy : February Mon 07, 2011
MMMM dddd dd, yyyy : February Monday 07, 2011


http://programming.top54u.com/Samples/ASP-Net-cs/DateTime-Functions/Date-Formats-Using-ToString-Function/Default.aspx

set icon on title in html

<LINK REL="SHORTCUT ICON" HREF="images/titallogo.gif">

scroll title bar in javascript




<SCRIPT language=javascript>
msg = "Welcome To Safe Life Pvt. Ltd";

msg = "..." + msg;pos = 0;
function scrollMSG() {
document.title = msg.substring(pos, msg.length) + msg.substring(0, pos);
pos++;
if (pos >  msg.length) pos = 0
window.setTimeout("scrollMSG()",200);
}
scrollMSG();
    </SCRIPT>


dynamic title of website in asp.net c#


set title from coding dynamically

By this we can give Title in once time ..........


Webconfig--->
--------------------------------------------------------------------------------
<appSettings>
<add key="CrystalImageCleaner-AutoStart" value="true"/>
<add key="CrystalImageCleaner-Sleep" value="60000"/>
<add key="CrystalImageCleaner-Age" value="120000"/>
    <add key ="mysite" value="cpsingh"/>
</appSettings>
........................................................................

---------------------------------------------
(On Particular Master Page)


using System.Web.Configuration;

 protected void Page_Load(object sender, EventArgs e)
    {
        Page.Header.Title = ConfigurationManager.AppSettings["mysite"].ToString();
    }
----------------------------------------------

stop enter key while input in asp.net c#

stop enter key on textbox

 <asp:TextBox ID="txtComments" Height="150" Columns="200" TextMode="multiline"  MaxLength="4000" runat="server" onkeydown =  "return (event.keyCode!=13);" />

read write text files in asp.net c#


// write data from database to text file
       public  void WriteToFile(string filename, string type)
       {

           StreamWriter SW;
           if (type.Equals("create"))
               SW = File.CreateText(filename);
           else
               SW = File.AppendText(filename);


           dtr =  GetData();

           while (dtr.Read()) // getting rows of datareader
           {
               int i = 0;
               string str = "";
               while (i < dtr.FieldCount) // getting columns of a single row
               {
                   str += dtr[i].ToString() + ",";
                   i++;
               }
               SW.WriteLine(str);

           }
           dtr.Close();
           SW.Close();

       }





 //private  void ReadFromFile(string filename)
    //{
    //    StreamReader SR;
    //    string S;
    //    SR = File.OpenText(filename);
    //    S = SR.ReadLine();
    //    while (S != null)
    //    {
    //      //  response.write( S );
    //        S = SR.ReadLine();
    //    }
    //    SR.Close();
    //}





// loop

           //while (dtr.Read()) // getting rows of datareader
           //{
           //    int i = 0;
           //    string str = "";
           //    //while (i < dtr.FieldCount) // getting columns of a single row
           //    //{
           //    //    str += dtr[i].ToString() + ",";
           //    //    i++;
           //    //}

           //    str = dtr[0].ToString();
           //    SW.WriteLine(str);

           //}

create new table with all the data of existing table in sql server

take backup of a table

select * into tbl_new from tbl_old

sum of values in datatable

        string y = ds.Tables[0].Compute("Sum(RemainingFund)", "RemainingFund is not null").ToString();

random number in sql server

 SELECT LEFT(SUBSTRING (RTRIM(RAND()) + SUBSTRING(RTRIM(RAND()),3,11), 3,11),5)

trigger in ajax updatepanel in asp.net c#


<asp:UpdatePanel ID="mncontainer" runat="server">
<contenttemplate>
</>
<Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnsave" EventName="Click" />
            <asp:PostBackTrigger ControlID="btncustimg" />
            <asp:AsyncPostBackTrigger ControlID="mnplanlist"
                EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="planlist"
                EventName="SelectedIndexChanged" />
        </Triggers>

</>

destroy session in asp.net c#


 
===========================================
Session["MId"] = null;
=========================================
Session.abadon();

server side time and client side time


Server Side Time:

Write this code:
private void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToLongTimeString());
}


Client Side Time

<script type="text/javascript">
function abc()
{
var a=new Date();
document.write(a.getHours()+":"+a.getMinutes()+":"+a.getSeconds());
}
abc();

</script>

send sms in asp.net c#


 public void sendsms()
    {
        string smsMessage = "with love" + "\r";
        smsMessage += "From" + "Sweeti" + "\r";
        smsMessage += "Subject:" + "Friendship" + "\r";
        smsMessage += "Message:" + "hi abhi , i love u ";

        string MobileNo = "9251950123";
        //HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        WebClient client = new WebClient();

   
        string baseurl = "http://sms.companyname.in/pushsms.php?username=Pinkcity Gold&password=264966&sender=Websms&to=" + MobileNo + "&message=" + smsMessage + "";
     


        Stream data = client.OpenRead(baseurl);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        data.Close();
        reader.Close();
    }

select row as column in sql server


DECLARE @strValues varchar(8000)
 SELECT @strValues = COALESCE(@strValues+',', '') + MainID
FROM
(
    SELECT   MainID
    FROM EndUser
) X
ORDER BY MainID


select @strValues

select all columns name from a table


SELECT     COLUMN_NAME AS Expr1
FROM         INFORMATION_SCHEMA.COLUMNS
WHERE     (TABLE_NAME = 'EndUserAddress')

get second maximum value in sql query




Find Out Second Maximum


SELECT     MIN(CapitalAccountID) AS ID
FROM         bal_CapitalAccount
WHERE     (CapitalAccountID IN
                          (SELECT     TOP (3) CapitalAccountID
                            FROM          bal_CapitalAccount AS bal_CapitalAccount_1
                            ORDER BY CapitalAccountID DESC))

stop right click in javascript


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

<script type="text/javascript" language="JavaScript">
document.onmousedown=click
var times=0
var times2=10
function click() {
if ((event.button==2) || (event.button==3)) {
if (times>=1) { bye() }
alert("Right Click Is not Allowed ...!!!");
times++ } }
 function bye() {
alert("Right Click Is not Allowed ...!!!");
 }
    </script>
    <script type="text/javascript" language="javascript">

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

..........................................................................................
<SCRIPT LANGUAGE="JavaScript">
function right(e) {
var msg = "Sorry, you don't have permission to right-click.";
if (navigator.appName == 'Netscape' && e.which == 3) {
alert(msg);
return false;
}
if (navigator.appName == 'Microsoft Internet Explorer' && event.button==2) {
alert(msg);
return false;
}
else return true;
}

function trap()
  {
  if(document.images)
    {
    for(i=0;i<document.images.length;i++)
      {
      document.images[i].onmousedown = right;
      document.images[i].onmouseup = right;
      }
    }
  }
</SCRIPT>
</HEAD>


<BODY onLoad="trap()">
..........................................................................................

change row color in repeater in asp.net c#


<asp:repeater id="rpOrderSummary" runat="server" onItemDataBound="FormatRepeaterRow">
<ItemTemplate>
<tr id="tRow" runat="server">
<TD width="10%" align="center" class="data" runat="server" ID="Td1">
<A id="A2" runat="server">
<asp:Label ID="lblCustomerID" Runat="server" text='<%#(DataBinder.Eval(Container, "DataItem.CustomerID"))%>'>
</asp:Label></A> </TD>
<TD width="10%" align="center" class="data" runat="server" ID="Td2">
<asp:Label ID="lblCustomerName" Runat="server" text='<%#(DataBinder.Eval(Container, "DataItem.CustomerName"))%>'>
</asp:Label>
</TD>
<TD width="10%" align="center" class="data" runat="server" id="Td3"><A id="A1" runat="server">
<asp:label id="lblCompanyName" runat="server" text='<%#(DataBinder.Eval(Container, "DataItem.CompanyName"))%>'>
</asp:label></A>
</TD>
</tr>
</ItemTemplate>
''''''''''''''''''
Now i will start my code behind to .ascx.cs file. the code will follow.
'''''''''''''''
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection cn  = new SqlConnection("server=localhost;database=Test;uid=test;pwd=test;");
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM V_CustomersDetails", cn);
SqlDataReader dr = cmd.ExecuteReader();
rpOrderSummary.DataSource = dr;
rpOrderSummary.DataBind();
}

protected void FormatRepeaterRow(Object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblCompanyName = new Label();
HtmlTableRow tr = new HtmlTableRow();
tr = e.Item.FindControl("tRow");
if(lblCompanyName.Text == "")
{
tr.BgColor = "red";
}
else
{
tr.BgColor = "Green";
}
}
}

Friday, 19 October 2012

Reguler Expression for Mobile No

^([9]{1})([02346789]{1})([0-9]{8})$

refresh page in html


<head>
    <title>Untitled Page</title>
    <meta http-equiv="refresh" content="10">
</head>

generate random number in asp.net c#


  Random rand = new Random((int)DateTime.Now.Ticks);
        for (i = 0; i < 100000; i++)
        {
            int numIterations = 0;
            numIterations = rand.Next(1, 1000);
            //Response.Write(numIterations.ToString());
            con.insert_data("insert into Random values('" + numIterations + "')");

        }

query for last date of month in sqlserver


----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth

improve query execution in sql server


There are many times that you want to delete a large batch of records, or do a bulk update of some type.

Many times when you do this you will cause locking / blocking of other users - This can be a VERY bad thing for a production database.

You can avoid this generally using this type of query:

SET ROWCOUNT 500
process_more:
DELETE FROM TableName WHERE Condition = 1
IF @@ROWCOUNT > 0 GOTO process_more
SET ROWCOUNT 0

You can use DELETE or UPDATE with this method, by doing this sql will continue looping until the rows affected = 0, processing 500 at a time (or whatever you set the rowcount to be).


query string in asp.net c#



**************URL Sending & QreryString Accepting Process******

******************* ( At Same Session)****************************

----------------------------------
On cs Page:---->
----------------------------------
Response.Redirect("Registration.aspx?loginid=" + userid + "&leg=" + leg + "", false);

Response.Redirect("Registration.aspx?UserId=" + userid , false);

----------------------------------
On Master Page:---->
----------------------------------
<li><a href="../Admin/Tree.aspx?ID=PWS1000001">Geneology</a></li>


----------------------------------
On cs File:---->
-----------------------------------


string str = Request.QueryString["ID"].ToString();


----------------------------------
On pre cs File:---->
-----------------------------------

Response.Redirect("~/Admin/DownLineReport.aspx?id=" + id + "&plan=" + plan);

----------------------------------
On post cs File:---->
-----------------------------------

 uid = Request.QueryString["id"];
 plan=Request.QueryString["plan"];


.................................................................................................

---------------------
 On .aspx    =========>
--------------------
<h3><a class="pod" href ="AccountLogin.aspx?typ=ft"><span class="style2">Customer Login</span></h3>
                     

---------------------
 On .cs   =========>
--------------------

  string type = Request.QueryString["typ"].ToString();

....................................................................................................

progressbar in javascript


<style>
<!--
.hide { position:absolute; visibility:hidden; }
.show { position:absolute; visibility:visible; }
-->
</style>

<SCRIPT LANGUAGE="JavaScript">

//Progress Bar script- by Todd King (tking@igpp.ucla.edu)
//Modified by JavaScript Kit for NS6, ability to specify duration
//Visit JavaScript Kit (http://javascriptkit.com) for script

var duration=3 // Specify duration of progress bar in seconds
var _progressWidth = 50; // Display width of progress bar.

var _progressBar = "|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
var _progressEnd = 5;
var _progressAt = 0;


// Create and display the progress dialog.
// end: The number of steps to completion
function ProgressCreate(end) {
// Initialize state variables
_progressEnd = end;
_progressAt = 0;

// Move layer to center of window to show
if (document.all) { // Internet Explorer
progress.className = 'show';
progress.style.left = (document.body.clientWidth/2) - (progress.offsetWidth/2);
progress.style.top = document.body.scrollTop+(document.body.clientHeight/2) - (progress.offsetHeight/2);
} else if (document.layers) { // Netscape
document.progress.visibility = true;
document.progress.left = (window.innerWidth/2) - 100+"px";
document.progress.top = pageYOffset+(window.innerHeight/2) - 40+"px";
} else if (document.getElementById) { // Netscape 6+
document.getElementById("progress").className = 'show';
document.getElementById("progress").style.left = (window.innerWidth/2)- 100+"px";
document.getElementById("progress").style.top = pageYOffset+(window.innerHeight/2) - 40+"px";
}

ProgressUpdate(); // Initialize bar
}

// Hide the progress layer
function ProgressDestroy() {
// Move off screen to hide
if (document.all) { // Internet Explorer
progress.className = 'hide';
} else if (document.layers) { // Netscape
document.progress.visibility = false;
} else if (document.getElementById) { // Netscape 6+
document.getElementById("progress").className = 'hide';
}
}

// Increment the progress dialog one step
function ProgressStepIt() {
_progressAt++;
if(_progressAt > _progressEnd) _progressAt = _progressAt % _progressEnd;
ProgressUpdate();
}

// Update the progress dialog with the current state
function ProgressUpdate() {
var n = (_progressWidth / _progressEnd) * _progressAt;
if (document.all) { // Internet Explorer
var bar = dialog.bar;
  } else if (document.layers) { // Netscape
var bar = document.layers["progress"].document.forms["dialog"].bar;
n = n * 0.55; // characters are larger
} else if (document.getElementById){
                var bar=document.getElementById("bar")
        }
var temp = _progressBar.substring(0, n);
bar.value = temp;
}

// Demonstrate a use of the progress dialog.
function Demo() {
ProgressCreate(10);
window.setTimeout("Click()", 100);
}

function Click() {
if(_progressAt >= _progressEnd) {
ProgressDestroy();
return;
}
ProgressStepIt();
window.setTimeout("Click()", (duration-1)*1000/10);
}

function CallJS(jsStr) { //v2.0
  return eval(jsStr)
}

</script>

<SCRIPT LANGUAGE="JavaScript">

// Create layer for progress dialog
document.write("<span id=\"progress\" class=\"hide\">");
document.write("<FORM name=dialog id=dialog>");
document.write("<TABLE border=2  bgcolor=\"#FFFFCC\">");
document.write("<TR><TD ALIGN=\"center\">");
document.write("Progress<BR>");
document.write("<input type=text name=\"bar\" id=\"bar\" size=\"" + _progressWidth/2 + "\"");
if(document.all||document.getElementById) // Microsoft, NS6
document.write(" bar.style=\"color:navy;\">");
else // Netscape
document.write(">");
document.write("</TD></TR>");
document.write("</TABLE>");
document.write("</FORM>");
document.write("</span>");
ProgressDestroy(); // Hides

</script>


<form name="form1" method="post">
<center>
<input type="button" name="Demo" value="Display progress" onClick="CallJS('Demo()')">
</center>
</form>

<a href="javascript:CallJS('Demo()')">Text link example</a>

<p align="center">This free script provided by<br />
<a href="http://www.javascriptkit.com">JavaScript
Kit</a></p>

print selected area in javascript


<style type="text/css" media="screen">
.hideonprint {display: block;}
</style>
<style type="text/css" media="print">
.hideonprint {display: none;}
</style>


......................


<div class=".hideonprint">
you can see me now, but you won't see me when printing!
</div>




next --->

onClick="javascript:window.document .tablename.print();"

print page in javascript




-------------------------------------------------
<script language="javascript" type="text/javascript">
   
    function Button1_onclick()
  {
    window.print();
  }
   
    </script>
--------------------------------------------------------

-----------------------------------------------------------------
<input id="Button1" onclick="return Button1_onclick()" style="width: 113px" type="button" value="Print" />
------------------------------------------------------------

upload photo and compress by asp.net c#



compress photo by file upload control in asp.net c#

---------------------------------------------------------------
 
if (FileUpload1.HasFile)
     {
         System.IO.FileInfo info = new System.IO.FileInfo(FileUpload1.PostedFile.FileName.ToString());
         if (info.Extension.ToLower() == ".jpg" || info.Extension.ToLower() == ".jpeg" || info.Extension.ToLower() == ".gif" || info.Extension.ToLower() == ".png" || info.Extension.ToLower() == ".bmp")
         {
             if (Image1.ImageUrl.ToString() != "~/UserPhoto/blankperson.JPG")
             {
                 FileInfo file = new FileInfo(Request.PhysicalApplicationPath + Image1.ImageUrl.ToString().Substring(2));
                 file.Delete();
             }
             string pth = "~/UserPhoto/" + txtUser.Text.Trim() + info.Extension.ToLower();
             logic.Photo_Update(pth, txtUser.Text.Trim());
             upload_photo(txtUser.Text + info.Extension.ToLower());
                       
         }
       
     }
       
        RMG.Functions.MsgBox("Updated Successfully");





private void upload_photo(string str)
    {

        byte[] imgNew;
        HttpPostedFile myfile = FileUpload1.PostedFile;
        // imgNew = imageResize.ResizeFromStream(120, FileUpload1.PostedFile.InputStream, FileUpload1.PostedFile.FileName);
        imgNew = imageResize.ResizeFromStream(120, myfile.InputStream, myfile.FileName);
        // Response.BinaryWrite(imgNew);
        byte[] imgNewSave;

        imgNewSave = imageResize.SaveFromStream(120, myfile.InputStream, str, "UserPhoto");
    }

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

print panel in javascript , print contoll in asp.net c#




-------------------------------------------------
<script language="javascript" type="text/javascript">
   
    function Button1_onclick()
  {
    window.print();
  }
   
    </script>
--------------------------------------------------------

-----------------------------------------------------------------
<input id="Button1" onclick="return Button1_onclick()" style="width: 113px" type="button" value="Print" />
------------------------------------------------------------



-----------------------------------------------------
<html>
<script type="text/javascript">
function printMe()
{
var content=document.getElementById('yourPanelClientID');

//open blank page and put the rendered HTML text inside
w=window.open('about:blank');
w.document.open();
w.document.write("<html>" + content.innerHTML);
w.document.writeln("<script>window.print()</"+"script>");
w.document.writeln("</html>");
w.document.close();
}
</script>

</html>

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

open popup from c# in asp.net


open popup from c# coding

These are the list of options we can use to open the new window using Process class.

//-- used to open a blank web browser window
string targetSite = "about:blank";

 //-- Open an url in a new web browser window
string targetSite = "http://www.yahoo.com";

//-- Open the ftp site in a new window
string targetSite = "ftp://ftp.mysite.com";

//-- Open the test.html  file in a new web browser window
 string targetSite = "D:\\test.html";

By using the following line of code we can open the required window programmatically from ASP.NET application .

System.Diagnostics.Process.Start(targetSite);

convert numeric to words in asp.net c#


using System;

namespace custom.util
{

    public class NumberToEnglish
    {

        //public String changeNumericToWords(double numb)
        //{

        //    String num = numb.ToString();

        //    return changeToWords(num, false);

        //}

        public String changeCurrencyToWords(String numb)
        {

            return changeToWords(numb, true);

        }

        public String changeNumericToWords(String numb)
        {

            return changeToWords(numb, false);

        }

        public String changeCurrencyToWords(double numb)
        {

            return changeToWords(numb.ToString(), true);

        }

        private String changeToWords(String numb, bool isCurrency)
        {

            String val = "", wholeNo = numb, points = "", andStr = "", pointStr = "";

            String endStr = (isCurrency) ? ("Only") : ("");

            try
            {

                int decimalPlace = numb.IndexOf(".");

                if (decimalPlace > 0)
                {

                    wholeNo = numb.Substring(0, decimalPlace);

                    points = numb.Substring(decimalPlace + 1);

                    if (Convert.ToInt32(points) > 0)
                    {

                        andStr = (isCurrency) ? ("and") : ("point");// just to separate whole numbers from points/cents

                        endStr = (isCurrency) ? ("Cents " + endStr) : ("");

                        pointStr = translateCents(points);

                    }

                }

                val = String.Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr);

            }

            catch { ;}

            return val;

        }

        private String translateWholeNumber(String number)
        {

            string word = "";

            try
            {

                bool beginsZero = false;//tests for 0XX

                bool isDone = false;//test if already translated

                double dblAmt = (Convert.ToDouble(number));

                //if ((dblAmt > 0) && number.StartsWith("0"))

                if (dblAmt > 0)
                {//test for zero or digit zero in a nuemric

                    beginsZero = number.StartsWith("0");

                    int numDigits = number.Length;

                    int pos = 0;//store digit grouping

                    String place = "";//digit grouping name:hundres,thousand,etc...

                    switch (numDigits)
                    {

                        case 1://ones' range

                            word = ones(number);

                            isDone = true;

                            break;

                        case 2://tens' range

                            word = tens(number);

                            isDone = true;

                            break;

                        case 3://hundreds' range

                            pos = (numDigits % 3) + 1;

                            place = " Hundred ";

                            break;

                        case 4://thousands' range

                        case 5:

                        case 6:

                            pos = (numDigits % 4) + 1;

                            place = " Thousand ";

                            break;

                        case 7://millions' range

                        case 8:

                        case 9:

                            pos = (numDigits % 7) + 1;

                            place = " Million ";

                            break;

                        case 10://Billions's range

                            pos = (numDigits % 10) + 1;

                            place = " Billion ";

                            break;

                        //add extra case options for anything above Billion...

                        default:

                            isDone = true;

                            break;

                    }

                    if (!isDone)
                    {//if transalation is not done, continue...(Recursion comes in now!!)

                        word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos));

                        //check for trailing zeros

                        if (beginsZero) word = " and " + word.Trim();

                    }

                    //ignore digit grouping names

                    if (word.Trim().Equals(place.Trim())) word = "";

                }

            }

            catch { ;}

            return word.Trim();

        }

        private String tens(String digit)
        {

            int digt = Convert.ToInt32(digit);

            String name = null;

            switch (digt)
            {

                case 10:

                    name = "Ten";

                    break;

                case 11:

                    name = "Eleven";

                    break;

                case 12:

                    name = "Twelve";

                    break;

                case 13:

                    name = "Thirteen";

                    break;

                case 14:

                    name = "Fourteen";

                    break;

                case 15:

                    name = "Fifteen";

                    break;

                case 16:

                    name = "Sixteen";

                    break;

                case 17:

                    name = "Seventeen";

                    break;

                case 18:

                    name = "Eighteen";

                    break;

                case 19:

                    name = "Nineteen";

                    break;

                case 20:

                    name = "Twenty";

                    break;

                case 30:

                    name = "Thirty";

                    break;

                case 40:

                    name = "Fourty";

                    break;

                case 50:

                    name = "Fifty";

                    break;

                case 60:

                    name = "Sixty";

                    break;

                case 70:

                    name = "Seventy";

                    break;

                case 80:

                    name = "Eighty";

                    break;

                case 90:

                    name = "Ninety";

                    break;

                default:

                    if (digt > 0)
                    {

                        name = tens(digit.Substring(0, 1) + "0") + " " + ones(digit.Substring(1));

                    }

                    break;

            }

            return name;

        }

        private String ones(String digit)
        {

            int digt = Convert.ToInt32(digit);

            String name = "";

            switch (digt)
            {

                case 1:

                    name = "One";

                    break;

                case 2:

                    name = "Two";

                    break;

                case 3:

                    name = "Three";

                    break;

                case 4:

                    name = "Four";

                    break;

                case 5:

                    name = "Five";

                    break;

                case 6:

                    name = "Six";

                    break;

                case 7:

                    name = "Seven";

                    break;

                case 8:

                    name = "Eight";

                    break;

                case 9:

                    name = "Nine";

                    break;

            }

            return name;

        }

        private String translateCents(String cents)
        {

            String cts = "", digit = "", engOne = "";

            for (int i = 0; i < cents.Length; i++)
            {

                digit = cents[i].ToString();

                if (digit.Equals("0"))
                {

                    engOne = "Zero";

                }

                else
                {

                    engOne = ones(digit);

                }

                cts += " " + engOne;

            }

            return cts;

        }

    }

}


showModalDialog in javascript


var value=window.showModalDialog("frmTrgDDOView.aspx","Null","dialogWidth:500px; dialogHeight:400px; scroll:no; center:yes");

         document.getElementById('<%=txtddocode.ClientID %>').value=value[0];
         document.getElementById('<%=txtddodesc.ClientID %>').value =value[1];


return value from popup window
----------------------------------
window.returnValue=array;

dynamic meta tag in asp.net c#

add meta tag from coading in asp.net c#


Step 1: Create a object of the HtmlMeta class
          
       HtmlMeta metaObject = new HtmlMeta();

Step 2: Add the attributes to the meta object
        metaObject .Attributes.Add("name", "keywords");
        metaObject .Attributes.Add("content", "keyword text here");

Step 3: Add the meta control to the header part of the page
       Header.Controls.Add(metaObject);

meta tag in html

Keywords for Search Engines
Some search engines on the WWW will use the name and content attributes of the meta tag to index your pages.
This meta element defines a description of your page:
<meta name="description" content="Free Web tutorials on HTML, CSS, XML, and XHTML" /> 
This meta element defines keywords for your page:
<meta name="keywords" content="HTML, DHTML, CSS, XML, XHTML, JavaScript" /> 
The intention of the name and content attributes is to describe the content of a page.
However, since too many webmasters have used meta tags for spamming, like repeating keywords to give pages a higher ranking, some search engines have stopped using them entirely.

messagebox in asp.net c#

   private void ShowMessageBox(string msg)
    {
        //  Get a ClientScriptManager reference from the Page class.
        msg = msg.Replace("'", " ");
        msg = msg.Replace("\r", "");
        msg = msg.Replace("\n", "");
        ClientScriptManager cs = Page.ClientScript;
        // Check to see if the startup script is already registered.
        if (!cs.IsStartupScriptRegistered(this.GetType(), "PopupScript"))
        {
            cs.RegisterStartupScript(this.GetType(), "PopupScript", "alert('" + msg + "');", true);
        }
    }

continuous marquee in html


================================================================================
Marquee Without Spacing--------->
=================================================================================

<script type="text/javascript" src="../js/lightbox.js"></script>
<style type="text/css">
    #outerCircleText {
    font-style: italic;
    font-weight: bold;
    font-family: 'comic sans ms', verdana, arial;
    color: #FFFFFF;

    position: absolute;top: 0;left: 0;z-index: 3000;cursor: default;}
    #outerCircleText div {position: relative;}
    #outerCircleText div div {position: absolute;top: 0;left: 0;text-align: center;}
</style>

<script type="text/javascript">
<!--
// Jeff
// www.huntingground.freeserve.co.uk
// ********** User Defining Area **********
data=[
["images/1.gif","Alt / Title text for image 1","1.gif"],
["images/2.gif","Alt / Title text for image 2","2.gif"],
["images/3.gif","Alt / Title text for image 3","3.gif"],
["images/4.gif","Alt / Title text for image 4","4.gif"],
["images/5.gif","Alt / Title text for image 5","5.gif"],
["images/6.gif","Alt / Title text for image 6","6.gif"],
["images/7.gif","Alt / Title text for image 7","7.gif"],
["images/8.gif","Alt / Title text for image 8","8.gif"],
["images/9.gif","Alt / Title text for image 9","9.gif"],
["images/10.gif","Alt / Title text for image 10","10.gif"],
["images/11.gif","Alt / Title text for image 11","11.gif"],
["images/12.gif","Alt / Title text for image 12","12.gif"],
["images/13.gif","Alt / Title text for image 13","13.gif"],
["images/14.gif","Alt / Title text for image 14","14.gif"],
["images/15.gif","Alt / Title text for image 15","15.gif"],
["images/16.gif","Alt / Title text for image 16","16.gif"],
["images/17.gif","Alt / Title text for image 17","17.gif"],
["images/18.gif","Alt / Title text for image 18","18.gif"],
["images/19.gif","Alt / Title text for image 19","19.gif"],
["images/20.gif","Alt / Title text for image 20","20.gif"],
["images/21.gif","Alt / Title text for image 21","21.gif"],
["images/22.gif","Alt / Title text for image 22","22.gif"],
["images/23.gif","Alt / Title text for image 23","23.gif"],
["images/24.gif","Alt / Title text for image 24","24.gif"],
["images/25.gif","Alt / Title text for image 25","25.gif"],
["images/26.gif","Alt / Title text for image 26","26.gif"],
["images/27.gif","Alt / Title text for image 27","27.gif"],
["images/28.gif","Alt / Title text for image 28","28.gif"],
["images/29.gif","Alt / Title text for image 29","29.gif"],
["images/30.gif","Alt / Title text for image 30","30.gif"],
["images/31.gif","Alt / Title text for image 31","31.gif"],
["images/32.gif","Alt / Title text for image 32","32.gif"],// no comma at end of last index
]
imgPlaces=39 // number of images visible
imgWidth=22 // width of the images
imgHeight=22 // height of the images
imgSpacer=3 // space between the images
dir=0 // 0 = left, 1 = right
newWindow=1 // 0 = Open a new window for links 0 = no  1 = yes
// ********** End User Defining Area **********
moz=document.getElementById&&!document.all
step=1
timer=""
speed=50
nextPic=0
initPos=new Array()
nowDivPos=new Array()
function initHIS3(){
for(var i=0;i<imgPlaces+1;i++){ // create image holders
newImg=document.createElement("IMG")
newImg.setAttribute("id","pic_"+i)
newImg.setAttribute("src","")
newImg.style.position="absolute"
newImg.style.width=imgWidth+"px"
newImg.style.height=imgHeight+"px"
newImg.style.border=0
newImg.alt=""
newImg.i=i
//newImg.onclick=function(){his3Win(data[this.i][2])}
document.getElementById("display_area").appendChild(newImg)
}
containerEL=document.getElementById("his3container")
displayArea=document.getElementById("display_area")
pic0=document.getElementById("pic_0")
containerBorder=(document.compatMode=="CSS1Compat"?0:parseInt(containerEL.style.borderWidth)*2)
containerWidth=(imgPlaces*imgWidth)+((imgPlaces-1)*imgSpacer)
containerEL.style.width=containerWidth+(!moz?containerBorder:"")+"px"
containerEL.style.height=imgHeight+(!moz?containerBorder:"")+"px"
displayArea.style.width=containerWidth+"px"
displayArea.style.clip="rect(0,"+(containerWidth+"px")+","+(imgHeight+"px")+",0)"
displayArea.onmouseover=function(){stopHIS3()}
displayArea.onmouseout=function(){scrollHIS3()}
imgPos= -pic0.width
for(var i=0;i<imgPlaces+1;i++){
currentImage=document.getElementById("pic_"+i)
if(dir==0){imgPos+=pic0.width+imgSpacer} // if left
initPos[i]=imgPos
if(dir==0){currentImage.style.left=initPos[i]+"px"} // if left
if(dir==1){ // if right
document.getElementById("pic_"+[(imgPlaces-i)]).style.left=initPos[i]+"px"
imgPos+=pic0.width+imgSpacer
}
if(nextPic==data.length){nextPic=0}
currentImage.src=data[nextPic][0]
currentImage.alt=data[nextPic][1]
currentImage.i=nextPic
//currentImage.onclick=function(){his3Win(data[this.i][2])} //By This Click we can open new window on image....
nextPic++
}
scrollHIS3()
}
timer=""
function scrollHIS3(){
clearTimeout(timer)
for(var i=0;i<imgPlaces+1;i++){
currentImage=document.getElementById("pic_"+i)
nowDivPos[i]=parseInt(currentImage.style.left)
if(dir==0){nowDivPos[i]-=step}
if(dir==1){nowDivPos[i]+=step}
if(dir==0&&nowDivPos[i]<= -(pic0.width+imgSpacer) || dir==1&&nowDivPos[i]>containerWidth){
if(dir==0){currentImage.style.left=containerWidth+imgSpacer+"px"}
if(dir==1){currentImage.style.left= -pic0.width-(imgSpacer*2)+"px"}
if(nextPic>data.length-1){nextPic=0}
currentImage.src=data[nextPic][0]
currentImage.alt=data[nextPic][1]
currentImage.i=nextPic
currentImage.onclick=function(){his3Win(data[this.i][2])}
nextPic++
}
else{
currentImage.style.left=nowDivPos[i]+"px"
}
}
timer=setTimeout("scrollHIS3()",speed)
}
function stopHIS3(){
clearTimeout(timer)
}
function his3Win(loc){
if(loc==""){return}
if(newWindow==0){
location=loc
}
else{
//window.open(loc)
newin=window.open(loc,'win1','left=1,top=1,width=1,height=1') // use for specific size and positioned window
newin.focus()
}
}
// add onload="initHIS3()" to the opening BODY tag
// -->
</script>

<body onload="initHIS3();">

 <table>
        <tr>
        <td>   
       
      <DIV id="his3container_2" style="position:relative; width:10px;height:10px; border:1px solid red;overflow:hidden">
      <div id="display_area_2" style="position:absolute; left:10; top:10; width:10px; height:10px; clip:rect(0,0,0,0)"></div>
        </DIV> 
      </td>
      </tr>
      </table>

send mail from asp.net c#



-----------------------------------------------------------
On csFile----->  At Registration Saving Time--------
-------------------------------------------------------------
Session["bk"] = "1";
if (txt_Email.Text != "")
  {
       logic.Send_Mail("info@progressivewebservices.com", txt_Email.Text, txt_UserName.Text.Trim(), id.ToString(), "Joining Info From PWS", "Welcome in PWS </br> You have successfully Registred .  </br> Plz Login in PWS and Change your password ");
                               
}
-----------------------------------------
On clsLogic----->
--------------------------------------------
      
#region Mail Section
           
public int Send_Mail(string mainfrom ,string mailto, string name, string pwd, string subject, string message)
            {
                try
                {
                    string sbody = "";
                    sbody += "<html>";
                    sbody += "<body>";
                    sbody += "<table width='100%'>";
                    sbody += "<tr>";
                    sbody += "<td align='center' style='FONT-WEIGHT: bold;COLOR: #ffffff; FONT-SIZE: medium; FONT-STYLE: italic; BACKGROUND-COLOR: #A55129; FONT-VARIANT: small-caps'>" + "<b>" + "" + "</b>" + "</td>";
                    sbody += "</tr>";
                    sbody += "</table>";
                    sbody += "</body>";
                    sbody += "</html>";
                    sbody += "<html><head><title>Safe Life</title></head><body>" + "<p>From :<font color='red'> " + mainfrom + "</font></p>" + "<p>Title : " + subject + "</p>" + "<p></p>" + "</body></html>";
                    sbody += "\n";
                    sbody += "Name:" + name;
                    sbody += "<br>";
                    sbody += "UserID :" + pwd;
                    sbody += "<br>";
                    sbody += "<br>";
                    sbody += "Password :" + pwd;
                    sbody += "<br>";
                    sbody += "Message:";
                    sbody += message;
                    MailMessage msg = new MailMessage(mainfrom, mailto, subject, sbody);
                    msg.IsBodyHtml = true;
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = "mail.yourDomain.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
                    NetworkCred.UserName = "info@progressivewebservices.com";
                    NetworkCred.Password = "123456";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = NetworkCred;
                    smtp.Port = 587;
                    smtp.Send(msg);
                    return 1;
                }
                catch (Exception ex)
                {
                    return 1;
                }
            }
            //Function for Mail to Admin Email
            public void Mail_Admin(string msg)
            {
                //Send_Mail("creativeProduct@yahoo.com", "CreativeProduct", "10000000", "Exception Message", msg);
            }
           
#endregion
------------------------------------------------------------------

stop back button after logout in asp.net c#

Design a login page, give user name and password then redirect to some other page which is a content page of a Master page. In this master page one link button should be present for logout. When you click on the logout button it redirects to the login page. Then when you click on the back arrow of the browser it again goes to the previous page (that you already visit before logout). Even if you write code for session clear in logout button click event still it goes to previous page. To avoid this write few lines of code in Page_Init method of master page.
  protected void Page_Init(object sender, EventArgs e)
{
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();
}

popup in javascript in asp.net c#

<a href="javascript:void(0);" onclick="popup('http://www.google.com',
'googlePopup',700,600);">OPEN GOOGLE</a>
and the javascript function is
function popup(pageURL, title, popupWidth, popupHeight)
    {
        var left = (screen.width / 2) - (popupWidth / 2);
        var top = (screen.height / 2) - (popupHeight / 2);
        var targetPop = window.open(pageURL, title, 'toolbar=no, location=no, directories=no,
status=no, menubar=no, scrollbars=YES, resizable=YES, copyhistory=no, width=' + popupWidth + ',
height=' + popupHeight + ', top=' + top + ', left=' + left);
    }