Wednesday, 20 November 2013

Send Email using WCF Service in C#.net



Hi Friends,

In this article I will tell you how to send email using WCF Service. We can send email directly from the client; however, in some cases you can't send external emails directly. In that case we need WCF service for sending email from client.
In this article, I will first explain how to create WCF service then I will try to implement email functionality using WCF Service. In this article I am using Gmail to send email., that why user must have gmail account for sending email.

1.    Create WCF Service Class Library

Create a new Project WCF Class Library Project and Name it EmailServices. 





Step 1: Create service contract as IEmailService and add OperationContract SendEmail for sending email. This method uses gmailuseraddress ,password and email to and cc subject as parameter


[ServiceContract]
    public interface IEmailService
    {
        [OperationContract]
        string SendEmail(string gmailUserAddress, string gmailUserPassword, string[] emailTo,string[] ccTo, string subject, string body, bool isBodyHtml);
             
    }

Step 2: Add EmailService class and Implement IEmailService. 


public class EmailService : IEmailService
    {
        private static string SMTPSERVER = "smtp.gmail.com";
        private static int PORTNO = 587;

        public string SendEmail(string gmailUserName, string gmailUserPassword, string[] emailToAddress, string[] ccemailTo, string subject, string body, bool isBodyHtml)
        {           
            if (gmailUserName == null || gmailUserName.Trim().Length == 0)
            {
                return "User Name Empty";
            }
            if (gmailUserPassword == null || gmailUserPassword.Trim().Length == 0)
            {
                return "Email Password Empty";
            }
            if (emailToAddress == null || emailToAddress.Length == 0)
            {
                return "Email To Address Empty";
            }

            List<string> tempFiles = new List<string>();

            SmtpClient smtpClient = new SmtpClient(SMTPSERVER, PORTNO);
            smtpClient.EnableSsl = true;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(gmailUserName, gmailUserPassword);
            using (MailMessage message = new MailMessage())
           
            {
                message.From = new MailAddress(gmailUserName);
                message.Subject = subject == null ? "" : subject;
                message.Body = body == null ? "" : body;
                message.IsBodyHtml = isBodyHtml;

                foreach (string email in emailToAddress)
                {                  
                    message.To.Add(email);
                }
                if (ccemailTo != null && ccemailTo.Length > 0)
                {
                    foreach (string emailCc in ccemailTo)
                    {                      
                        message.CC.Add(emailCc);
                    }
                }
                try
                {
                    smtpClient.Send(message);                
                    return "Email Send SuccessFully";
                }
                catch
                {                 
                    return "Email Send failed";
                }
            }



        }
    }


Step 3: Build your Class library.


2.    Add WCF Service Application Project

 
Step 1: Add reference of Classlibrary Project to that WCFServiceHost project.
Step 2: Delete IService1.Cs and codebehind file
Step3 : Right click on that SaleService.svc and select view Markup:


Step 4: Change the Service Name from that markup:
<%@ ServiceHost Language="C#" Debug="true" Service="EmailServices.EmailService" CodeBehind="EmailService.svc.cs" %>

Step 5: And build the solution and WCFServiceHost set as startup project and EmailService.svc set as startup page and run the service


 



3. Testing Email Service

1.       Use WCFSTORM for testing WCF Service . You can download WCFSTORM from http://www.wcfstorm.com/wcf/home.aspx
2.       Open WCF Strom add following endpoint http://localhost:53818/EmailService.svc?wsdl



By using this, we have successfully send email using WCF Service









Please find attached source code Download Here




Happy Programming!!

If you have any query mail me to Sujeet.bhujbal@gmail.com     


Regards

Sujeet Bhujbal

------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------



Sunday, 27 October 2013

How to create a Zip file with the .NET 4.5

Hi friends,

In this article i will tell you how to create a Zip file with .Net 4.5


In .Net  4.5 , there is new Namespace has been added System.IO.Compression namespace. Now, in a very simple manner, we can perform zip and unzip actions.I will demonstrate how to perform  zip file in C# you can use the following code:





public void CreateZipFile()
{
    string zipPath = @"C:\Test.zip";
    string entryName = "Readme.txt";
    string content = "Hello world!";
    using (var zipToOpen = new System.IO.FileStream(zipPath, System.IO.FileMode.CreateNew))
    {
        using (var archive = new System.IO.Compression.ZipArchive(zipToOpen, System.IO.Compression.ZipArchiveMode.Create))
        {
            System.IO.Compression.ZipArchiveEntry readmeEntry = archive.CreateEntry(entryName);
            using (var writer = new System.IO.StreamWriter(readmeEntry.Open()))
            {
                writer.Write(content);
            }
        }
    }
}






The System.IO.Compression namespace in .NET 4.5 provides us with an easy way to work with zip files. We can create archives, update archives, and extract archives.


I hope you found this article helpful. As always, I appreciate your feedback.


Happy Programming!! 


 If you have any query mail me to Sujeet.bhujbal@gmail.com


 Regards

 Sujeet Bhujbal  


-------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------


Friday, 11 October 2013

Passing Values from One Page to Another Page – ASP.NET


Hi Friends,

In this article I will tell you how to pass values from one page to another page in asp.net
Passing parameters from one page to another is a very common task in Web development. It is very importance and frequency used with ASP.NET
There are still many situations in which you need to pass data from one Web page to another.
There are three widely used methods of passing values from one page to another in ASP.NET
Main

1. Using Query String


We usually pass value through query string of the page and then this value is pulled from Request object in another page.
FirstForm.aspx.cs
—————–
Response.Redirect(“SecondForm.aspx?Parameter=” + TextBox1.Text);

SecondForm.aspx.cs
——————
TextBox1.Text = Request. QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters.More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
—————
Response.Redirect(“SecondForm.aspx?Parameter=” + Server.UrlEncode(TextBox1.Text));

SecondForm.aspx.cs
—————–
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());


2. Passing value through context object


Passing value through context object is another widely used method.
FirstForm.aspx.cs
—————
TextBox1.Text = this.Context.Items["Parameter"].ToString();

SecondForm.aspx.cs
——————
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer(“SecondForm.aspx”, true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.


3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
—————
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add(“onclick”, “return PostPage();”);
}

And we create a javascript function to post the form.
SecondForm.aspx.cs
—————–

function PostPage()
{
document.Form1.action = “SecondForm.aspx”;
document.Form1.method = “POST”;
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false


4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
————–
<asp:Button id=buttonPassValue style=”Z-INDEX: 102
runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
—————–
TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
—————
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1
);
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.
Conclusion Passing values between pages is another common task mostly used in web based development.

As we have discussed many of mechanisms above, I prefer and recommend to use Query String then other
methods for its clean and simple implementation as long as your parameter doesnt have security concern.


Happy Programming!!

If you have any query mail me to Sujeet.bhujbal@gmail.com    


Regards

Sujeet Bhujbal

------------------------------------------------------------------------------------------------------------
Twitter :- http://twitter.com/SujeetBhujbal

--------------------------------------------------------------------------------------------------------