Thursday, 26 September 2013

How Auto poastbak in ie 10 Enternet exploer 10 in .net

private void Page_Init(object sender, EventArgs e)
    {
        Page.ClientTarget = "uplevel";
    }

Wednesday, 25 September 2013

Url Rewite

protected void Application_BeginRequest(Object sender, EventArgs e)
    {

 if (HttpContext.Current.Request.QueryString["isValid"] == null)
                {
                    if (HttpContext.Current.Request.UrlReferrer == null && HttpContext.Current.Request.QueryString.Count > 0 && !(HttpContext.Current.Request.Url.ToString().ToLower().Contains("fundpage.aspx")))
                    {
                        if (!HttpContext.Current.Request.Url.ToString().Contains("?2") && !HttpContext.Current.Request.Url.ToString().ToLower().Contains("?formcentre"))
                        {
                            Response.Redirect("~/errorpage.aspx");
                        }

                    }
                    else
                    {
                        // BusinessLogic.URLRewriter.ProcessRequest();
                        URLRewriterNew.URLRewriterNew.ProcessRequest();
                        URLTagRewriter.ProcessRequest();
                    }
                }
                else if (HttpContext.Current.Request.UrlReferrer == null)
                {
                    //Response.Redirect("~/default.aspx");
                }
}


=========================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using System.Data;

using System.Xml;

public class URLTagRewriter : IConfigurationSectionHandler
{

    #region Private Variables
    // static AccessData _accessData = new AccessData();
    #endregion
    public static void ProcessRequest()
    {

        //string zSubst = oRewriter.GetSubstitution(HttpContext.Current.Request.Path);

        //Added by Deepak T to check the keyword

        if (HttpContext.Current.Request.Path.ToLower().Contains("aspx"))
        {
            //do nothing
            string zSubst = string.Empty;
            if (HttpContext.Current.Request.Url.AbsoluteUri.ToString().ToLower().Contains("?ptagid="))
            {
                string strPid = HttpContext.Current.Request.QueryString["ptagid"].ToString();
                int id = int.Parse(strPid);
                zSubst = ReadURLFromSql(id.ToString());
                if (zSubst.Length > 0)
                {
                    if (HttpContext.Current.Request.RequestType != "POST")
                    {
                        HttpContext.Current.Response.Redirect(zSubst);
                        //HttpContext.Current.RewritePath(zSubst);
                    }
                }

            }
            else
            {
                //HttpContext.Current.Response.Redirect("~/default.aspx");
            }

        }
        else if (HttpContext.Current.Request.Path.ToLower().Contains("."))
        {
            //do nothing
        }
        else
        {
            string zSubst = string.Empty;
            string strPid ="";
            zSubst = ReadURLFromSql();//ReadXML(HttpContext.Current.Server.MapPath("~/URL.xml"));

            if (zSubst.Length > 0)
            {
                HttpContext.Current.RewritePath(zSubst);
            }
            else
            {
                //HttpContext.Current.Response.Redirect("~/default.aspx");
                // throw new Exception("Page not found");
            }
        }
    }

    public static string ReadURLFromSql()
    {
        string strRequestPath = string.Empty;
        string dbPath = string.Empty;
        string strMatchPath = string.Empty;
        strRequestPath = HttpContext.Current.Request.Path; // got the requested path
        strMatchPath = strRequestPath.Substring(strRequestPath.LastIndexOf("/"), strRequestPath.Length - (strRequestPath.LastIndexOf("/")));
        if (strMatchPath.Contains("/"))
        {
            strMatchPath = strMatchPath.Remove(strMatchPath.IndexOf("/"), 1);
        }

        if (strMatchPath.Contains("'"))
        {
            int index = strMatchPath.IndexOf("'");
            index = index + 1;
            strMatchPath = strMatchPath.Insert(index, "'");
        }
        else
        {
            // strMatchPath = "7";
        }


        DataSet dsURL = new DataSet();


        //dsURL = GetFundPageLink("GetFundPageIDByLink","", strMatchPath);




        //if (dsURL != null && dsURL.Tables.Count > 0 && dsURL.Tables[0].Rows.Count > 0)
        //{
        //    dbPath = dsURL.Tables[0].Rows[0]["ID"].ToString();
      //  string strPid = HttpContext.Current.Request.QueryString["tagid"].ToString();
       //}
        //else
        //{
        //    dbPath = "";
        //}
  
        if (strMatchPath == "equity-funds")
        {
            dbPath = "1";
        }
        else if (strMatchPath == "debt-funds")
        {
            dbPath = "2";
        }
        else if (strMatchPath == "hybrid-funds")
        {
            dbPath = "3";
        }
        else if (strMatchPath == "tax-saving-funds")
        {
            dbPath = "7";
        }
        else if (strMatchPath == "long-term-funds")
        {
            dbPath = "18";
        } else
        {
            dbPath = "";
        }

        string str = string.Empty;
        if (dbPath != "")
            str = "~/mutual-funds-at-a-glance.aspx?tagID=" + dbPath + "";
        else
            str = "";

        return str;
    }

    public static string ReadURLFromSql(string fundID)
    {
        string strRequestPath = string.Empty;
        string dbPath = string.Empty;
        string strMatchPath = string.Empty;
        strRequestPath = HttpContext.Current.Request.Path; // got the requested path


        DataSet dsURL = new DataSet();

        //dsURL = GetFundPageLink("GetFundPageLink", fundID,"");

        if (fundID == "1")
        {
            dbPath = "equity-funds";
        }
        else if (fundID == "2")
        {
            dbPath = "debt-funds";
        }
        else if (fundID == "3")
        {
            dbPath = "hybrid-funds";
        }
        else if (fundID == "7")
        {
            dbPath = "tax-saving-funds";
        }
         else if (fundID == "18")
        {
            dbPath = "long-term-funds";
        }


        //if (dsURL!=null && dsURL.Tables.Count>0 &&  dsURL.Tables[0].Rows.Count > 0)
        //{
        //dbPath = "pramod";// dsURL.Tables[0].Rows[0]["FundPageLink"].ToString();
        // }

        string str = string.Empty;
        if (dbPath != "")
            str = "~/" + dbPath;
        else
            str = "";

        return str;
    }


    //public static DataSet GetFundPageLink(string strAction, string strFundID,string strFundLink)
    //{
    //    try
    //    {

    //        _accessData.Section = "FundPageLinks";
    //        object[] obj = _accessData.GetObject();
    //        obj[0] = strAction;
    //        obj[1] = strFundID;
    //        obj[2] = strFundLink;

    //        DataSet _ds = _accessData.getDataSet(obj);
    //        return _ds;
    //    }
    //    catch (Exception ex)
    //    {
    //        throw (ex);
    //    }
    //}



    #region Implementation of IConfigurationSectionHandler
    public object Create(object parent, object configContext, XmlNode section)
    {
        //_oRules = section;

        // TODO: Compile all Regular Expressions

        return this;
    }

    #endregion

}

Monday, 16 September 2013

More pageing in .net use ListView with DataPager

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div class="StatusMessage">
        <asp:ListView ID="lvEmployee" runat="server" OnDataBound="lvEmployee_DataBound">
            <LayoutTemplate>
                <table id="itemPlaceholderContainer">
                    <tr runat="server" id="itemPlaceholder">
                    </tr>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        Address:<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Id") %>' />
                    </td>
                </tr>
            </ItemTemplate>
        </asp:ListView>
        <div id="divpaging" runat="server">
            <asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvEmployee" PageSize="2"
                OnPreRender="DataPager1_PreRender">
                <Fields>
                   <%-- <asp:NumericPagerField ButtonCount="5" />--%>
                    <asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true"
                        ShowNextPageButton="true" ShowPreviousPageButton="true" />
                    <asp:TemplatePagerField OnPagerCommand="listPages_Click">
                        <PagerTemplate>
                            <asp:Button ID="listPages" runat="server" Text="more"></asp:Button>
                        </PagerTemplate>
                    </asp:TemplatePagerField>
                </Fields>
            </asp:DataPager>
        </div>
    </div>
    </form>
</body>
</html>

===============================cs pages===================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class listview_paging : System.Web.UI.Page
{

        int CurrentPage = 2;

        public int PageNumber
        {
            get
            {
                if (ViewState["PageNumber"] != null)
                    return Convert.ToInt32(ViewState["PageNumber"]);
                else
                    return 0;
            }
            set
            {
                ViewState["PageNumber"] = value;

            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                PageNumber = 1;
                ProductList db = new ProductList();
                lvEmployee.DataSource = db.GellAll();
                lvEmployee.DataBind();

            }

        }



        protected void lvEmployee_DataBound(object sender, EventArgs e)
        {


            //DropDownList ddl = DataPager1.Controls[1].FindControl("ddlPage") as DropDownList;

            int PageCount = (DataPager1.TotalRowCount / 2);

            if (PageCount * 2 != DataPager1.TotalRowCount)
            {

                PageCount = PageCount + 1;

            }

            //for (int i = 0; i < PageCount; i++)
            //{

            //    ddl.Items.Add(new ListItem((i + 1).ToString(), (1 + i).ToString()));

            //}

            // ddl.Items.FindByValue(CurrentPage.ToString()).Selected = true;

        }

        //protected void ddlPage_SelectedIndexChanged(object sender, EventArgs e)
        //{

        //    DropDownList ddl = sender as DropDownList;

        //    CurrentPage = int.Parse(ddl.SelectedValue);

        //    int PageSize = 2 * CurrentPage;

        //    DataPager1.SetPageProperties(0, PageSize, true);

        //}

        protected void DataPager1_PreRender(object sender, EventArgs e)
        {

            ProductList db = new ProductList();
            lvEmployee.DataSource = db.GellAll();
            lvEmployee.DataBind();

        }

        protected void listPages_Click(object sender, EventArgs e)
        {
            decimal PageCount = (decimal)((decimal)DataPager1.TotalRowCount / 2);

            if (PageNumber < PageCount)
            {
                PageNumber = PageNumber + 1;
                if (PageNumber >= PageCount)
                {
                    divpaging.Attributes["style"] = "display:none;";
                }
            }
            else
            {
                divpaging.Attributes["style"] = "display:none;";
            }

            int PageSize = 2 * PageNumber;//CurrentPage

            DataPager1.SetPageProperties(0, PageSize, true);
        }




        //protected void ProductListPager_PreRender(object sender, EventArgs e)
        //{
        //    ProductList db = new ProductList();
        //    ProductList.DataSource = db.GellAll();
        //    ProductList.DataBind();
        //}

    }

Tuesday, 10 September 2013

Dynamic create file and send in mail without save a file on server

StringBuilder messagebody1 = new StringBuilder();
            messagebody1.Append("Category,Product,First Name,Last Name,EmailId,Phone number,Location,PinCode,Message" + System.Environment.NewLine);
            messagebody1.Append(Category + "," + Product + "," + firstName + "," + lastName + "," + emailId + "," + phoneNumber + "," + location + "," + pincode + "," + queryText + System.Environment.NewLine);
            StringBuilder messagebody = new StringBuilder();
            messagebody.Append("Category:" + Category + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("Product:" + Product + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("First Name: " + firstName + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("Last Name: " + lastName + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("EmailId:" + emailId + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("Phone number:" + phoneNumber + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("Location:" + location + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("PinCode:" + pincode + System.Environment.NewLine + System.Environment.NewLine);
            messagebody.Append("Message:" + queryText + System.Environment.NewLine + System.Environment.NewLine);



            MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(messagebody1.ToString()));
            string to = "pramod.koli1@gmail.com";
            string from = ConfigurationManager.AppSettings["QueryEmail"].ToString();
            string subject = "Leave a query:" + category + "-" + product;
            string body = messagebody.ToString();
            SmtpClient SMTPServer = new SmtpClient("*********");
            MailMessage mailObj = new MailMessage(from, to, subject, body);
            mailObj.Attachments.Add(new Attachment(stream, "details.csv", "text/csv"));
           // mailObj.IsBodyHtml = true;
            SMTPServer.Send(mailObj);

Tuesday, 3 September 2013

Exception handle

using System;

class Program
{
    static void Main()
    {
 try
 {
     int value = 1 / int.Parse("0");
 }
 catch (Exception ex)
 {
     Console.WriteLine("HelpLink = {0}", ex.HelpLink);
     Console.WriteLine("Message = {0}", ex.Message);
     Console.WriteLine("Source = {0}", ex.Source);
     Console.WriteLine("StackTrace = {0}", ex.StackTrace);
     Console.WriteLine("TargetSite = {0}", ex.TargetSite);
 }
    }
}

Output
    (StackTrace was abbreviated for display.)

HelpLink =
Message = Attempted to divide by zero.
Source = ConsoleApplication1
StackTrace =    at Program.Main() in C:\...\Program.cs:line 9
TargetSite = Void Main()

HelpLink: This is empty because it was not defined on the exception. HelpLink is a string property.
Message: This is a short description of the exception's cause. Message is a read-only string property.
Source: This is the application name. Source is a string property that can be assigned to or read from.
StackTrace: This is the path through the compiled program's method hierarchy that the exception was generated from.
TargetSite: This is the name of the method where the error occurred. This property helps simplify what part of the errors are recorded.

Friday, 30 August 2013

Find value of Usercontrol of control in aspx page side

 -----------------------usercontrol-------------------------
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserControl1.ascx.cs" Inherits="Customvalidation_UserControl1" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

------------------------aspx pages------------------------

<form id="form1" runat="server">
    <div>
   
        <Test:TestControl ID="TestControl" runat="server" />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
------------------------aspx.cs side pages------------------------

 UserControl UC_text1 = (UserControl)Page.FindControl("TestControl");
        TextBox text1 = (TextBox)UC_text1.FindControl("TextBox1");
         TextBox text2 = (TextBox)UC_text1.FindControl("TextBox2");
        Response.Write(text1.Text+ "<br/>"+text2.Text);

Thursday, 29 August 2013

Rmove invalid data and tag from your database

DECLARE @T varchar(255),@C varchar(4000)
DECLARE Table_Cursor CURSOR FOR
 select a.name,b.name from sysobjects a,syscolumns b
 where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231
 or b.xtype=167)
 OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0)
 BEGIN
 exec('update ['+@T+'] set ['+@C+']=Replace('+@C+',''<script>'','''')')
 FETCH NEXT FROM
 Table_Cursor INTO @T,@C END CLOSE
 Table_Cursor DEALLOCATE Table_Cursor