Thursday, 12 April 2012

SEND AN EMAIL WITH ATTACHMENT USING C#

I have described an example to send an email using ASP.NET in C# and using GMAIL as a port.The Namespaces to be used are System.Net.Mail and System.IO. The code is written in the way that the attachment is stored in a folder temporarily before sending it and will be deleted afterwards.

  
 





In ASPX Page,

<table cellpadding="5" cellspacing="0" border="0">
  <tr>
    <td>To</td>
    <td>:</td>
    <td>
      <asp:TextBox ID="ToTextBox" runat="server" Width="400px"></asp:TextBox>
    </td>
  </tr>
  <tr>
    <td>Cc</td>
    <td>:</td>
    <td><asp:TextBox ID="CcTextBox" runat="server" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Subject</td>
    <td>:</td>
    <td><asp:TextBox ID="SubjectTextBox" runat="server" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Attachments</td>
    <td>:</td>
    <td>
    <asp:FileUpload ID="FileUpload" runat="server" Width="400px" />
    </td>
  </tr>
  <tr>
    <td valign="top">Message</td>
    <td valign="top">:</td>
    <td>
<asp:TextBox ID="MessageTextBox" runat="server" TextMode="MultiLine" Columns="20"   Rows="10" Width="400px"></asp:TextBox></td>
  </tr>
  <tr>
    <td colspan="4" align="right">
    <asp:Button ID="SendButton" runat="server" Text="Send"
     onclick="SendButton_Click" /></td>
  </tr>
</table>
<div>
    <asp:Label ID="StatusLabel" runat="server" Text="" ForeColor="Green" Font-Size="Large" Visible="false"></asp:Label>
</div>
                
In ASPX.CS Page,



    protected void SendButton_Click(object sender, EventArgs e)
    {
        this.StatusLabel.Visible = true;
        string FileName = string.Empty;
        MailMessage objMail = new MailMessage();
        objMail.From = new MailAddress("Your Mail Address");
        objMail.To.Add(new MailAddress(ToTextBox.Text.Trim()));
        if (CcTextBox.Text != string.Empty)
        {
            objMail.CC.Add(new MailAddress(CcTextBox.Text.Trim()));
        }
        objMail.Subject = SubjectTextBox.Text.Trim();
        objMail.Body = MessageTextBox.Text.Trim();
        objMail.IsBodyHtml = true;
        try
        {
            if (FileUpload.HasFile)
            {
                HttpPostedFile pf = this.FileUpload.PostedFile;
                // Filepath in which the file has to be stored
                FileName = Server.MapPath("~") + @"\uploads\" + FileUpload.FileName.Substring(FileUpload.FileName.LastIndexOf('\\') + 1);
                if (pf.ContentLength > 0)
                {
                    pf.SaveAs(FileName);
                    pf.InputStream.Flush();
                    pf.InputStream.Close(); // just in case any other process has the handle
                }
                pf.InputStream.Dispose();
                Attachment attach = new Attachment(FileName);
                objMail.Attachments.Add(attach);
            }
        SmtpClient client = new SmtpClient();
        client.Credentials = new System.Net.NetworkCredential("Mail Address", "Password");
        client.Port = 587; // Gmail works on this port
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true; //Gmail works on SSL
        client.Send(objMail);
       
        objMail.Dispose();
        client.Dispose();
        if (FileUpload.HasFile)
        {
            File.Delete(FileName);
        }
       
        }
        catch (SmtpFailedRecipientsException exp)
        {
            StatusLabel.Text = "Unable to send email to " + exp.FailedRecipient;
        }
        catch (SmtpFailedRecipientException exp)
        {
            StatusLabel.Text = "Unable to send email to " + exp.FailedRecipient + "<br />Error Message: " + exp.Message.Replace("'", "\'");
        }
        catch (SmtpException exp)
        {
            StatusLabel.Text = "There was a problem in sending the email to " + ToTextBox.Text.Trim() + "<br />" + exp.Message.Replace("'", "\'");
        }
        catch (Exception exp)
        {
            StatusLabel.Text = "There was an Unknown Problem in sending the email:<br />"
                            + exp.Message.Replace("'", "\'");
        }

        if (StatusLabel.Text == string.Empty)
        {
            StatusLabel.Text = "Mail sent successfully";
            ToTextBox.Text = string.Empty;
            CcTextBox.Text = string.Empty;
            SubjectTextBox.Text = string.Empty;
            MessageTextBox.Text = string.Empty;
        }
    }      














               
























(SQL SERVER)TO SCRIPT AN ENTIRE DATABASE ALONG WITH THE TABLE RECORDS


Steps to be followed to script an entire database
1.      Start the SQL Server Management Studio
2.      Select and Right Click the database you want to script
3.      Select Tasks > Generate Scripts… as seen in the below snapshot.

          
 4.
    
5.      Select the database 
6.      Choose the options you want to script. NOTE: if you want to script the tables along with the records, Under Table/View Options, set the Script Data to true.

          

                  7.      Choose the object types


                   

8.      Select the tables you want to script
                  9.      Choose the script mode and the destination where you want to store the file if you are scripting it to file.

           

10. Click on Finish to start scripting the database.

Wednesday, 4 April 2012

TO PASS THE STRING ALONG WITH THE DOUBLE QUOTES IN C#


To display a string enclosed within a double quotes, we can use,

string str = "I like \"string\"";    -- Output: I like "string"  
string str = @"Here is my ""quoted"" text.";  -- Output: Here is my "quoted" text.

To display a string enclosed within a double quotes that is assigned a control value (eg:- label), we can use,

Label1.Text = "String";
string str = "\"" + Label1.Text + "\"";  -- Output: "String"

Monday, 2 April 2012

HOW TO CREATE AND DOWNLOAD A TEXT FILE USING C#

To create and download a text file with some text in it, 
In aspx page,
<asp:Button ID="Button1" runat="server" Text="Download" onclick="Button1_Click" />

In aspx.cs page,

protected void Button1_Click(object sender, EventArgs e)
{
    string text = "ASP.NET, C#, SQL SERVER, TIPS & TRICKS AND MORE..";  
    string attachment = String.Format("attachment; filename=Blog.txt");
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.AddHeader("content-disposition", attachment);
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.Write(text);
    HttpContext.Current.Response.End();
}


As you can see in the above code, the type of the file that has to be downloaded is specified in the ContentType. Similarly, we can download files with other extensions. For reference, take a look at the below formats .

".asf" = "video/x-ms-asf"
".avi" = "video/avi"
".doc" = "application/msword"
".zip" = "application/zip"
".xls" = "application/vnd.ms-excel"
".gif" = "image/gif"
".jpg"= "image/jpeg"
".wav" = "audio/wav"
".mp3" = "audio/mpeg3"
".mpg" "mpeg" = "video/mpeg"
".rtf" = "application/rtf"
".htm", "html" = "text/html"
".asp" = "text/asp"