Click here to Skip to main content
15,883,883 members
Articles / Web Development

ASP.NET Web Greeting Card Tool

Rate me:
Please Sign up or sign in to vote.
4.93/5 (26 votes)
14 Jan 2016CPOL5 min read 53K   1.7K   35   18
In this article, we will see how to create a web based Greeting Card tool using ASP.NET and jQuery.

Image 1

Introduction

In my previous article, ASP.NET Web Photo Editing Tool Using HTML 5, I explained how to create a web based Photo editing tool. In this article, we will see how to create a web based Greeting Card tool using ASP.NET and jQuery.

This article shows the details of how to do the following:

Image 2

  1. Clear Card: Clear the card to design new.
  2. Add Image: Upload Image to Canvas Tag (You can add any image to create your Greeting Card).
  3. Add Sticker: Add stickers, for example balloon, flowers, and so on to our Greeting Card for decoration. I have downloaded all the free images from the Icon Finder.
  4. Select Color: The selected color can be applied to Card Border and Text.
  5. Add Border: Add a border to the Greeting Card.
  6. Card Title: Add Greeting Card Title. For example, “Happy New Year”.
  7. Card Message: You can add your own wishes to the Greeting card.
  8. Save and Send to Email: The final created Greeting Card can be saved to the application root folder. Also, send the card to a user entered email address.
  9. Post Canvas Greeting Card to Facebook: The Final Edited Greeting Card can be posted to Facebook.

Prerequisites

Using the Code

The main purpose is to make the program very simple and easy to use. All the functions have been well commented in the project. Here, we will see the procedure to create a Web Greeting Card tool using a HTML 5 canvas.

HTML5

HTML5 is the new version of HTML. HTML5 has cross-platform support. That means HTML5 can work on a PC, Tablet and a Smartphone. HTML5 should be started with a DOCTYPE, for example:

Some of the new features in HTML5 are CANVAS, AUDIO, and VIDEO and so on.

Canvas

Canvas is the element for 2D drawings using JavaScript. The Canvas has methods such as drawing paths, rectangles, arcs, text and so on. The Canvas element looks like the following:

HTML
<canvas id="canvas" width="400" height="400"></canvas>

Reference for HTML5 canvas. The Canvas is nothing but a container for creating graphics. To create 2D graphics, we need to use JavaScript. We will see the details here in the code.

Create Your Web Application in Visual Studio 2015

After installing Visual Studio 2015, click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Web Application. Enter your Project Name and click OK.

Image 3

Select Web Forms and click OK.

Image 4

Now our web application has been created. Add all script and image files needed for this project.

JavaScript Declaration Part

Firstly, add all the JavaScript references and styles to your ASP.NET page as in the following:

HTML
<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.0)" />
    <meta http-equiv="Page-Exit" content="blendTrans(Duration=0.0)" />
   <meta http-equiv="x-ua-compatible" content="IE=9" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" 
    type="text/javascript"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
       <script type="text/javascript" 
       src="Scripts/jquery-1.10.2.min.js"></script>
   <script type="text/javascript" 
   src="Scripts/jscolor.js"></script>

Declare all the variables necessary for Greeting Card Tool. In each declaration, I have added comments to explain its usage.

JavaScript
<SCRIPT>
    //public Canvas object to use in all the functions.
    //Main canvas declaration
    var canvas;
    var ctx;
    var canvasEffect;
    var ctxEffect;
    var x = 75;
    var y = 50;
    //Width and Height of the canvas
    var WIDTH = 200;
    var HEIGHT = 252;
    //    var dragok = false;
    //Global color variable which will be used to store the selected color name.
    var Colors = "";
    var newPaint = false;
    var DrawingTypes = "";
    //Circle default radius size
    var radius = 30;
    var radius_New = 30;
    var stickerWidth = 40, stickerHeight = 40;
    // Rectangle array
    rect = {},
    //drag= false default to test for the draging
drag = false;
    // Array to store all the old Shapes drawing details
    var rectStartXArray = new Array();
    var rectStartYArray = new Array();
    var rectWArray = new Array();
    var rectHArray = new Array();
    var recttextXArray = new Array();
    var recttextYArray = new Array();
    var recttextWArray = new Array();
    var recttextHArray = new Array();
    var textXArray = new Array();
    var textYArray = new Array();
    var rectColor = new Array();
    var DrawType_ARR = new Array();
    var radius_ARR = new Array();
    var Text_ARR = new Array();
    var Text_ARRNew = new Array();
    // Declared for the Free hand pencil Drawing.
    var prevX = 0,
    currX = 0,
    prevY = 0,
    currY = 0;
    //to add the Image
    var ImageNames = new Array();
    var imageCount = 0;
    var imageObj = new Image();
    var imageObj_BG = new Image();
    //to clear the Canvas
    function clear() {
        ctx.clearRect(0, 0, WIDTH, HEIGHT);
    }

init() Method

init is important since for each button click, this function will be called and pass the parameter for each function type. In this method, I will create an object for the canvas and this canvas object will be used in all other functions. Here, for example, the DrawType will be DrawImage, DrawText, DrawBorder. Place Uploaded Image as Background and the ImageName parameter will be used to pass each sticker image name and so on. In this init method, I will create Mouse events such as Mousedown, Mousemove and MouseUp to add a sticker, move a sticker, resize a sticker and so on.

JavaScript
//Initialize the Canvas and Mouse events for Canvas
    function init(DrawType, ImageName) {
        newPaint = true;
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d");
        canvasEffect = document.getElementById("canvas");
        ctxEffect = canvasEffect.getContext("2d");
        x = 5;
        y = 5;
        if (ImageName) {       
            ImageNames[imageCount] = ImageName;
            imageCount = imageCount + 1;
        }

        DrawingTypes = DrawType;
        if (DrawType = 'BG') {
            ctx.drawImage(imageObj_BG, 1, 1, canvas.width - 1, canvas.height - 1);
        }   

        radius = 30;
        radius_New = radius;
        canvas.addEventListener('mousedown', mouseDown, false);
        canvas.addEventListener('mouseup', mouseUp, false);
        canvas.addEventListener('mousemove', mouseMove, false);
        return setInterval(draw, 10);
    }

Add Image to canvas:

Image 5

In file onchange event, we get an Image uploaded by user. We pass this uploaded image to be set as our Canvas Background to design our Greeting Card.

HTML
<input type="file" accept="image/*" onchange="uploadImage(event)" />
// to upload the image to Canvas
    var uploadImage = function (event) {
        var reader = new FileReader();
        ////canvas = document.getElementById("canvas");
        ////ctx = canvas.getContext("2d");
        reader.onload = function () {
            imageObj_BG.src = reader.result;
            init('BG', '');
            // ctx.drawImage(imageObj_BG, 2, 3, canvas.width - 6, canvas.height );
        };
        reader.readAsDataURL(event.target.files[0]);
    };

Add Border/Title/Sticker

Image 6

In the Border Image click event, we passed the DrawType as "Border" and in the mouse move event, we will call the draw() method. This method depends on the DrawingTypes selected. We will add the features to the canvas tag, for example, if Border is selected, then we will draw the border for the canvas tag. If Images is selected, then we will add the selected sticker image to the canvas tag.

JavaScript
//Draw all Shapes, Text and add images
    function draw() {
        ctx.beginPath();
        Colors = document.getElementById("SelectColor").value;
        ctx.fillStyle = "#" + Colors;
        switch (DrawingTypes) {
            case "Border":
                ctx.strokeStyle = "#" + Colors;
                ctx.lineWidth = 10;
                ctx.strokeRect(0, 0, canvas.width, canvas.height)
                DrawBorder = "YES";
                //     ctx.rect(canvas.width - 4, 0, canvas.width - 4, canvas.height);
                break;
            case "Images":
                imageObj.src = ImageNames[imageCount - 1];
                ctx.drawImage(imageObj, rect.startX, rect.startY, rect.w, rect.h);
                //  ctx.drawImage(imageObj, rect.startX, rect.startY, 
                //  stickerWidth, stickerHeight);
                break;
            case "DrawText":
                ctx.font = '54pt Calibri';
                ctx.fillText($('#txtInput').val(), drawx, drawy);
                break;
            case "DrawTextNew":
                ctx.font = '16pt Calibri';
                ctx.fillText($('#txtmsg').val(), drawx, drawy);
                break;
        }
        ctx.fill();
        // ctx.stroke();
    }

Save and Send Email

In the send email button client click, we will store the Canvas as image to the hidden field.

JavaScript
<asp:Button ID="btnImage" runat="server" Text="Send Email"  
             OnClientClick = "sendEmail();return true;" onclick="btnImage_Click" /> 

 function sendEmail() { 
    var m = confirm("Are you sure to Save "); 
    if (m) { 
        var image_NEW = document.getElementById("canvas").toDataURL("image/png"); 
        image_NEW = image_NEW.replace('data:image/png;base64,', ''); 
        $("#<%=hidImage.ClientID%>").val(image_NEW); 
        alert('Image saved to your root Folder and email send !'); 
    } 
}

In the code behind button click event, we will get the hidden field value and store the final result image to the application root folder. This image will be used to send an email.

C#
protected void btnImage_Click(object sender, EventArgs e)
               {
                      string imageData = this.hidImage.Value;
                      Random rnd = new Random();
 string imagePath = HttpContext.Current.Server.MapPath
                    ("Shanuimg" + rnd.Next(12, 2000).ToString() + ".jpg");
                      using (FileStream fs = new FileStream(imagePath, FileMode.Create))
                      {
                              using (BinaryWriter bw = new BinaryWriter(fs))
                              {
                                     byte[] data = Convert.FromBase64String(imageData);
                                     bw.Write(data);
                                     bw.Close();
                                     sendMail(imagePath);
                              }
                      }
               }

In the button click event after the image is saved to the root folder, we will send the image path to the sendMail method. In this method using the user entered From and To email address, we will send the Greeting Card with the subject and message to the email.

C#
private void sendMail(string FilePath)
               {
                      MailMessage message = new MailMessage();
                      SmtpClient smtpClient = new SmtpClient();
                      string msg = string.Empty;
                      try
                      {
                              MailAddress fromAddress = 
                                          new MailAddress(txtFromEmail.Text.Trim());
                              message.From = fromAddress;
                              message.To.Add(txtToEmail.Text.Trim());

                              message.Attachments.Add(new Attachment(FilePath));
                              message.Subject = txtSub.Text.Trim();
                              message.IsBodyHtml = true;
                              message.Body = txtMessage.Text.Trim();
                              smtpClient.Host = "smtp.gmail.com";
                              smtpClient.Port = 587;
                              smtpClient.EnableSsl = true;
                              smtpClient.UseDefaultCredentials = true;
                              smtpClient.Credentials = new System.Net.NetworkCredential
                              (userGmailEmailID, userGmailPasswod);

                              smtpClient.Send(message);
                              msg = "Successful<BR>";
                      }
                      catch (Exception ex)
                      {
                              msg = ex.Message;
                      }
               }

Here, we use the host as smtp.gmail.com and in System.Net.NetworkCredential(userGmailEmailID, userGmailPasswod); you need to provide your Gmail email address and Gmail password to send the email.

Note: We have declared the variable as global as in the following so that the user can add their own Gmail Email address and Gmail password.

C#
string userGmailEmailID = "YourGamilEmailAddress";
string userGmailPasswod = "YourGmailPassword";

Image 7

Post Photo to Facebook

To post our photo to Facebook, we need to have a Facebook APPID. To create our APPID, go to Facebook Developers and login using your Facebook id.

After Login, to create New App ID, enter your Display Name and click Create App ID.

Image 8

Now you can see your App ID has been created. You can use this App ID to post your image to Facebook.

Image 9

Click on Settings and add your website URL in case, if you’re developing as localhost in site URL, you can give the localhost URL as below:

Image 10

Click Settings, then Advanced and set the Embedded browser OAutho Login to “YES”.

Image 11

Send to FB: Using Facebook API, we can pass the Canvas converted base64 Image to Facebook using our App ID. Take a look at this reference link which explains how to convert and embed HTML5 Canvas 5 Image to base64.

JavaScript
function sendtoFB() {  
       var m = confirm("Are you sure Post in FaceBook ");  
       if (m) {  
  
           $.getScript('//connect.facebook.net/en_US/all.js', function () {  
               // Load the APP / SDK  
               FB.init({  
                   appId: 'YOURFBAPPID', // App ID from the App Dashboard  
                   cookie: true,         // set sessions cookies to allow your server 
                                         // to access the session?  
                   xfbml: true,          // parse XFBML tags on this page?  
                   frictionlessRequests: true,  
                   oauth: true  
               });  
               FB.login(function (response) {  
                     
                   if (response.authResponse) {  
                       
                       window.authToken = response.authResponse.accessToken;  
                       
                       PostImageToFacebook(window.authToken)  
                   } else {  
                   }  
               }, {  
                   scope: 'publish_actions'  
               });  
           });    
       }    
   }  

Note: For appId, enter your FB appID which you have created.

Image 12

Points of Interest

Note: If your posted Photo on Facebook is not visible to other users, then you have to set your app to live. To make your app live, go to your App Facebook page, select Settings and set "Do you want to make this app and all its live features available to the general public?"to YES.

Image 13

Tested Browsers

  • Chrome
  • Internet Explorer 10

History

  • 21st December, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
Questiondrawx is not defined Pin
Mahmoud Adb-Elghany5-May-21 14:29
Mahmoud Adb-Elghany5-May-21 14:29 
QuestionMulti Line Text Pin
Member 1163305815-Feb-16 9:40
Member 1163305815-Feb-16 9:40 
QuestionHello Sir! Have couple of questions Pin
Member 116330589-Feb-16 11:57
Member 116330589-Feb-16 11:57 
AnswerRe: Hello Sir! Have couple of questions Pin
syed shanu9-Feb-16 12:44
mvasyed shanu9-Feb-16 12:44 
GeneralRe: Hello Sir! Have couple of questions Pin
Member 1163305810-Feb-16 1:51
Member 1163305810-Feb-16 1:51 
QuestionNice Project !...But have one query Pin
Member 116330583-Feb-16 11:51
Member 116330583-Feb-16 11:51 
AnswerRe: Nice Project !...But have one query Pin
syed shanu3-Feb-16 13:08
mvasyed shanu3-Feb-16 13:08 
QuestionWeb Greeting Card Tool Pin
Member 82662323-Jan-16 6:05
Member 82662323-Jan-16 6:05 
AnswerRe: Web Greeting Card Tool Pin
syed shanu3-Jan-16 13:40
mvasyed shanu3-Jan-16 13:40 
AnswerRe: Web Greeting Card Tool Pin
MikeCollins26-Jan-16 2:34
MikeCollins26-Jan-16 2:34 
GeneralMy vote of 5 Pin
George Tourtsinakis1-Jan-16 3:44
George Tourtsinakis1-Jan-16 3:44 
GeneralMy vote of 4 Pin
Omar Nasri22-Dec-15 4:59
professionalOmar Nasri22-Dec-15 4:59 
GeneralRe: My vote of 4 Pin
syed shanu22-Dec-15 13:16
mvasyed shanu22-Dec-15 13:16 
GeneralMy vote of 5 Pin
Santhakumar M22-Dec-15 4:02
professionalSanthakumar M22-Dec-15 4:02 
GeneralRe: My vote of 5 Pin
syed shanu22-Dec-15 13:16
mvasyed shanu22-Dec-15 13:16 
GeneralMy Vote of 5 Pin
aarif moh shaikh20-Dec-15 19:00
professionalaarif moh shaikh20-Dec-15 19:00 
GeneralRe: My Vote of 5 Pin
syed shanu20-Dec-15 19:03
mvasyed shanu20-Dec-15 19:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.