Thursday, 5 December 2013

How To Transfer Values From One Page To Another Through Query String in Asp.NET

How To Transfer Values From One Page To Another Through Query String in Asp.NET 


Hi Friends,
          In this post i have shown how to transfer values from one page to another through Query String.


Step 1: Create a New Web Form Page1.aspx . Then paste the below code:-



<asp:Label runat="server" ID="lbl" >Text To Transfer to next Page :</asp:Label><asp:TextBox runat="server" ID="txttrans"></asp:TextBox>
    <br />
    <asp:Button runat="server" ID="btnnext" Text="Transfer To Next Page" onclick="btnnext_Click" />



Step 2: Create a New Web Form Page2.aspx . Then paste the below code:-

 <asp:Label runat="server" ID="lbl" >Text Transfered from Previos Page :</asp:Label><asp:TextBox runat="server" ID="txttransfered"></asp:TextBox>


Step 3: Now open Page2.aspx.cs and paste the below code in Page_Load

if (Request.QueryString.Count > 0)
            {
                txttransfered.Text = Request.QueryString["Text"].ToString();
            }


Step 4: Now open Page1.aspx.cs and paste the below code below Page_Load



 protected void btnnext_Click(object sender, EventArgs e)
        {
            string trans = txttrans.Text.Trim();

            Response.Redirect("~/TransferValues/Page2.aspx?Text="+trans);
            // Your second page url where you want to transfer the values
        }


Snaps:-


Now Click Transfer To Next Page



Your Text is transferred. You can see it in Url.


Please leave your feedback and comments below..!


Wednesday, 4 December 2013

How to Send Email with WCF Service in Asp.NET

How to Send Email with WCF Service in Asp.NET

Hi Friends,
            In this post I will tell you Step by Step Process how to send email using WCF Service. I will first explain how to create WCF service then I will try to implement email functionality using WCF Service. Here i am using Gmail to send email., that why user must have gmail account for sending email.


Step:1 Create a new ASP.Net Web Application.
Step:2 Now right click on solution and add new Project.






Step:3 Now form installed templates select WCF then Select wcf service application and name it Email. 






Now you should have two projects in your solution.






Step:4 Now from Email project open IService1.cs add the below namespace

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net.Mail;


Now Delete the below code:-



and this




Now paste the below code:-

[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string Email(SendEmail objemail);

    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    
    [DataContract]
    public class SendEmail
    {
        string from, to, cc, bcc, subject, body, filename,path;

        //Stream attachment;

        [DataMember]
        public string From
        {
            get { return from; }
            set { from = value; }
        }

        [DataMember]
        public string To
        {
            get { return to; }
            set { to = value; }
        }

        [DataMember]
        public string Cc
        {
            get { return cc; }
            set { cc = value; }
        }

        [DataMember]
        public string Bcc
        {
            get { return bcc; }
            set { bcc = value; }
        }

        [DataMember]
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        [DataMember]
        public string Body
        {
            get { return body; }
            set { body = value; }
        }
    }

Now your Page should look like this:-





Step:5 Now open Service1.svc.cs and add below namespace

using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


Now Delete the below code :-




Now paste the below code:- 

public string Email(SendEmail objemail)
        {
            string fromEmail = "Your Gmail Id";
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(fromEmail, "Your Name");
            mail.Subject = objemail.Subject;
            mail.Body = objemail.Body;

           
            mail.To.Add(objemail.To);
            if (objemail.Cc.ToString() != null && objemail.Cc.ToString() != "")
            {
                mail.CC.Add(objemail.Cc);
            }
            if (objemail.Bcc.ToString() != null && objemail.Bcc.ToString() != "")
            {
                mail.Bcc.Add(objemail.Bcc);
            }

            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.UseDefaultCredentials = false;
            smtpClient.EnableSsl = Convert.ToBoolean(true);
            smtpClient.Credentials = new NetworkCredential("Your Gmail Id", "Your Password");
            try
            {
                smtpClient.Send(mail);
                return "Email Send";
            }
            catch
            {
                return "Failed To Send Email";
            }

        }



Note:- Please don't forget to enter your gmail id and password . 

Now Your Page should look like this:-





Step:6 Now Press F6 To build your project.

Then Right Click on Service1.svc and view in browser:-




Now from browser copy the url.




Step:7 Now add service reference in your web application project. In my case my project name is WCFExample. Right Click Reference and Click on Add Service Reference.




Now a popup box will appear. In Address paste the copied url then press Go.
Now in Namespace write EmailService then press OK.


  


Step:8 Now create a new web form using master page and name it Email.aspx

Now Paste below code in main content of Email.aspx page:-

     <div class="entry-content">
        <h2>
            Email</h2>
        <asp:Label runat="server" ID="lblTo">To</asp:Label>
        <asp:TextBox ID="txt_to" runat="server" CssClass="TextBox" AutoComplete="off" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVto" runat="server" ControlToValidate="txt_to"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Please enter email Id."
            ToolTip="Please enter email Id" ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="REVto" ValidationGroup="sbmitbtn" runat="server"
            Display="Dynamic" SetFocusOnError="true" ToolTip="Email Id invalid." ErrorMessage="Email Id invalid."
            ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_to"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label runat="server" ID="lblCC">Cc</asp:Label>
        <asp:TextBox ID="txt_cc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVcc" ValidationGroup="sbmitbtn" Display="Dynamic"
            SetFocusOnError="true" runat="server" ToolTip="Please check email id/id's are wrong."
            ErrorMessage="Please check email id/id's are wrong" ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_cc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label runat="server" ID="lblBcc">Bcc</asp:Label>
        <asp:TextBox ID="txt_bcc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVBcc" ValidationGroup="sbmitbtn" Display="Dynamic"
            SetFocusOnError="true" runat="server" ToolTip="Please check email id/id's are wrong."
            ErrorMessage="Please check email id/id's are wrong" ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_bcc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label ID="Label2" class="Label" runat="server">Subject</asp:Label>
        <br />
        <asp:TextBox ID="txt_subject" runat="server" AutoComplete="off" CssClass="TextBox"
            MaxLength="50" Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVsubject" runat="server" ControlToValidate="txt_subject"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Subject is required."
            ToolTip="Subject is required." ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <br />
        <br />
        <label class="Label">
            <asp:Literal ID="Literal1" runat="server" Text="Message"></asp:Literal>
        </label>
        <br />
        <asp:TextBox ID="txt_msgbody" runat="server" TextMode="MultiLine" CssClass="multiline"
            Style="height: 180px; width: 570px; resize: none;" ValidationGroup="sbmitbtn"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVmsg" runat="server" ToolTip="Please write in message body."
            CssClass="failureNotification" ErrorMessage="Please write in message body." ControlToValidate="txt_msgbody"
            ValidationGroup="sbmitbtn" ForeColor="Red"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="btn_email" CssClass="Button" runat="server" Text="Send" ValidationGroup="sbmitbtn"
            OnClick="btn_email_Click" />
        <br />
        <asp:Label ID="lblemailmsg" runat="server"></asp:Label>
        <asp:HiddenField runat="server" ID="hf_msz" />
    </div>

Now your page should be like:-


Step:9 Now open Email.aspx.cs and add below namespace

using System.IO;
using System.Net.Mail;
using System.Net;
using WCFExample.EmailService; // In my case reference is added in my web appplication project WCFExample

Now Paste the below code above Page_Load:-

EmailService.Service1Client objemail = new EmailService.Service1Client();

Now add below code below Page_Load:-

protected void btn_email_Click(object sender, EventArgs e)
        {
            SendEmail seobj = new SendEmail();

            seobj.To = txt_to.Text.Trim();
            seobj.Cc = txt_cc.Text.Trim();
            seobj.Bcc = txt_bcc.Text.Trim();
            seobj.Subject = txt_subject.Text.Trim();
            seobj.Body = txt_msgbody.Text.Trim();
            
            string result = objemail.Email(seobj);
            lblemailmsg.Text = result;



        }

Now press F6 to build project. Then Press F5 to run the project.

Finally Your page will be like this:-



Enter email-id,subject,message and Press Send Button to send email.
When Email is send you will get message "Email Send" below Send Button.


Please leave your feedback and comments below..!









Tuesday, 3 December 2013

How to show list of files from folder in GridView in Asp.Net

How to show list of files from folder in GridView in Asp.Net

Aspx Page:-



 <div>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">

        <Columns>
            <asp:BoundField DataField="Text" HeaderText="File Name" />
            <asp:TemplateField>
         </Columns>
    </asp:GridView>
    </div>

CS Page:-


Name Space Used:-


using System;

using System.Collections.Generic;

using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

Code:-

 protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {
                string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/")); 
// Here Files is the name of my folder where files are stored
                List<ListItem> files = new List<ListItem>();
                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
                GridView1.DataSource = files;
                GridView1.DataBind();
            }
        }



Don't forget to leave your feedback and comments below..!

How to download files from a folder in Asp.Net

How to download files from a folder in Asp.Net

Aspx Page:-



 <div>

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
         </Columns>
    </asp:GridView>
    </div>

CS Page:-


Name Space Used:-


using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

Code to List files in folder:-


 protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)
            {
                string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/")); 
// Here Files is the name of my folder where files are stored
                List<ListItem> files = new List<ListItem>();
                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
                GridView1.DataSource = files;
                GridView1.DataBind();
            }
        }

Code To Download Files:-


 protected void DownloadFile(object sender, EventArgs e)
        {
            string filePath = (sender as LinkButton).CommandArgument;
            Response.ContentType = ContentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
            Response.WriteFile(filePath);
            Response.End();
        }




Don't forget to leave your feedback and comments below..!

How to delete files from a folder in Asp.Net

How to delete files from a folder in Asp.Net

Aspx Page:-



 <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="File Name" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
                </ItemTemplate>
            </asp:TemplateField>
         </Columns>
    </asp:GridView>
    </div>

CS Page:-


Name Space Used:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

Code to List files in folder:-


 protected void Page_Load(object sender, EventArgs e)

        {
            if (!IsPostBack)
            {
                string[] filePaths = Directory.GetFiles(Server.MapPath("~/Files/")); 
// Here Files is the name of my folder where files are stored
                List<ListItem> files = new List<ListItem>();
                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
                GridView1.DataSource = files;
                GridView1.DataBind();
            }
        }

Code To Delete Files:-


protected void DeleteFile(object sender, EventArgs e)
        {
            string filePath = (sender as LinkButton).CommandArgument;
            File.Delete(filePath);
            Response.Redirect(Request.Url.AbsoluteUri);
        }




Don't forget to leave your feedback and comments below..!