Advertisements

Create a Zip File Using Asp.Net & C#


Introduction

In this article I will explain how to create a zip file using ASP.Net & C#. In this purpose we can use Ionic.Zip.dll reference for creating Zip file in ASP.Net.So first we download the dll through this link Ionic.Zip.dll.

Assemblies Required

After downloading the  Ionic.Zip.dll Zip file you can get many folders inside the zip file. Go to zip-v1.9-Reduced folder Inside the zip file. then open the particular folder that contain Ionic.Zip.Reduced.dll.

We must add the following namespace:

using Ionic.Zip;

Code

The following code will create zip file in ASP.Net with the help of  Ionic.Zip.Reduced.dll.

protected void btn_zip_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("~/Test/");//Location for inside Test Folder
        string[] Filenames = Directory.GetFiles(path);
        using (ZipFile zip = new ZipFile())
        {
            zip.AddFiles(Filenames, "Project");//Zip file inside filename
            zip.Save(@"C:\Users\user\Desktop\Projectzip.zip");//location and name for creating zip file
            
        }
    }
  • Code line number 03 describe the location of the file.Those files we can convert into zip format.
  • Code line number 07 describe that the particular name of the file inside the zip file.
  • Code line number 08 define the name of the zip file we are going to create.

Dll Reference

Add the Downloaded dll inside the Bin Folder.

5

Figure 1 : Ionic.Zip.Reduced.dll

Design

3

Figure 2

OutPut

Created the Zip file.

1

Figure 3

Inside The Zip File.

2

Figure 4

Summary

We learned how to create a Zip file using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Advertisements

Send Email To Multiple Email Addresses With Inline Image Using ASP.NET With C#


Introduction

In this article I will explain how to send multiple emails with Inline Image. Before reading this article you must read my previous email related article because I have explained some basics part in my previous article and changed few of the code part in new one. The following are my previous articles.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {
        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        
        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);

        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress email", "fromaddress password");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Net.Mime;

Multiple Email

The following code will help to split the Comma ‘”,” separated email in the given textbox ( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress email"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Inline Image Code

The following code will help to fetch the image and set into the inline of the email body.

        string mailbody = Txt_Bodycontent.Text + "<br/><html><body><h1>Happy Coding</h1><br><img src=\"cid:Email\"  width='600' height='300'></body></html>";
        AlternateView AlternateView_Html = AlternateView.CreateAlternateViewFromString(mailbody, null, MediaTypeNames.Text.Html);
        // Create a LinkedResource object and set Image location path and Type
        LinkedResource Picture1 = new LinkedResource(Server.MapPath("Selfie.jpeg"), MediaTypeNames.Image.Jpeg);
        Picture1.ContentId = "Email";
        AlternateView_Html.LinkedResources.Add(Picture1);
        message.AlternateViews.Add(AlternateView_Html);
        message.Body = mailbody;

Important Notes

  • Firstly, create one string that contain the html body with Inline image. In the above code “mailbody” is the string. It contains the html body.
  • Create an AlternateView object for those supporting the HTML content.
  • System.Net.Mime namespace contain the Image type and html format ( MediaTypeNames.Image.Jpeg & MediaTypeNames.Text.Html ).
  • Create a LinkedResource object for the Inline image to send.
  • Add a LinkedResource object to the AlternateView object.
  • Check the correct Image location otherwise it will throw an error.
  • Give same Image source id and LinkedResource ContentId.Like “<img src=\”cid:Email\” width=’600′ height=’300′>” & Picture1.ContentId = “Email“;

Design

1

Output

2

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with Inline Image using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Send Email To Multiple Email Addresses With Attachment Using ASP.NET With C#


Introduction

In my previous article I explained Send Email Using ASP.Net With C#. In this article I will explain how to send multiple emails with attachments. If you don’t bother about the code because I just change some codes in my previous article. ! Let’s start.

Code

protected void btn_sendemail_Click(object sender, EventArgs e)
    {

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }
        if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#23377771"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

        string mailbody = Txt_Bodycontent.Text;
        message.Subject = Txt_Subject.Text;
        message.Body = mailbody;
        message.BodyEncoding = Encoding.UTF8;
        message.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp    
        System.Net.NetworkCredential basicCredential1 = new
        System.Net.NetworkCredential("fromaddress", "fromaddresspassword");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = basicCredential1;
        try
        {
            client.Send(message);
        }

        catch (Exception ex)
        {
            throw ex;
        }
    }

We must add the following namespace:

using System.Net;
using System.Net.Mail;
using System.Text;

Multiple Email

The following code will help to split the Comma ‘”,” Separated email in the given textbox( Txt_toaddress.Text ).

        string to = Txt_toaddress.Text; //To address    
        string from = "fromaddress"; //From address 
        string[] Multiple = to.Split(',');
        MailMessage message = new MailMessage();
        message.From = new MailAddress(from);

        foreach (string multiple_email in Multiple)
        {
            message.To.Add(new MailAddress(multiple_email));
        }

Attachment

If you want to send an attachment with email you can add the following code. Otherwise you just remove this part in the code.

if (FileUpload2.HasFile)//Attaching<a class="fithdblru" style="z-index: 2147483647;" title="Click to Continue > by DNSUnlocker" href="#79547700"> document<img src="https://cdncache-a.akamaihd.net/items/it/img/arrow-10x10.png" alt="" /></a>
        {
            string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
            message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));

        }

File Upload

If you want to select multiple files in a single file uploader, then you just add AllowMultiple=”true”.This is one of the option in ASP file upload.

<div>  
    <asp:FileUpload runat="server" ID="FileUpload2" AllowMultiple="true" />  
</div>

Design

output

Output

Capture

Common Error for sending an Email

Check the following reference to solve your 5.5.1 Authentication.

Summary

We learned how to send multiple emails with attachment using ASP.NET and C#. I hope this article is useful for all .NET beginners.

Write Text On a Image Using Asp.Net & C#


Introduction

This article explains how to Write a Text On Image Using Asp.Net & C#.In this article i am using some common library functions and methods.

Image Class & Bitmap Class

  • The Image class is one of the example of Abstract Class
  • The Bitmap class is an implementation of the Image class and it inherits from the Abstract Image class.
  • After implementation we can get the Image Class functionality in Bitmap Class.

C# Code

The below code is using for Write a Text On Image.We can change the below functionalities based on our requirement.

        //creating a image object
        System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("onam.jpg")); // set image 
        //draw the image object using a Graphics object
        Graphics graphicsImage = Graphics.FromImage(bitmap);

        //Set the alignment based on the coordinates   
        StringFormat stringformat = new StringFormat();
        stringformat.Alignment = StringAlignment.Far;
        stringformat.LineAlignment = StringAlignment.Far;

        StringFormat stringformat2 = new StringFormat();
        stringformat2.Alignment = StringAlignment.Center;
        stringformat2.LineAlignment = StringAlignment.Center;

        //Set the font color/format/size etc..  
        Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//direct color adding
        Color StringColor2 = System.Drawing.ColorTranslator.FromHtml("#e80c88");//customise color adding
        string Str_TextOnImage = "Happy";//Your Text On Image
        string Str_TextOnImage2 = "Onam";//Your Text On Image

        graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40,
        FontStyle.Regular), new SolidBrush(StringColor), new Point(268, 245),
        stringformat); Response.ContentType = "image/jpeg";

        graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 111,
        FontStyle.Bold), new SolidBrush(StringColor2), new Point(145, 255),
        stringformat2); Response.ContentType = "image/jpeg";

        bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

Graphics & Bitmap

A Bitmap is an object used to work with images defined by pixel data and you can draw the image object using a Graphics object.Check the below code.

         //creating a image object
        System.Drawing.Image bitmap = (System.Drawing.Image)Bitmap.FromFile(Server.MapPath("onam.jpg")); // set image 
        //draw the image object using a Graphics object
        Graphics graphicsImage = Graphics.FromImage(bitmap);

Formatting the string

Change Text Alignment based on the coordinates

        //Set the alignment based on the coordinates   
        StringFormat stringformat = new StringFormat();
        stringformat.Alignment = StringAlignment.Far;
        stringformat.LineAlignment = StringAlignment.Far;

        StringFormat stringformat2 = new StringFormat();
        stringformat2.Alignment = StringAlignment.Center;
        stringformat2.LineAlignment = StringAlignment.Center;

Text On Image

Set the font color,size,format.

        string Str_TextOnImage = "Happy";//Your Text On Image
        string Str_TextOnImage2 = "Onam";//Your Text On Image

        graphicsImage.DrawString(Str_TextOnImage, new Font("arial", 40,
        FontStyle.Regular), new SolidBrush(StringColor), new Point(268, 245),
        stringformat); Response.ContentType = "image/jpeg";

        graphicsImage.DrawString(Str_TextOnImage2, new Font("Edwardian Script ITC", 111,
        FontStyle.Bold), new SolidBrush(StringColor2), new Point(145, 255),
        stringformat2); Response.ContentType = "image/jpeg";

String Color

Adding the string color in two way..

Color StringColor = System.Drawing.Color.Red;//direct color adding  
Color StringColor = System.Drawing.ColorTranslator.FromHtml("#933eea");//customise color adding  

Important Section

Namespace

using System.Drawing;
using System.Drawing.Imaging;

The above namespace is contain Graphics,Bitmaps,Image Editing and Alignment,etc libraries.

OutPut

Happy Onam

Happy Onam

Auto Save Using AJAX


Introduction

This article explains how to automatically save a value into a SQL database using an ASP.Net WebMethod and jQuery Ajax.

Jquery

The following code shows that SaveDraft.aspx is the aspx page and AutoSave is the method. We pass the client-side value to the server-side using Ajax and WebMethod.

$(document).ready(function () {
 // Configure to save every 5 seconds
 window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds

 });

 // ajax method
 function saveDraft() {

 $.ajax({
 type: "POST",
 contentType: "application/json; charset=utf-8",
 url: "SaveDraft.aspx/AutoSave",
 data: "{'firstname':'" + document.getElementById('Firstname').value + "','middlename':'" + document.getElementById('Middlename').value + "','lastname':'" + document.getElementById('Lastname').value + "'}",

 success: function (response) {

 }

 });

 }

In the following code the saveDraft function fires every 5 seconds. The value will be saved in the database every 5 seconds without post-backs. Based on our requirements we can change the time interval.

 $(document).ready(function () {
            // Configure to save every 5 seconds
            window.setInterval(saveDraft, 5000);//calling saveDraft function for every 5 seconds

        });

Database structure

Create a table in a database for storing the personal information.The following SQL code contains an existing person’s details. So we can change those values at runtime without a post-back and button-click.

USE [TestDB]
GO
/****** Object:  Table [dbo].[Autosave]    Script Date: 08/07/2015 18:19:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Autosave](
	[Id] [int] NULL,
	[firstname] [nvarchar](50) NULL,
	[middlename] [nvarchar](50) NULL,
	[lastname] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Autosave] ([Id], [firstname], [middlename], [lastname]) VALUES (1, N'Rajeesh', N'', N'Menoth')

C# Code

The WebMethod will catch the client-side value in the server side. In the given example I am passing the id directly into the update query. You can modify the code for your requirements.

[WebMethod]
    public static string AutoSave(string firstname, string middlename, string lastname)
    {
        int id = 1;
        string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
        SqlConnection con = new SqlConnection(ConnectionString);
        {
            string str = "Update Autosave set firstname='" + firstname + "',middlename= '" + middlename + "',lastname= '" + lastname + "' where Id=" + id + "";
            SqlCommand cmd = new SqlCommand(str, con);
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return "True";
            }
        }

    }

Important Section

1.Namespace

The given namespace contains the WebMethod,database connection libraries.

using System.Web.Services;
using System.Data.SqlClient;

2.Reference

Add the following jQuery reference.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
pic1

Figure 1

Output

pic2

Figure 2

Summary

We learned how to automatically save a value into a SQL database using ASP.Net WebMethod and jQuery Ajax. I hope this article is useful for all .NET beginners.

Convert Pdf to Other format Using Spire.Pdf


Introduction :

Spire.PDF from E-iceblue is a .NET component that lets you manipulate PDF documents programmatically. Spire.PDF for .NET is a professional .NET library specially designed for developers to create, read, write, convert and print PDF document files from any .NET platform with fast and high-quality performance.

Background :

I got an opportunity from a China-based company E-iceblue, to review one of their products. I selected Spire.Pdf from E-iceblue, which is a .Net component that lets you manipulate PDF documents programmatically.

Namespace:

using Spire.Pdf;
using Spire.Doc.Documents;

Add Reference :

  • Add the following reference.
  • Add the Spire.Pdf,Spire.Doc,Spire.License Dll files to the bin folder.
  • Spire.Pdf contains the PDF conversion libraries.
  • Spire.Doc contains the doc conversion libraries.
Reference

Figure 1: Add Reference

Code :

Code

Creating the instance of PdfDocument

PdfDocument document_doc = new PdfDocument();

Load the file location, in this code “spire.pdf” is a pdf file as in the following:

document_doc.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\spire.pdf");

Convert the PDF file into Document format using “FileFormat.Doc”

document_doc.SaveToFile("Spire.doc", FileFormat.DOC);

Launch the conversion process as in the following:

System.Diagnostics.Process.Start("Spire.doc");

Examples :

The following converts a PDF to Xps:


//Creating instance of PdfDocument

PdfDocument document = new PdfDocument();

//Loading the File path of pdf file

document.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\SpireXps.pdf");

//Save Spire.Pdf.PdfDocument object as XPS format.

document.SaveToFile("SpireXps.xps", FileFormat.XPS);

//Launch XPS

System.Diagnostics.Process.Start("SpireXps.xps");

OutPut :

Convert Pdf to Xps

OutPut 1

The following converts a PDF to Doc:


//Creating instance of PdfDocument

PdfDocument document_doc = new PdfDocument();

//Loading the File path of pdf file

document_doc.LoadFromFile(@"E:\MVC APP\SpireDoc\SpireDoc\spire.pdf");

//Save Spire.Pdf.PdfDocument object as DOC format.

document_doc.SaveToFile("Spire.doc", FileFormat.DOC);

//Launch Document

System.Diagnostics.Process.Start("Spire.doc");

OutPut :

Convert Pdf to Doc

Figure 3: Output 2

Important Points :

  • Merge/split PDF documents.
  • Set PDF position, title display, resize, page mode and print scaling, and so on.
  • Protect PDF documents by setting passwords and digital signature.
  • Overlay documents.
  • Decrypt PDF Document.
  • Fast Conversion Process.

Reference : http://www.e-iceblue.com/Tutorials.html

Published : http://www.c-sharpcorner.com/UploadFile/2a6dc5/convert-pdf-to-other-format-using-spire-pdf/

 

How to send sms using C#


C#

public void send(string message, string no)
{

HttpWebRequest myReq =
// (HttpWebRequest)WebRequest.Create("http://ubaid.tk/sms/sms.aspx?uid=" + uid + "&pwd=" + password +
//"&msg=" + message + "&phone=" + no + "&provider=way2sms");
(HttpWebRequest)WebRequest.Create("put_urlink = "+"UrUsername"+ "&password=" + "UrPassword" + "&sender=" +"UrSenderID"+ "&to=" +no+ "&message=" + message+ "&reqid=1&format={json|text}&route_id=route+id&callback=Any+Callback+URL&unique=1&sendondate=" +"10-10-2014T05:17:52"+"");
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}

Button Click Code :

protected void btn_send_Click(object sender, EventArgs e)
{

send(txt_message.Text, txt_mobile.Text);

ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('sms sent successfully...');", true);

}
%d bloggers like this: