Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Saturday, 10 May 2014

GET random Unique OTP(One Time Password) in C#.NET

Use this Code for random Unique OTP(One Time Password) generation:

private string generatePassword()
    {
        int lenthofpass = 6;
        string allowedChars = "";
        allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
        allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
        allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
        char[] sep = { ',' };
        string[] arr = allowedChars.Split(sep);
        string passwordString = "";
        string temp = "";
        Random rand = new Random();
        for (int i = 0; i < lenthofpass; i++)
        {
            temp = arr[rand.Next(0, arr.Length)];
            passwordString += temp;
        }
        return passwordString;
    }

Tuesday, 29 April 2014

Send Mail with Attachment in asp.net

 MailAddress SendFrom = new MailAddress("brijesh.singh879@gmail.com", "Brijesh");
        MailAddress SendTo = new MailAddress("brijesh.singh879@gmail.com");
        System.Net.Mail.MailMessage MyMessage = new System.Net.Mail.MailMessage(SendFrom, SendTo);
        MyMessage.IsBodyHtml = true;
        MyMessage.Subject = "Send Mail with attachment ";
        MyMessage.Body = "Body";
        if (fupResume.HasFile)
        {
            string FileName = Path.GetFileName(fupResume.PostedFile.FileName);
            MyMessage.Attachments.Add(new Attachment(fupResume.PostedFile.InputStream, FileName));
        }
        System.Net.NetworkCredential authentication = new System.Net.NetworkCredential("brijesh.singh879@gmail.com", "password");
        SmtpClient client = new SmtpClient("smtp.gmail.com", 25);//587
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = authentication;
        client.Send(MyMessage);

Tuesday, 8 April 2014

Directly Bind Byte[] Type Image data to Image control asp.net

Use this code for display image on both asp Image control and html img tag

<asp:Image ImageUrl='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("IMG_DATA")) %>' />

            OR 

<img src='<%# "data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("IMG_DATA")) %>' />

Friday, 4 April 2014

Re-sized Image of byte[] array type in asp.net

I found the solutions of image re-sizing at run-time in asp.net 
use this code to obtain re-sized image:

SqlCommand cmd = new SqlCommand("select ProductPicture from ProductDetails where Id=" + pdctid + "", con);
                byte[] product = (byte[])cmd.ExecuteScalar();
                MemoryStream stream = new MemoryStream(product);
                Response.BinaryWrite(ResizeUploadedImage(stream));


private byte[] ResizeUploadedImage(Stream streamToResize)
        {
            byte[] resizedImage;
            using (System.Drawing.Image orginalImage = System.Drawing.Image.FromStream(streamToResize))
            {
                ImageFormat orginalImageFormat = orginalImage.RawFormat;
                int orginalImageWidth = orginalImage.Width;
                int orginalImageHeight = orginalImage.Height;
                int resizedImageWidth = 150; // Type here the width you want
                int resizedImageHeight = 90; // Type here the hight you want
                using (Bitmap bitmapResized = new Bitmap(orginalImage, resizedImageWidth, resizedImageHeight))
                {
                    using (MemoryStream streamResized = new MemoryStream())
                    {
                        bitmapResized.Save(streamResized, orginalImageFormat);
                        resizedImage = streamResized.ToArray();
                    }
                }
            }

            return resizedImage;
        }

Tuesday, 1 April 2014

Export GridView Data with Image in C#.net

Write this code on .aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Job" HeaderText="Job" />
                <asp:BoundField DataField="Location" HeaderText="Location" />
                <asp:ImageField DataImageUrlField="Image" HeaderText="Image">
                </asp:ImageField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" Text="Export" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>





copy & paste this code on .cs page....

protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            FillGridview();
        }
    }

    private void FillGridview()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name", typeof(string));
        table.Columns.Add("Job", typeof(string));
        table.Columns.Add("Location", typeof(string));
        table.Columns.Add("Image");

        table.Rows.Add("JP", "XXX", "QQQQ", "http://localhost:10735/WebSite2/image/sub-menu-corner.png");
        table.Rows.Add("HP", "TTT", "AAAA", "http://localhost:10735/WebSite2/image/sub-menu-corner-2.png");
        table.Rows.Add("SQ", "YYY", "HHHH", "http://localhost:10735/WebSite2/image/section1-bg.jpg");
        table.Rows.Add("XS", "EEE", "UUUU", "http://localhost:10735/WebSite2/image/form-bg.png");
        GridView1.DataSource = table;
        ViewState["dt"] = table;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        DataTable dt = (DataTable)ViewState["dt"];
        GridView1.DataSource = dt;
        GridView1.DataBind();

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {

    }


Result:


Thursday, 13 February 2014

PRevent Re-submission of Data on Browser reload in C#.NET

On .aspx page write take a hidden field:

<asp:HiddenField id="hdncheckreload" runat="server" />


On .cs page write a function to check whether it's first time call event or reloaded......

public bool notIsRefresh()
        {
            bool retVal = false;
            if (Session["match"] == null || Session["match"].ToString() == hdncheckreload.Value)
                retVal = true;
            Session["match"] = DateTime.Now.Ticks;
            hdncheckreload.Value = Session["match"].ToString();
            return retVal;
        }

call this method on event which is reloaded such as button click event, form submission etc...

Wednesday, 22 January 2014

HOw to implement LINQ in C#.NET to Perform Aggregate Function as in SQL Server

First Add the namespace - System.Collections.Generic and System.Linq

Now we get data into datatable : 

DataTable dtt = new DataTable();
string _cquery = "Select * from table1";
dtt = du.getdatatable(_cquery);

Now apply group by clause on datatable dtt using LINQ :

var query = from row in dtt.AsEnumerable()
                                group row by row.Field<string>("col1") into grp
                                select new { AfterDistinct = grp.Key};
                    DataTable ddldt = new DataTable();
                    ddldt.Columns.Add("col1");
                    foreach (var row in query)
                    {
                        int i = 0;
                        DataRow dr = ddldt.NewRow();
                        dr["col1"] = row.AfterDistinct.ToString();
                        ddldt.Rows.Add(dr);
                        i++;
                    }
                    ddl1.Items.Clear();
                    ddl1.DataSource = ddldt;
                    ddl1.DataTextField = "col1";
                    ddl1.DataValueField = "col1";
                    ddl1.DataBind();
                    ddl1.Items.Insert(0, new ListItem("--Select--", "0"));


in this example we get data with group by clause from DataTable and bind this data to DropdownList ddl1.

Monday, 30 December 2013

GridView Insert,Update,Edit and Delete in C#.net

On .aspx Page:

<asp:GridView ID="gvDetails"  runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"ImageUrl="~/Images/update.png" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"ImageUrl="~/Images/Cancel.png" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.png"ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server"ImageUrl="~/Images/delete.png" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg"CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User"ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*"ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
<asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*"ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation"Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>


 



After that on .cs File:


SqlConnection con = new SqlConnection("Data Source=BRIJESH-PC;Integrated Security=true;Initial Catalog=TEST");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}

Saturday, 7 December 2013

Export Selected GridViewRow to Excel on button click in C#.NET

Copy & Paste this on .aspx file:

<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" CellPadding="4"
                            BackColor="#5DA63A" ForeColor="White" Width="100%" AllowPaging="false" Style="border-radius: 10px;
                            border: Solid 3px #5DA63A; text-align: left; word-wrap: break-word; word-break: break-all">
                            <AlternatingRowStyle BackColor="#F1FCCA"></AlternatingRowStyle>
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" CssClass="grid_font" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#8EBE12" Font-Bold="False" ForeColor="#E7E7FF" />
                            <Columns>
                                <asp:TemplateField ItemStyle-Width="20px">
                                    <HeaderTemplate>
                                        <asp:CheckBox ID="chkAll" runat="server" AutoPostBack="True" 
                                            oncheckedchanged="chkAll_CheckedChanged" />
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="True" 
                                            oncheckedchanged="chkSelect_CheckedChanged" />
                                    </ItemTemplate>
                                    <ItemStyle Width="20px" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="EIEUID" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblid" runat="server" Text='<%#Eval("EIEUid")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="60px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblname" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="150px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Details" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblemail" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="160px" />
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Mobile" HeaderStyle-HorizontalAlign="Left">
                                        <ItemTemplate>
                                            <asp:Label ID="lblmobile" runat="server" Text='<%#Eval("Mobile")%>'></asp:Label>
                                        </ItemTemplate> 
                                        <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                                        <ItemStyle Width="120px" />
                                    </asp:TemplateField>
                            </Columns>
                        </asp:GridView>



Copy & Paste this on .cs Code File:

dataUtility du = new dataUtility();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindGridData();
        }

        /// This Method is used to bind gridview
        private void BindGridData()
        {
            try
            {
                DataTable dtnew = new DataTable();
                DataTable dt = new DataTable();
                dt = du.executeStoteProc("SP_CLIENT 5,'" + Session["Name"] + "','',''");
               
                    if (dt.Rows.Count > 0)
                    {
                        gvDetails.DataSource = dt;
                        gvDetails.DataBind();

                    }
                    else
                    {
                        dt.Rows.Add(dt.NewRow());
                        gvDetails.DataSource = dt;
                        gvDetails.DataBind();
                        int columncount = gvDetails.Rows[0].Cells.Count;
                        gvDetails.Rows[0].Cells.Clear();
                        gvDetails.Rows[0].Cells.Add(new TableCell());
                        gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
                        gvDetails.Rows[0].Cells[0].Text = "No Records Found";
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }

        /// enable gridview control to be rendered
        public override void VerifyRenderingInServerForm(Control control)
        {
            /*Verifies that the control is rendered */
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            ExportToExcell();
        }

        /// export gridview to excel
        private void ExportToExcell()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Details");
            dt.Columns.Add("Mobile");
            foreach (GridViewRow row in gvDetails.Rows)
            {
                CheckBox chkCalls = (CheckBox)row.FindControl("chkSelect");
                if (chkCalls.Checked == true)
                {
                    int i = row.RowIndex;
                    Label lblname = (Label)gvDetails.Rows[i].FindControl("lblname");
                    Label lblemail = (Label)gvDetails.Rows[i].FindControl("lblemail");
                    Label lblmobile = (Label)gvDetails.Rows[i].FindControl("lblmobile");

                    DataRow dr = dt.NewRow();
                    dr["Name"] = Convert.ToString(lblname.Text);
                    dr["Details"] = Convert.ToString(lblemail.Text);
                    dr["Mobile"] = Convert.ToString(lblmobile.Text);
                    dt.Rows.Add(dr);
                }
            }
            GridView gdvExportxls = new GridView();
            gdvExportxls.DataSource = dt;
            gdvExportxls.DataBind();
            gdvExportxls.HeaderStyle.Font.Bold = true;
            gdvExportxls.HeaderStyle.ForeColor = Color.White;
            gdvExportxls.HeaderStyle.BackColor = Color.Green;
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("content-disposition", string.Format("attachment;filename=ReferrerDetails.xls", "selectedrows"));
            Response.Charset = "";
            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
            gdvExportxls.RenderControl(htmlwriter);
            Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
            Response.End();

        }

        /// select/unselect all row using header checkbox
        protected void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox chkH = (CheckBox)gvDetails.HeaderRow.FindControl("chkAll");
                if (chkH.Checked == true)
                {
                    foreach (GridViewRow gv in gvDetails.Rows)
                    {
                        CheckBox chk = (CheckBox)gv.FindControl("chkSelect");
                        chk.Checked = true;
                    }
                }
                else
                {
                    foreach (GridViewRow gv in gvDetails.Rows)
                    {
                        CheckBox chk = (CheckBox)gv.FindControl("chkSelect");
                        chk.Checked = false;
                    }

                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        /// select/unselect single row using row checkbox
        protected void chkSelect_CheckedChanged(object sender, EventArgs e)
        {
            bool isFound = false;
            CheckBox cbxall = (CheckBox)gvDetails.HeaderRow.FindControl("chkAll");
            foreach (GridViewRow gvr in gvDetails.Rows)
            {
                CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
                if (chkSelect.Checked == false)
                {
                    isFound = true;
                    break;
                }

            }

            if (isFound)
                cbxall.Checked = false;
            else
                cbxall.Checked = true;

        }

Thursday, 5 December 2013

SOLVED: Session Lost problem after Response.Redirect when redirect from Iframe

Copy & Paste this to head tag:

<script type="text/javascript" language="javascript">
      
        //for Redirect Iframe
        function Redirect() 
        {
            top.location = "Checkout.aspx";
            return false;
        }

</script>


Copy & Paste this code on .cs file:

ScriptManager.RegisterStartupScript(Page, typeof(System.Web.UI.Page),
                                                    "blur", @"<script type='text/javascript'>Redirect();</script>", false);

Note: bool value set true if you don't use UpdatePanel......

Monday, 2 December 2013

HOw to Add break-point when Debug Window Service in C#.net

Service1.cs file code:

Timer timer;
        public Service1()
        {
            InitializeComponent();
        }

        public void OnDebug()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            // get today's date at 00:01 AM  
            DateTime time = DateTime.Today.AddMinutes(1);

            // if 00:01 AM has passed, get tomorrow at 00:01 AM  
            if (DateTime.Now > time)
                time = time.AddDays(1);

            // calculate milliseconds until the next 00:01 AM.  
            int timeToFirstExecution = (int)time.Subtract(DateTime.Now).TotalMilliseconds;

            // calculate the number of milliseconds in 24 hours.   
            int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;

            // set the method to execute when the timer executes.   
            TimerCallback methodToExecute = Brijeshmethod;

            // start the timer.  The timer will execute "Brijeshmethod" when the number of seconds between now and   
            // the next 00:01 AM elapse.  After that, it will execute every 24 hours.   
            timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls);
  
        }

        private void Brijeshmethod(object source)
        {
            //write your code here
        }

        protected override void OnStop()
        {
            Thread.Sleep(Timeout.Infinite);

        }



Program file:

/// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            #if DEBUG
            Service1 myService = new Service1();
            myService.OnDebug();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            #else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
            #endif


        }

Friday, 29 November 2013

HOw to Clear Cache,Cookies and History of All Browser in C#.net on Button Click

Use this code on your button click event:

protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            Session["AEmail"] = null;
            Session.Clear();
            ClearCache();
            clearchachelocalall();
            Response.Redirect("../Default.aspx");

        }
        public static void ClearCache()
        {
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetExpires(DateTime.Now);
            HttpContext.Current.Response.Cache.SetNoServerCaching();
            HttpContext.Current.Response.Cache.SetNoStore();
            HttpContext.Current.Response.Cookies.Clear();
            HttpContext.Current.Request.Cookies.Clear();
        }

        private void clearchachelocalall()
        {
            string GooglePath = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Google\Chrome\User Data\Default\";
            string MozilaPath = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Roaming\Mozilla\Firefox\";
            string Opera1 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Opera\Opera";
            string Opera2 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Roaming\Opera\Opera";
            string Safari1 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Apple Computer\Safari";
            string Safari2 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Roaming\Apple Computer\Safari";
            string IE1 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Microsoft\Intern~1";
            string IE2 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Microsoft\Windows\History";
            string IE3 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Local\Microsoft\Windows\Tempor~1";
            string IE4 = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Roaming\Microsoft\Windows\Cookies";
            string Flash = Environment.GetEnvironmentVariable("USERPROFILE") + @"\AppData\Roaming\Macromedia\Flashp~1";

            //Call This Method ClearAllSettings and Pass String Array Param
            ClearAllSettings(new string[] { GooglePath, MozilaPath, Opera1, Opera2, Safari1, Safari2, IE1, IE2, IE3, IE4, Flash });
           
        }

        public void ClearAllSettings(string[] ClearPath)
        {
            foreach (string HistoryPath in ClearPath)
            {
                if (Directory.Exists(HistoryPath))
                {
                    DoDelete(new DirectoryInfo(HistoryPath));
                }

            }
        }

        void DoDelete(DirectoryInfo folder)
        {
            try
            {

                foreach (FileInfo file in folder.GetFiles())
                {
                    try
                    {
                        file.Delete();
                    }
                    catch
                    { }

                }
                foreach (DirectoryInfo subfolder in folder.GetDirectories())
                {
                    DoDelete(subfolder);
                }
            }
            catch
            {
            }
        }