Aspdotnetsummary

 setting focus of the modal popup by script

<script language="javascript" type="text/javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

        var blnReportWinOpen = false;
        function BeginRequestHandler(sender, args) {

            $find('<%= mpeProgress.ClientID %>').show();
        }
        function EndRequestHandler(sender, args) {
            $find('<%= mpeProgress.ClientID %>').hide();

        }
    </script>

</body>

 

RadTreeView.Net2.dll and xml

Telrik and DevExpress

Assembly name
RadPanelbar.Net2.dll and xml
RadChart.dll and xml
 Global.asax
It is use to handle session and application state .
when the application loads first it calls The Application_OnStart then Session_Start then Page_Load event
 
TextOnImage.aspx
         <asp:Image ID="Image1" runat="server" ImageUrl="~/ImageTextFile.aspx"/>
 
ImageTextFile Page_Load event
using System.Drawing;
using System.Drawing.Imaging;
ff 
protected void Page_Load(object sender, EventArgs e)
{
         Bitmap bitmapImage = new Bitmap(Server.MapPath("Water lilies.jpg"));
 Graphics g = Graphics.FromImage(bitmapImage);
   g.DrawString("Hi EveryOne", new Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new PointF(10, 10));
 Response.ContentType = "image/jpg";
bitmapImage.Save(Response.OutputStream, ImageFormat.Jpeg);
}
 
<asp:TextBox ID="txtStaffNumber" Style="width: 220px;" runat="server" ReadOnly="false"TabIndex="1"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtStaffNumber"
         ErrorMessage="Staff No : Can not be blank" ToolTip="Staff Number: Can not be blank"
         Display="Dynamic" SetFocusOnError="true" ValidationGroup="Step1"> </asp:RequiredFieldValidator>
 
<asp:ImageButton runat="server" ID="btnUpdate" ImageUrl="~/images/buttons/PHS/submit_1.gif"
                    ValidationGroup="Step1" OnClick="btnUpdate_Click" />
 <asp:Button ID="Button1" runat="server" Text="Button" />
NOTE:-
ValidationGroup value Validator will work only for that ValidationGroup only
On Button1 click the validator will not show error
TabIndex if we set the increment +1 for each control then on Tab click it will move according to number but the no
control should have TabIndex=0 which is ByDefaullt make it to -1 for control we don't want the focus on tab click
 
Repeater Control
 In Repeater1_ItemDataBound it takes the Item(Rows) as Item and AlternateItem so
Repeater1_ItemDataBound event
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 
Adding ......... aftre the 200 character
 
string str_content;
 
Label lblContent=(Label)e.Item.FindControl("lblContent");
For Repeater control
Label lblContent=(Label)e.Item.FindControl("lblContent");
str_content = (string)DataBinder.Eval(e.Item.DataItem, "ContentText");
 
Label lblContent=(Label)e.Item.FindControl("lblContent");
 
For Gridview control
Label lblContent=(Label)e.Row.FindControl("lblContent");
str_content = (string)DataBinder.Eval(e.Row.DataItem, "ContentText");
int count = str_content.Length;
if (count > 200)
{
string sub = str_content.Substring(0, 200);
lblContent.Text = sub + "....";
}
else
{
lblContent.Text = str_content;
}
ff
ff
BATCH Update

1 table

public static int UpdateDataset(DataSet dsData)
    {
        int res = 1;
        if (dsData == null) return -1;
        using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["HYJIYAREVAMP"].ConnectionString))
        {
            myConnection.Open();
            SqlTransaction transaction = myConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
            try
            {
                foreach (DataTable dt in dsData.Tables)
                {

                    if (dt != null && dt.GetChanges() != null && dt.GetChanges().Rows.Count > 0)
                    {
                        SqlDataAdapter da = new SqlDataAdapter();
                        string strQuery = selectQuery(dt);
                        SqlCommand cmd = new SqlCommand(strQuery, myConnection, transaction);
                        da.SelectCommand = cmd;
                        //da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();
                        SqlCommandBuilder cmb = new SqlCommandBuilder();
                        cmb.DataAdapter = da;
                        da.UpdateBatchSize = dt.Rows.Count;
                        da.Update(dt);
                    }
                }
                transaction.Commit();
            }
            catch (Exception ex)
            {
                res = -1;
                transaction.Rollback();
            }
            finally
            {
                if (myConnection != null && myConnection.State == ConnectionState.Open)
                    myConnection.Close();
            }
        }
        return res;
    }

    internal static string selectQuery(DataTable dt)
    {
        if (dt != null && dt.Columns.Count > 0)
        {
            string strQuery = "select top 1 ";
            foreach (DataColumn dc in dt.Columns)
            {
                strQuery += ",[" + dc.Caption + "]";
            }
            strQuery = strQuery.Replace("select top 1 ,", "select top 1 ");
            strQuery += " from " + dt.TableName;
            return strQuery;
        }
        else
            return "select top 1 * from " + dt.TableName + " with (readpast)";
    }

Multiple Table

Have PK and FK Releationship

 public int Update(DataSet dsData)
        {
            int result = -1;
            using (SqlConnection myConnection = new SqlConnection(DB.GetConnectionString(0)))
            {
                myConnection.Open();
                SqlTransaction transaction = myConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                try
                {
                    List<string> lstComputedIds = null; List<string> lstDBIds = null;

                    if (dsData != null && dsData.Tables.Count > 0
                                                && dsData.Tables["kpi_ToolControlMaster"] != null
                                                && dsData.Tables["kpi_ToolControlMaster"].Rows.Count > 0)
                    {
                        lstComputedIds = getComputedIds(dsData.Tables["kpi_ToolControlMaster"], "CtrlToolID");
                        lstDBIds = getEquevalantDBIds(myConnection, transaction, dsData.Tables["kpi_ToolControlMaster"], lstComputedIds, "CtrlToolID");
                        getUpdateDetailTables(dsData.Tables["kpi_ToolControlData"], lstComputedIds, lstDBIds, "CtrlToolID", typeof(int));
                        dsData.Tables.Remove("kpi_ToolControlMaster");
                    }
                    result = UpdateDataSet(myConnection, transaction, dsData);
                    transaction.Commit();
                }
                catch
                {
                    result = -1;
                    transaction.Rollback();
                }
                finally
                {
                    if (myConnection != null && myConnection.State == ConnectionState.Open)
                        myConnection.Close();
                }
            }
            return result;
        }
        public int UpdateDataSet(SqlConnection connection, SqlTransaction transaction, DataSet ds)
        {
            try
            {
                if (ds != null)
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        if (dt != null && dt.GetChanges() != null && dt.GetChanges().Rows.Count > 0)
                        {
                            string strQuery = selectQuery(dt);
                            SqlDataAdapter da = new SqlDataAdapter();
                            da.SelectCommand = getCommand(strQuery, connection, transaction);
                            SqlCommandBuilder cmb = new SqlCommandBuilder();
                            cmb.DataAdapter = da;
                            da.UpdateBatchSize = dt.Rows.Count;
                            da.Update(dt.GetChanges());
                        }
                    }
                }
            }
            catch
            {
                return -1;
            }
            return 1;
        }
        public List<string> getEquevalantDBIds(SqlConnection connection, SqlTransaction transaction, DataTable dtMst, List<string> lstComputedIds, string Pkey)
        {
            if (dtMst != null && dtMst.Rows.Count > 0)
            {
                List<string> lstIds = new List<string>();

                string strQuery = selectQuery(dtMst);
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = getCommand(strQuery, connection, transaction);
                SqlCommandBuilder cmb = new SqlCommandBuilder();
                cmb.DataAdapter = da;
                da.Update(dtMst);

                DataTable dtEqueDBTable = new DataTable();
                da = new SqlDataAdapter();
                da.SelectCommand = getCommand("select top " + lstComputedIds.Count + " * from " + dtMst.TableName + "  order by 1 desc", connection, transaction);
                da.Fill(dtEqueDBTable);
                if (dtEqueDBTable != null && dtEqueDBTable.Rows.Count > 0)
                {
                    for (int i = dtEqueDBTable.Rows.Count - 1; i >= 0; i--)
                    {
                        if (dtEqueDBTable.Columns.Contains(Pkey) == true)
                            lstIds.Add(dtEqueDBTable.Rows[i][Pkey].ToString());
                    }
                    return lstIds;
                }
            }
            return null;
        }
        public DataTable getUpdateDetailTables(DataTable dtDet, List<string> strComputedIds, List<string> strDBIds, string Fkey, Type fkType)
        {
            if (dtDet != null && dtDet.Rows.Count > 0 && strDBIds != null && strComputedIds != null && strDBIds.Count == strComputedIds.Count)
            {
                DataView dv = null;
                for (int j = 0; j < strComputedIds.Count; j++)
                {
                    dv = new DataView(dtDet);
                    if (fkType == typeof(int))
                        dv.RowFilter = Fkey + " = " + strComputedIds[j];
                    if (fkType == typeof(string))
                        dv.RowFilter = Fkey + " = '" + strComputedIds[j] + "'";
                    int cnt = dv.Count;
                    for (int i = 0; i < cnt; i++)
                    {
                        dv[0][Fkey] = strDBIds[j];
                    }
                }
            }
            return dtDet;
        }
        internal string selectQuery(DataTable dt)
        {
            if (dt != null && dt.Columns.Count > 0)
            {
                string strQuery = "select top 1 ";
                foreach (DataColumn dc in dt.Columns)
                {
                    strQuery += ",[" + dc.Caption + "]";
                }
                strQuery = strQuery.Replace("select top 1 ,", "select top 1 ");
                strQuery += " from " + dt.TableName;
                return strQuery;
            }
            else
                return "select top 1 * from " + dt.TableName + " with (readpast)";
        }
        public SqlCommand getCommand(string query, SqlConnection con, SqlTransaction transaction)
        {
            SqlCommand cmd = new SqlCommand(query);
            cmd.Connection = con;
            cmd.Transaction = transaction;
            cmd.CommandTimeout = 0;
            return cmd;
        }
        public List<string> getComputedIds(DataTable dtMst, string Pkey)
        {
            if (dtMst != null && dtMst.Rows.Count > 0)
            {
                List<string> lstIds = new List<string>();
                foreach (DataRow dr in dtMst.Rows)
                {
                    if (dtMst.Columns.Contains(Pkey) == true && dr.RowState == DataRowState.Added)
                        lstIds.Add(dr[Pkey].ToString());
                }
                return lstIds;
            }
            return null;
        }

Calling Batch Upadate
DataSet dsa = new DataSet();
        dtCurrentMedication = (DataTable)ViewState["DataTable"];
        dsa.Tables.Add(dtCurrentMedication);
int id = Common.UpdateDataset(dsa);
ff
ff
Generate the Random value by passing the length of the o/p value
public String generateRandomString(int length)
{
String randomString = "";
int randNumber;
Random random = new Random();
Random random = new Random();
for (int i = 0; i < length; i++)
{
if (random.Next(1, 3) == 1)
randNumber = random.Next(97, 123); //char {a-z}
else
randNumber = random.Next(48, 58); //int {0-9}
//append random char or digit to random string
randomString = randomString + (char)randNumber;
}
return randomString;
}
 
asp:ImageButton Issue
The PostBackUrl cannot call html page
 
 
PreView The Image Before Saving in aa folder or databaseBut it works only in IE
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImagePreviewFileUpload.aspx.cs"
    Inherits="ImagePreviewFileUpload" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Asp FileUpload Image Preview</title>
    <style type="text/css">
        #newPreview
        {
            filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);
        }
    </style>

    <script language="javascript" type="text/javascript">
    function PreviewImg(imgFile)
    {
        var newPreview = document.getElementById("newPreview");
        newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgFile.value;
        newPreview.style.width = "80px";
        newPreview.style.height = "60px";
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    Add Refrence-> COM-> Interop.DXTMSFTLib.dll AND Interop.IMAGEVIEWERLib.dll
    <br />
        preview
        <asp:FileUpload ID="Fud_Pic" runat="server" onchange="PreviewImg(this)" /><%--onBlur="PreviewImg(this)" --%>
        <div id="newPreview">
        </div>
    </div>
    </form>
</body>
</html>

 
2)
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
    <title>Image preview example</title>

    <script type="text/javascript">
oFReader = new FileReader(), rFilter = /^(?:image/bmp|image/cis-cod|image/gif|image/ief|image/jpeg|image/jpeg|image<br/>

/jpeg|image/pipeg|image/png|image/svg+xml|image/tiff|image/x-cmu-raster|image/x-cmx|image/x-icon|image/x<br/>

-portable-anymap|image/x-portable-bitmap|image/x-portable-graymap|image/x-portable-pixmap|image/x-rgb|image<br/>

/x-xbitmap|image/x-xpixmap|image/x-xwindowdump)$/i;

oFReader.onload = function (oFREvent) {
alert("1");
alert(oFREvent.target.result);
  document.getElementById("uploadPreview").src = oFREvent.target.result;
};

function loadImageFile() {
alert(document.getElementById("uploadImage").value);
  if (document.getElementById("uploadImage").files.length === 0) { return; }
  var oFile = document.getElementById("uploadImage").files[0];
  alert(oFile);
  if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
  oFReader.readAsDataURL(oFile);
}
    </script>

</head>
<body>
    <form>
    <table>
        <tbody>
            <tr>
                <td>
                    <img id="uploadPreview" style="width: 100px; height: 100px;" alt="Image preview" />
                </td>
                <td>
                    <input id="uploadImage" type="file" name="myPhoto" onchange="loadImageFile();" />
                </td>
            </tr>
        </tbody>
    </table>
    <p>
        <input type="submit" value="Send" /></p>
    </form>
</body>

 
3)
<script type="text/javascript" language="javascript">
    function ImageViw(string)
    {
        var imgPreview=document.getElementById("imgPreview");
        document.getElementById('imgPreview').src='File://' + string;
    }
    </script>

<asp:FileUpload ID="JFileUp" runat="server" onchange="javascript:ImageViw(this.value);" />
        <img id="imgPreview" runat="server" />

 
 

Only letters:

<p>

<span class="typ">Regex</span><span class="pun">.</span><span class="typ">IsMatch</span><br/><br /><br /><br /><span class="pun">(</span><br/><br /><br /><span class="pln">input</span><br/><br /><br /><span class="pun">,</span><br /><span class="str">@"^[a-zA-Z]+$"</span><br/><br /><br /><span class="pun">);</span><span class="pln"><br /></span><br /></p><br />

Only letters and numbers:

<span class="typ">Regex</span><span class="pun">.</span><span class="typ">IsMatch</span><br/><br /><br /><br /><span class="pun">(</span><span class="pln">input</span><br/><br /><br /><span class="pun">,</span><br /><span class="str">@"^[a-zA-Z0-9]+$"</span><br/><br /><br /><span class="pun">);</span><span class="pln"><br /></span>

Only letters, numbers and underscore:

<span class="typ">Regex</span><span class="pun">.</span><span class="typ">IsMatch</span><br/><br /><br /><br /><span class="pun">(</span><span class="pln">input</span><span class="pun">,</span><br/><br /><br /><br /><span class="str">@"^[a-zA-Z0-9_]+$"</span><span class="pun">);</span><br/><br /><br /><br /><span class="pln"><br /></span>
 

 retrieving the distinct column values

string[] strColumnsManagerArr = { "Acc Manager name", "AccountMangerID" };
            DataTable dtManage = ds.Tables[0].DefaultView.ToTable(true, strColumnsManagerArr);

 

 Thread

1. How to create Thread?

 A. Namespace.

 using System.Threading;
 Thread  t1 = new Thread(new System.Threading.ThreadStart(sendMail));   //sendMail function should be parameterless
            t1.Start();
 

 publi void sendMail() {//here your full fletch code

}

 
 2. How to work with TWO thread.
 A. Create two instance of thread.

 Thread t1=new Thread(ThreadStart(sendmail));

Thread t2=new Thread(ThreadStart(EnterValue));

t1.start; //initiall it required to start the thread if want to make thread wait use t.Interrupt();--like WaitSleepJoin

   public void sendMail()
        {
            while (true)
            {
                foreach (DataRow dr in dtEmail.Rows)
                {
                    if (i < dtEmail.Rows.Count)
                    {
                        try
                        {
                            dr["Status"] = "process";
                            objSendEmail.sendMail(objEmailBO, Convert.ToString(dr["Email"]));
                            t1.Interrupt();
                            dr["Status"] = "Success";
                            str_Success = Convert.ToString(Convert.ToInt32(str_Success) + 1);
                            if (i == 0)
                            {
                                t2.Start();
                            }
                            else
                            {
                                //t2.Resume();
                            }

                        }
                        catch (Exception ex)
                        {
                            t1.Interrupt();
                            dr["Status"] = "Failed";
                            str_Fail = Convert.ToString(Convert.ToInt32(str_Fail) + 1);
                            if (i == 0)
                            {
                                t2.Start();
                            }
                        }
                        i++;
                    }
                }
            }
        }
        public void EnterNo()
        {
            try
            {
                while (true) //runs cont.
                {

//Here we are using a variable which is running on different thread  (str_Success & str_Fail)

//So we use this if condition
                    if (txtSuccessEmail.InvokeRequired)
                    {
                        txtSuccessEmail.Invoke(new MethodInvoker(delegate { txtSuccessEmail.Text = str_Success; }));
                    }
                    if (txtFailEmail.InvokeRequired)
                    {
                        txtFailEmail.Invoke(new MethodInvoker(delegate { txtFailEmail.Text = str_Fail; }));
                    }
                    txtSuccessEmail.Text = str_Success;
                    txtFailEmail.Text = str_Fail;
                    t2.Interrupt();
                }
            }
            catch (Exception ex)
            {
                if (txtSuccessEmail.InvokeRequired)
                {
                    txtSuccessEmail.Invoke(new MethodInvoker(delegate { txtSuccessEmail.Text = str_Success; }));
                }
                if (txtFailEmail.InvokeRequired)
                {
                    txtFailEmail.Invoke(new MethodInvoker(delegate { txtFailEmail.Text = str_Fail; }));
                }
                txtSuccessEmail.Text = str_Success;
                txtFailEmail.Text = str_Fail;
                t2.Interrupt();
            }
        }

 
 Export gridview to excel
  <table>
            <tr>
                <td>
                    <asp:ImageButton ID="imgExcel" runat="server" ImageUrl="~/ExcelImage.jpg" OnClick="imgExcel_OnClick" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:GridView runat="server" ID="gvdetails" DataSourceID="SqlDataSource1" AllowPaging="true"
                        AllowSorting="true" AutoGenerateColumns="false">
                        <RowStyle BackColor="#EFF3FB" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:BoundField DataField="Fid" HeaderText="Fid" />
                            <asp:BoundField DataField="User_FirstName" HeaderText="User_FirstName" />
                            <asp:BoundField DataField="User_LastName" HeaderText="User_LastName" />
                            <asp:BoundField DataField="User_Email" HeaderText="User_Email" />
                            <asp:BoundField DataField="User_LoginId" HeaderText="User_LoginId" />
                            <asp:BoundField DataField="User_Pwd" HeaderText="User_Pwd" />
                            <asp:CheckBoxField DataField="User_Locked" HeaderText="User_Locked" />
                            <asp:BoundField DataField="User_RoleId" HeaderText="User_RoleId" />
                            <asp:BoundField DataField="Pid" HeaderText="Pid" />
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
        </table> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:local %>"
        SelectCommand="SELECT * FROM [Users]"></asp:SqlDataSource>
 Code
  protected void imgExcel_OnClick(object sender, ImageClickEventArgs e)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "asd.xls"));
        HttpContext.Current.Response.ContentType = "application/vn.xls";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gvdetails.HeaderRow != null)
                {
                    PrepareControlForExport(gvdetails.HeaderRow);
                    table.Rows.Add(gvdetails.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gvdetails.Rows)
                {
                    PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gvdetails.FooterRow != null)
                {
                    PrepareControlForExport(gvdetails.FooterRow);
                    table.Rows.Add(gvdetails.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                PrepareControlForExport(current);
            }
        }
    }
RSSS 
 <asp:XmlDataSource ID="XmlNewsFeed" runat="server" DataFile="http://www.logisticsit.com/feed.rss?tag=Supply+Chain"
                    XPath="rss/channel/item"></asp:XmlDataSource>
                <asp:GridView ID="gvdnew" runat="server" DataSourceID="XmlNewsFeed" AutoGenerateColumns="false"
                    AllowPaging="true" ShowHeader="false" border="0" BorderWidth="0" OnRowDataBound="gvdnew_OnRowDataBound"
                    Width="95%" PageSize="8" PagerStyle-CssClass="Pg">
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <div class="NCont">
                                    <div class="header_05" style="font-family: calibri;">
                                        <a id="lnk1" href='<%# XPath("link")%>' runat="server" target="_blank" style="font-size: 14px;">
                                            <%# XPath("title")%></a></div>
                                    <asp:Label ID="Label1" runat="server" Text='<%# XPath("pubDate")%>' Style="text-align: justify;
                                        font-size: 13px; color: black; font-family: calibri;"></asp:Label><br />
                                    <asp:Label ID="lblDesc" runat="server" Text='<%# XPath("description")%>' Style="text-align: justify;
                                        font-size: 12px; color: black; font-family: calibri;"></asp:Label>
                                </div>
                                <div class="cleaner">
                                </div>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

 From Code behind

http://www.aspsnippets.com/Articles/Fetch-and-Display-RSS-Feeds-using-ASP.Net.aspx

Asp Char control

Allow Single decimal point Regular expression

d+(.d{1,2})?

 

Gridview Export to excel (Even if it is nested gridview)

protected void ImgExport_OnClick(object sender, EventArgs e)
        {
            try
            {
                gvCompanyListing.AllowPaging = false;
                GetValueAndBind();
                //table1.BorderStyle = BorderStyle.Solid;

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=ReportPendingPayment" + ".xls", gvCompanyListing));
                HttpContext.Current.Response.ContentType = "application/vn.xls";

                #region "Add Filter data"
                TableRow tRow = new TableRow();
                TableCell c1 = new TableCell();
                string strComapanyText = ddlCompany.SelectedIndex > 0 ? ddlCompany.SelectedItem.Text : "All";
                c1.Text = "Company = " + strComapanyText;
                c1.HorizontalAlign = HorizontalAlign.Left;

                tRow.Cells.Add(c1);
                table1.Rows.Add(tRow);

                tRow = new TableRow();
                c1 = new TableCell();

                string strStartDate = !string.IsNullOrEmpty(datepickerStartDate.Value) ? datepickerStartDate.Value : "N/A";
                string strEnddate = !string.IsNullOrEmpty(datepickerEndDate.Value) ? datepickerEndDate.Value : "N/A";
                c1.Text = "Start Date = " + strStartDate + " &nbsp; &nbsp;&nbsp;     End Date = " + strEnddate;
                c1.HorizontalAlign = HorizontalAlign.Left;
                tRow.Cells.Add(c1);
                table1.Rows.Add(tRow);
                #endregion

                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        //  Create a form to contain the grid

                        //  add the header row to the table
                        if (gvCompanyListing.HeaderRow != null)
                        {
                            PrepareControlForExport(gvCompanyListing.HeaderRow);
                            table1.Rows.Add(gvCompanyListing.HeaderRow);
                        }

                        //  add each of the data rows to the table
                        foreach (GridViewRow row in gvCompanyListing.Rows)
                        {
                            PrepareControlForExport(row);
                            row.BackColor = Color.Yellow;
                            table1.Rows.Add(row);
                            TableRow tr = new TableRow();
                            TableCell cell = new TableCell();
                            tr.Cells.Add(cell);
                            table1.Rows.Add(tr);
                        }

                        //  add the footer row to the table
                        if (gvCompanyListing.FooterRow != null)
                        {
                            PrepareControlForExport(gvCompanyListing.FooterRow);
                            table1.Rows.Add(gvCompanyListing.FooterRow);
                        }

                        //  render the table into the htmlwriter
                        table1.RenderControl(htw);

                        //  render the htmlwriter into the response
                        HttpContext.Current.Response.Write(sw.ToString());
                        HttpContext.Current.Response.End();
                    }
                }

            }
            catch (Exception ex) { }
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
            /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
               server control at run time. */
        }
        private void PrepareControlForExport(Control control)
        {
            try
            {
                for (int i = 0; i < control.Controls.Count; i++)
                {
                    Control current = control.Controls[i];
                    if (current is LinkButton)
                    {
                        control.Controls.Remove(current);
                        control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                    }
                    else if (current is ImageButton)
                    {
                        control.Controls.Remove(current);
                        control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                    }
                    else if (current is HyperLink)
                    {
                        control.Controls.Remove(current);
                        control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                    }
                    else if (current is DropDownList)
                    {
                        control.Controls.Remove(current);
                        control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                    }
                    else if (current is CheckBox)
                    {
                        control.Controls.Remove(current);
                        control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                    }

                    if (current.HasControls())
                    {
                        PrepareControlForExport(current);
                    }
                }
            }
            catch (Exception ex) { }
        }

 

 

 

Comma seperate in Gridview

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
    <Columns>
    <asp:TemplateField HeaderText="Values">
        <ItemTemplate>
            <asp:Literal runat="server" id="Values"
                Text='<%# string.Join("<br />", Eval("Values").ToString().Split(new []{","},StringSplitOptions.None)) %>'>
            </asp:Literal>
        </ItemTemplate>
    </asp:TemplateField>
    </Columns>
</asp:GridView>

 

Output Direction

 string CommandString = @"insert into Kpi_Company values(@cname) set @newid = SCOPE_IDENTITY() ";
                Command = new SqlCommand(CommandString, Connection);
                Command.Parameters.AddWithValue("@cname", cname);
                Command.Parameters.Add("@newid", SqlDbType.Int).Direction = ParameterDirection.Output;
                Connection.Open();
                Command.ExecuteNonQuery();
                id = Convert.ToInt64(Command.Parameters["@newid"].Value.ToString());
                Connection.Close();
                Connection.Dispose();

 

 

 

public string EncryptData(string Message)
        {
            try
            {
                byte[] Results;
                string passphrase = "password";
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
                byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
                TDESAlgorithm.Key = TDESKey;
                TDESAlgorithm.Mode = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;
                byte[] DataToEncrypt = UTF8.GetBytes(Message);
                try
                {
                    ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                    Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
                }
                finally
                {
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }
                return Convert.ToBase64String(Results);
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public string DecryptString(string Message)
        {
            try
            {
                byte[] Results;
                string passphrase = "password";
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
                byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
                TDESAlgorithm.Key = TDESKey;
                TDESAlgorithm.Mode = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;
                byte[] DataToDecrypt = Convert.FromBase64String(Message);
                try
                {
                    ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                    Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
                }
                finally
                {
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }
                return UTF8.GetString(Results);
            }
            catch (Exception ex)
            {
                return "";
            }
        }

 

LINQ Standard Deviation

double[] dAverage = new double[8];
double[] dStandardDeviation = new double[8];

 Call:

-> dStandardDeviation[0] = CalculateStdDev(d1.AsEnumerable(), dAverage[0]);

private double CalculateStdDev(IEnumerable<double> values, double avg)
        {
            double ret = 0;

            if (values.Count() > 0)
            {
                //Compute the Average
                //double avg = values.Average();

                //Perform the Sum of (value-avg)^2
                double sum = values.Sum(d => Math.Pow(d - avg, 2));

                //Put it all together
                ret = Math.Sqrt((sum) / (values.Count() - 1));
            }
            return ret;
        }

 

 

Hiding url(.aspx)

Global.asax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;

namespace WebApplication1
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RegisterRoutes();
        }
        private static void RegisterRoutes()
        {
            System.Web.Routing.RouteTable.Routes.Add("Any Description1",
                new System.Web.Routing.Route("home", new
                                      PageRouteHandler("~/Default.aspx")));
            System.Web.Routing.RouteTable.Routes.Add("Any Description2",
               new System.Web.Routing.Route("About", new
                                     PageRouteHandler("~/About.aspx")));
        }
    }
}

 

iText

 public void ExportPDF()
        {
            var titleFont = FontFactory.GetFont("Arial", 14, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font fontWhite = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 11, iTextSharp.text.Color.WHITE);
            iTextSharp.text.Font fontSecRow = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 11);
            iTextSharp.text.Font fontThirdRow = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Document Doc = new iTextSharp.text.Document(PageSize.A3, 25f, 25f, 25f, 15f);

            string path = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UserKpiDocs"]) + Request.Cookies["proid"].Value;
            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            if (File.Exists(path + "StatusLog.pdf"))
            {
                File.Delete(path + "StatusLog.pdf");
            }
            var output = new FileStream(path + "/StatusLog.pdf", FileMode.Create);
            iTextSharp.text.pdf.PdfWriter.GetInstance(Doc, output);
            StringReader readerbg = new StringReader(lblActivity.Text + "<br/>");
            StringReader readercs = new StringReader(lblAction.Text + "<br/>");
            StringReader readerana = new StringReader(lblRisk.Text + "<br/>");
            StringReader readergoal = new StringReader(lblMg.Text + "<br/>");

            HTMLWorker parser = new HTMLWorker(Doc);


            Doc.Open();

            Paragraph pCompanyName = new Paragraph("StatusLog for " + lblCompanyName.Text, titleFont);
            Paragraph pActivitiesPerformedthisPeriod = new Paragraph("Activities Performed this Period ", fontThirdRow);
            Paragraph pActionsPlannedNextPeriod = new Paragraph("Actions Planned Next Period ", fontThirdRow);
            Paragraph pRisks = new Paragraph("Risks/Issues/Concerns ", fontThirdRow);
            Paragraph pMitigationActionsPlanned = new Paragraph("Mitigation Actions Planned", fontThirdRow);

            pCompanyName.SetAlignment("Center");
            pActivitiesPerformedthisPeriod.SetAlignment("left");
            pActionsPlannedNextPeriod.SetAlignment("left");
            pRisks.SetAlignment("left");
            pMitigationActionsPlanned.SetAlignment("left");

            Doc.Add(pCompanyName);
            Doc.Add(pActivitiesPerformedthisPeriod);
            parser.Parse(readerbg);
         
            Doc.Add(pActionsPlannedNextPeriod);
            parser.Parse(readercs);
            Doc.Add(pRisks);
            parser.Parse(readerana);
            Doc.Add(pMitigationActionsPlanned);
            parser.Parse(readergoal);

            Doc.Close();
            output.Close();
        }

ASP.Net URL re-writing in VS 2010

Start

http://localhost:22333/about

public class Global : System.Web.HttpApplication
{
        void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("Home", "Home", "~/Default.aspx");
            routes.MapPageRoute("About", "About", "~/About.aspx");
        }
        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

}

  <a href="Home" />Home</a>

<a href="About" />About</a>

End URL rewriting