/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Sunday, November 18, 2012

ASP.NET show alert message from server side

If you want to show msg if you are posting the page to server through update panal (asynchronous postback) then you have to use this function.

//During Asynchronous Post Back in Update Panal Use ScriptManager (Inside Update Panal)
public void alertBox(string Message)
{
ScriptManager.RegisterStartupScript(Page, this.GetType(),"Key", string.Format("alert('{0}');", Message), true);
}


If you want to show message in browser and want to show it through javascript (alert function)
then use this function.

// During synchronous normal Post Back Use ClientScript
public static void ShowMessage(string MessageText, PageMyPage)
{
MyPage.ClientScript.RegisterStartupScript(MyPage.GetType(),
"MessageBox", "alert('" + MessageText.Replace("'", "\'") +"');", true);
}
Read More »

Friday, October 19, 2012

Common Regular Expressions in ASP.NET

Some common regular expressions are shown here:

Common Regular Expressions



FieldExpressionFormat SamplesDescription
Name^[a-zA-Z''-'\s]{1,40}$John Doe
O'Dell
Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. You can modify this list.
Social Security Number^\d{3}-\d{2}-\d{4}$111-11-1111Validates the format, type, and length of the supplied input field. The input must consist of 3 numeric characters followed by a dash, then 2 numeric characters followed by a dash, and then 4 numeric characters.
Phone Number^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$(425) 555-0123
425-555-0123
425 555 0123
1-425-555-0123
Validates a U.S. phone number. It must consist of 3 numeric characters, optionally enclosed in parentheses, followed by a set of 3 numeric characters and then a set of 4 numeric characters.
E-mail ^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$someone@example.comValidates an e-mail address.
URL^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$http://www.microsoft.comValidates a URL
ZIP Code^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$12345Validates a U.S. ZIP Code. The code must consist of 5 or 9 numeric characters.
Password(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$Validates a strong password. It must be between 8 and 10 characters, contain at least one digit and one alphabetic character, and must not contain special characters.
Non- negative integer^\d+$0
986
Validates that the field contains an integer greater than zero.
Currency (non- negative)^\d+(\.\d\d)?$1.00Validates a positive currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point. For example, 3.00 is valid but 3.1 is not.
Currency (positive or negative)^(-)?\d+(\.\d\d)?$1.20Validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point.

ASP.NET TextBox.MultiLine maxlength

Add following javascript

function Count(text,long)
{
var maxlength = new Number(long); // Change number to your max length.
if(document.getElementById('<%=textBox.ClientID%>').value.length > maxlength){
text.value = text.value.substring(0,maxlength);
alert(" Only " + long + " chars");
}

Where “textBox” is the asp text box ID.
Also add following events in your textbox.

onKeyUp="javascript:Count(this,200);" onChange="javascript:Count(this,200);"

Your textbox code should look like





Solution Number 2 for

ASP.NET TextBox.MultiLine maxlength

Another way to achieve this is regular expression. You can add following regular expression validate on asp text box.

quot; runat="server" />



Hope this helps you!!!
Read More »

Friday, September 21, 2012

Dynamically set Gridview page size property in asp.net

Set Grid view page size property at run time in asp.net:

Here's an example:

ASPX 
<%@ page title="" language="C#" masterpagefile="~/MasterPages/Default.master" autoeventwireup="true"
    codefile="AllowPageSizing.aspx.cs" inherits="GridView_AllowPageSizing" %>

 id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
    Page Size:
     id="DropDownList1" runat="server" autopostback="True"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        2

       
5
       
10
   

   
id="GridView1" runat="server" style="margin-top: 20px;"
       
allowpaging="True" onpageindexchanging="GridView1_PageIndexChanging">
   

CODE-BEHIND 

using System;
using System.Web.UI.WebControls;
public partial class GridView_AllowPageSizing : System.Web.UI.Page
{
    private void GetData()
    {
        GridView1.PageSize = Int32.Parse(DropDownList1.SelectedValue);
        GridView1.DataSource = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
        GridView1.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.GetData();
        }
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridView1.PageIndex = 0;
        this.GetData();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        this.GetData();
    }
}
Read More »

Friday, August 31, 2012

C Sharp dot net Send Bulk SMS (Sending sms to mutiple recipient.)

Handling Web Request in c sharp dot net

Code Here:

///
/// Method used to send bulk sms
///

///

public void SendMsg(string URL)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL);

webRequest.Method = WebRequestMethods.Http.Get;

webRequest.AllowAutoRedirect = true;

webRequest.PreAuthenticate = true;

webRequest.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;

webRequest.KeepAlive = false; // Set Keep alive to false (not to make persistent connection with server)

webRequest.ContentType = "application/x-www-form-urlencoded";

HttpWebResponse res = (HttpWebResponse)(webRequest.GetResponse());

System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), Encoding.GetEncoding("UTF-8"));

StringBuilder responseText = new StringBuilder(String.Empty);

responseText.Append(sr.ReadToEnd());

webRequest = null;
}
catch (Exception _ex)
{}
}
________________________________________________________________________________

///
/// Method for sending sms to all user that belong to the hierarchy selected from the hierarchy chain
///
    private void SendSMS()
    {
        //Do not change
        string FeedID = "287089";
        //Your number
        string sendTo = "";
        //Do not change
        string Uname = "9833664117";
        //Do not change
        string Pwd = "awajw";

        string Query = "";

        string msg = "";

        dsRecord = ObjComFunc.GetAnnouncement(Convert.ToInt32(Request.QueryString["id"].ToString()), "SI");
        if (dsRecord != null)
        {
            if (dsRecord.Tables[0].Rows.Count > 0)
            {
                msg = Convert.ToString(dsRecord.Tables[0].Rows[0]["S_Brief_Desc"].ToString());
            }
        }
        else
        {
            msg = "";
        }
        
        //string msg = "We have received your request for verification code. Your code is 1234. If you have not requested code, kindly ignore this message.";

        //Gett All Center Numbers
        DataTable dtSendTo = GetCentersPhoneNumbers();

        if (dtSendTo != null)
        {
            if (dtSendTo.Rows.Count > 0)
            {
                for (int i = 0; i < dtSendTo.Rows.Count; i++)
                {
                    sendTo = dtSendTo.Rows[i][0].ToString().Trim();
                    Query = "http://bulkpush.mytoday.com/BulkSms/SingleMsgApi?feedid=" + FeedID + "&To=" + sendTo + "&UserName=" + Uname + "&Password=" + Pwd + "&Text=" + msg;
                    ObjComFunc.SendMsg(Query);
                    //Response.Redirect(Query);
                }
            }
        }
    }
________________________________________________________________________________
Read More »

Wednesday, August 22, 2012

ASP.NET Sorting in GridView By Columns Header In Asp.Net Ascending Descending


http://csharpdotnetfreak.blogspot.com/2012/06/sorting-gridview-columns-headers-aspnet.html

Sorting GridView By Columns Header In Asp.Net Ascending Descending

This is example of how to enable Sorting In GridView By Clicking on Columns Or Headers In Ascending Or Descending Direction In Asp.Net Using C# And VB

If you have Populated GridView With ObjectDataSource or SqlDataSOurce to Insert Update Edit Delete record , then You just have toset AllowSorting property to True andSortExpression property of columns to respective field from database to sort.

Setting these properties changes column names to hyperlink and No coding is required

Write html source as mentioned below 

<asp:GridView ID="gvDetails" runat="server" 
              AutoGenerateColumns="False" 
              onsorting="gvDetails_Sorting">
<Columns>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" Text='<%#Eval("FirstName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" Text='<%#Eval("LastName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location" SortExpression="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


IF SQLCONNECTION AND SQLCOMMAND IS USED IN CODE BEHIND

If data is populated from database using code behind, then to sortwe need to write custom codeto save direction (Ascending or Descending) in ViewState and writecode in Sorting Event of Grid.

Populate and load GridView on Page_Load Event

BindGridView Method fetches data from database and return it as DataTable.

C# CODE

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            gvDetails.DataSource = BindGridView();
            gvDetails.DataBind();
        }
    }

    private DataTable BindGridView()
    {
        DataTable dtGrid = new DataTable();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        string strSelect = "SELECT FirstName,LastName,Location FROM Details";
        SqlCommand cmd = new SqlCommand(strSelect, con);
        SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
        dAdapter.Fill(dtGrid);
        return dtGrid;
    }
VB.NET CODE

Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not Page.IsPostBack Then
  gvDetails.DataSource = BindGridView()
  gvDetails.DataBind()
 End If
End Sub

Private Function BindGridView() As DataTable
 Dim dtGrid As New DataTable()
 Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
 Dim strSelect As String = "SELECT FirstName,LastName,Location FROM Details"
 Dim cmd As New SqlCommand(strSelect, con)
 Dim dAdapter As New SqlDataAdapter(cmd)
 dAdapter.Fill(dtGrid)
 Return dtGrid
End Function
Create Public Property of SortDirection type and store direction in ViewState.
C# CODE
public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {
                ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        }
        set
        {
            ViewState["dirState"] = value;
        }
    }
VB.NET CODE
Public Property dir() As SortDirection
 Get
  If ViewState("dirState") Is Nothing Then
   ViewState("dirState") = SortDirection.Ascending
  End If
  Return DirectCast(ViewState("dirState"), SortDirection)
 End Get
 Set
  ViewState("dirState") = value
 End Set
End Property
Check Gridview's current direction from ViewState and set new sort direction in Sorting Event.
C# CODE
protected void gvDetails_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortingDirection = string.Empty;
        if (dir == SortDirection.Ascending)
        {
            dir = SortDirection.Descending;
            sortingDirection = "Desc";
        }
        else
        {
            dir = SortDirection.Ascending;
            sortingDirection = "Asc";
        }
        
        DataView sortedView = new DataView(BindGridView());
        sortedView.Sort = e.SortExpression + " " + sortingDirection;
        gvDetails.DataSource = sortedView;
        gvDetails.DataBind();
    }
VB.NET CODE
Protected Sub gvDetails_Sorting(sender As Object, e As GridViewSortEventArgs)
 Dim sortingDirection As String = String.Empty
 If dir = SortDirection.Ascending Then
  dir = SortDirection.Descending
  sortingDirection = "Desc"
 Else
  dir = SortDirection.Ascending
  sortingDirection = "Asc"
 End If

 Dim sortedView As New DataView(BindGridView())
 sortedView.Sort = Convert.ToString(e.SortExpression) & " " & sortingDirection
 gvDetails.DataSource = sortedView
 gvDetails.DataBind()
End Sub
Read More »

Tuesday, August 21, 2012

SQL SERVER IN query between two comma separated column using split method

Split Method for split column value . . .


CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
        declare @idx int
        declare @slice varchar(8000)
   

        select @idx = 1
                if len(@String)<1 is="is" nbsp="nbsp" null="null" or="or" p="p" return="return" tring="tring">   

        while @idx!= 0
        begin
                set @idx = charindex(@Delimiter,@String)
                if @idx!=0
                        set @slice = left(@String,@idx - 1)
                else
                        set @slice = @String
               

                if(len(@slice)>0)
                        insert into @temptable(Items) values(@slice)


                set @String = right(@String,len(@String) - @idx)
                if len(@String) = 0 break
        end
return
end
__________________________________________________________________________


WITH testdata
(
CommaColumn,
I_AddContest_Id,
I_ModeratorID,
S_Moderator,
S_ContestTitle,
S_Contest_Image,
S_Brief_Desc,
I_Hierarchy_Detail_ID,
I_Hierarchy_Master_ID
)
AS
(

SELECT
(',' + cast(I_ModeratorID as varchar) +',' + S_ZoneID +','+ S_AreaId +','+ S_CityId +','+ S_CentreID +',') as [FK_I_Hierarchy_Detail_ID],
A.I_AddContest_Id,
A.I_ModeratorID,
A.S_Moderator,
A.S_ContestTitle,
A.S_Contest_Image,
A.S_Brief_Desc,
B.I_Hierarchy_Detail_ID,
B.I_Hierarchy_Master_ID
FROM PULSEMKTG.T_Contest_Master AS A
LEFT OUTER JOIN T_User_Hierarchy_Details AS B
ON B.I_Hierarchy_Master_ID = A.I_ModeratorID
WHERE
A.Active=1
AND A.Approve=0 AND B.I_Status <> 0
AND GETDATE() >= ISNULL(B.Dt_Valid_From,GETDATE())
AND GETDATE() <= ISNULL(B.Dt_Valid_To,GETDATE())
AND B.I_User_ID = @I_User_ID  
)

SELECT
MAX(I_AddContest_Id) AS I_AddContest_Id  
,MAX(I_ModeratorID) AS I_ModeratorID
,MAX(S_Moderator) AS S_Moderator
,MAX(S_ContestTitle) AS S_ContestTitle  
,MAX(S_Contest_Image) AS S_Contest_Image
,MAX(cast(S_Brief_Desc as varchar(max))) AS S_Brief_Desc
FROM
(
SELECT D.items AS SplitValue,* FROM testdata AS C
CROSS APPLY dbo.Split(C.CommaColumn,',') AS D
WHERE
C.I_Hierarchy_Detail_ID = D.items
OR
C.I_Hierarchy_Master_ID = C.I_ModeratorID
) AS E

GROUP BY E.I_AddContest_Id
ORDER BY E.I_AddContest_Id DESC


Read More »

ASP.NET Getting files from directory


How to get files from directory on the server map path ?

GetFilesFromDirectory(MapPath("~/temp/"));
private void GetFilesFromDirectory(string DirPath)
{
     try
     {
     int id = 0;

     DirectoryInfo Dir = new DirectoryInfo(DirPath);         

     FileInfo[] FileList = Dir.GetFiles("*.*");

    dsFiles = comfunc.GetAllUserDetails(Convert.ToInt32(Request.QueryString["id"].ToString()), "SFILE");

    if (dsFiles.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dsFiles.Tables[0].Rows.Count; i++)
                {
                    foreach (FileInfo FI in FileList)
                    {
                        if (dsFiles.Tables[0].Rows[i]["fname"].ToString() == FI.FullName)
                        {
                           FI.Delete();
                        }
                        id++;
                        //
                    }
                }
            }
            FillClientDetails();
        }
        catch (Exception ex)
        {

        }
    }
Read More »

Tuesday, July 17, 2012

Sql Server 2005: Change schema for all tables

Recently I have needed to change the schema for all the tables in a Sql Server 2005 database.

Sql Server 2005 provides a T-SQl statement capable to change the schema for a given object called ALTER SCHEMA 

You may use the following syntax to change the schema for all the tables in a database. Just change the "new_schema" string with the desired one:

exec sp_MSforeachtable "ALTER SCHEMA new_schema TRANSFER ? PRINT '? modified' "

Enjoy the Script!
Read More »

My Blog List