Menus

Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Thursday, May 8, 2014

How To Convert Date Time to “X minutes ago” in jQuery

Today I found a nice plugin with the help of which you can convert any date time on your HTML page to something similar to Gmail/Facebook updates – “5 minutes ago” or “a day ago”. The best part of this plugin is it auto updates the minutes as you’re on the webpage. So, if you have opened the page now and the date shows “1 minute ago”, after 5 minutes the same date will auto update to “6 minutes ago”. In this post, we will see how this plugin works and write a simple HTML using the plugin.

To start with, you can download the timeago plugin from here.This plugin depends on jquery. so the very 1st thing is to include jQuery in our code and then the plugin Javascript.
 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js">
</script>
<script src="jquery.timeago.js"></script>

Once the plugin files are loaded, you can use the plugin’s timeago() function in any of the following ways -
var date = $.timeago(new Date()); //Displays 'less than a minute ago'
var date = $.timeago('2014-05-04'); //Displays 'a day ago'

You can also call the timeago() function on a specific class on your page as below -
//This will modify the date time on all elements having class as 'time'
$(document).ready(function(){
   $(".time").timeago();
});

Friday, December 14, 2012

Display Watermark Text for ASP.Net TextBox, Password and MultiLine TextArea using jQuery Plugin

In this article I will explain how to Watermark ASP.Net TextBoxes in SingleLine, MultiLine and Password using jQuery Watermark plugin
 HTML Markup
In the below HTML Markup I have ASP.Net TextBoxes with different TextMode i.e. SingleLine, MultiLine and Password i.e. Normal TextBox, TextArea and Password fields. You will notice that I have set ToolTip property of the TextBox, the text in the ToolTip property will be displayed as the Watermark text.
 
UserName:
<asp:TextBox ID="txtUserName" runat="server" ToolTip="Enter UserName">asp:TextBox><br />
Password:
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" ToolTip="Enter Password">asp:TextBox><br />
Email:
<asp:TextBox ID="txtEmail" runat="server" ToolTip="Enter Email">asp:TextBox><br />
Details:
<asp:TextBox ID="txtDetails" runat="server" TextMode="MultiLine" ToolTip="Enter Details">asp:TextBox>
 
 
Applying Watermark to ASP.Net TextBoxes
I have built the jQuery Watermark plugin to apply Watermark to all types of ASP.Net TextBoxes i.e. SingleLine, MultiLine and Password.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">script>
<script src="WaterMark.min.js" type="text/javascript">script>
<script type="text/javascript">
    $(function () {
        $("[id*=txtUserName], [id*=txtPassword], [id*=txtDetails]").WaterMark();
 
        //To change the color of Watermark
        $("[id*=Email]").WaterMark(
        {
            WaterMarkTextColor: '#000'
        });
    });
script>
 
 
The Watermark jQuery plugin has an optional property WaterMarkTextColor which can be used to set the color of the Watermark text.
The complete page HTML markup is provided below
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">script>
<script src="WaterMark.min.js" type="text/javascript">script>
<script type="text/javascript">
    $(function () {
        $("[id*=txtUserName], [id*=txtPassword], [id*=txtDetails]").WaterMark();
 
        //To change the color of Watermark
        $("[id*=Email]").WaterMark(
        {
            WaterMarkTextColor: '#000'
        });
    });
script>
head>
<body>
    <form id="form1" runat="server">
    UserName:
    <asp:TextBox ID="txtUserName" runat="server" ToolTip="Enter UserName">asp:TextBox><br />
    Password:
    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" ToolTip="Enter Password">asp:TextBox><br />
    Email:
    <asp:TextBox ID="txtEmail" runat="server" ToolTip="Enter Email">asp:TextBox><br />
    Details:
    <asp:TextBox ID="txtDetails" runat="server" TextMode="MultiLine" ToolTip="Enter Details">asp:TextBox><br />
    form>
body>
html>
 
 

Select and Upload Multiple Files Gmail Style using JQuery and ASP.Net

In this article we will see how to upload multiple files AJAX style along with progress bar similar to the Google’s GMAIL in ASP.Net
And the answer is Uploadify plugin for JQuery which does the same in few simple steps. In this article I’ll explain the same.
Step 1
Download the Uploadify JQuery plugin and the JQuery Library using the links below.
Download JQuery

Download Uploadify

Once downloaded you’ll need to place the below four files
1. jquery-1.3.2.min.js
2. jquery.uploadify.js
3. uploader.fla
4. uploader.swf
in a folder called scripts in the root folder of your ASP.Net website application
Step 2
Start Visual Studio, create a new website and do as done below
 
Inherit the following files you downloaded earlier in the head section of the aspx or the master page
<link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
 
Add an ASP.Net FileUpload Control to the form tag
<form id="form1" runat="server">
    <div style = "padding:40px">
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </div>
</form>
 
Place the following script in the head section or the ContentPlaceHolder in case you are using Master Pages
<script type = "text/javascript">
$(window).load(
    function() {
    $("#<%=FileUpload1.ClientID %>").fileUpload({
        'uploader': 'scripts/uploader.swf',
        'cancelImg': 'images/cancel.png',
        'buttonText': 'Browse Files',
        'script': 'Upload.ashx',
        'folder': 'uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': true,
        'auto': true
    });
   }
);
</script>  
 
As you can see we need to specify some settings along with the FileUpload control. The complete list of settings and their description is available here
Important setting to point out is 'script': 'Upload.ashx'  which will handle the FileUpload and save the uploaded files on to the disk.
Below is the code for the Upload.ashx file
    
C#
<%@ WebHandler Language="C#" Class="Upload" %>
 
using System;
using System.Web;
using System.IO;
 
public class Upload : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
           
            string savepath = "";
            string tempPath = "";
            tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
            savepath = context.Server.MapPath(tempPath);
            string filename = postedFile.FileName;
            if (!Directory.Exists(savepath))
                Directory.CreateDirectory(savepath);
 
            postedFile.SaveAs(savepath + @"\" + filename);
            context.Response.Write(tempPath + "/" + filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
 
VB.Net
<%@ WebHandler Language="VB" Class="UploadVB" %>
 
Imports System
Imports System.Web
Imports System.IO
 
Public Class UploadVB : Implements IHttpHandler
   
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
 
        Dim savepath As String = ""
        Dim tempPath As String = ""
        tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
        savepath = context.Server.MapPath(tempPath)
        Dim filename As String = postedFile.FileName
        If Not Directory.Exists(savepath) Then
            Directory.CreateDirectory(savepath)
        End If
 
        postedFile.SaveAs((savepath & "\") + filename)
        context.Response.Write((tempPath & "/") + filename)
        context.Response.StatusCode = 200
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
 
End Class
 
As you will notice that the handler simply accepts the posted files and saves the file in folder called uploads inside the website root directory whose path is placed in an AppSettings key in the Web.Config file Refer below
<appSettings>
    <add key ="FolderPath" value ="uploads"/>
</appSettings >
 
That’s all you need to do now run the application and you’ll notice your website running
Browsing the File
Uploading Multiple Files like GMAIL in ASP.Net with AJAX and progressbar

Selecting Multiple Files Simultaneously
Selecting Multiple files in single browse ASP.Net

Uploading Multiple Files with upload progress

Uploading Multiple Files with Upload progress using AJAX ASP.Net
You might have noticed that the files are auto uploaded once browsed if you do not want this feature you can simply set the 'auto' settings to false. But in that case you’ll need to provide a trigger the uploading of files on user interaction by placing an Upload button
First you’ll need to set the Auto Upload setting to false refer the bold part
<script type = "text/javascript">
$(window).load(
    function() {
        $("#<%=FileUpload1.ClientID%>").fileUpload({
        'uploader': 'scripts/uploader.swf',
        'cancelImg': 'images/cancel.png',
        'buttonText': 'Browse Files',
        'script': 'Upload.ashx',
        'folder': 'uploads',
        'fileDesc': 'Image Files',
        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
        'multi': true,
        'auto': false
    });
   }
);
</script>
 
Then add the following link that will trigger the upload
<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadStart()">Start Upload</a>
 
That’s it now until user clicks the above link uploading of files won’t take place. Now since the upload is triggered by user it would be great to give him an additional link to clear the browsed files in one go
<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadClearQueue()">Clear</a>

Send email with Multiple Attachments in ASP.Net Website

In this article I will explain how to attach multiple files and send email like GMAIL in ASP.Net using jQuery Uploadify Plugin.

HTML Markup
Below is the HTML Markup which is nothing but a simple form to send email.
<table>
<tr><td>To:</td><td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td></tr>
<tr><td>Subject:</td><td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td></tr>
<tr><td>Body:</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr>
<tr><td></td><td><asp:FileUpload ID="FileUpload1" runat="server"/></td></tr>
<tr><td></td><td><table id="attachedfiles"></table></td></tr>
<tr><td></td><td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click"/></td></tr>
</table>
  Uploading multiple files as email attachments
To allow select and upload multiple files, I have made use of Uploadify jQuery plugin
<link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=FileUpload1]").fileUpload({
            'uploader': 'scripts/uploader.swf',
            'cancelImg': 'images/cancel.png',
            'buttonText': 'Attach Files',
            'script': 'Upload.ashx',
            'folder': 'uploads',
            'multi': true,
            'auto': true,
            'onSelect': function (event, ID, file) {
                $("#attachedfiles tr").each(function () {
                    if ($("td", this).eq(0).html() == file.name) {
                        alert(file.name + " already uploaded.");
                        $("[id*=FileUpload1]").fileUploadCancel(ID);
                        return;
                    }
                });
            },
            'onComplete': function (event, ID, file, response, data) {
                $("#attachedfiles").append("<tr><td>" + file.name + "</td><td><a href = 'javascript:;'>[x]</a></td></tr>");
            }
        });
    });
</script>
The files are uploaded via Generic Handler Upload.ashx. I am storing the uploaded files in Session. Also the uploaded files are dynamically displayed on the page
C#
<%@ WebHandler Language="C#" Class="UploadCS" %>
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Collections.Generic;
public class UploadCS : IHttpHandler, IRequiresSessionState {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            List<HttpPostedFile> files = (List<HttpPostedFile>)context.Session["Files"];
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            files.Add(postedFile);
            string filename = postedFile.FileName;
            context.Response.Write(filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}
VB.Net
<%@ WebHandler Language="VB" Class="UploadVB" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Collections.Generic
Public Class UploadVB : Implements IHttpHandler, IRequiresSessionState
  
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Try
            Dim files As List(Of HttpPostedFile) = DirectCast(context.Session("Files"), List(Of HttpPostedFile))
            Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
            files.Add(postedFile)
            Dim filename As String = postedFile.FileName
            context.Response.Write(filename)
            context.Response.StatusCode = 200
        Catch ex As Exception
            context.Response.Write("Error: " + ex.Message)
        End Try
    End Sub
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
 
Removing Attached files using jQuery AJAX
I have also added functionality to remove files like we have in GMAIL browser. To achieve this I have made use of jQuery AJAX and ASP.Net Page Methods
<script type="text/javascript">
$("#attachedfiles a").live("click", function () {
    var row = $(this).closest("tr");
    var fileName = $("td", row).eq(0).html();
    $.ajax({
        type: "POST",
        url: "Default.aspx/RemoveFile",
        data: '{fileName: "' + fileName + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () { },
        failure: function (response) {
            alert(response.d);
        }
    });
    row.remove();
});
</script>
The above JavaScript function makes call to a WebMethod defined below which deletes the file from the Session variable where it was stored.
C#
[WebMethod]
public static void RemoveFile(string fileName)
{
    List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
    files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
}
VB.Net
<WebMethod()> _
Public Shared Sub RemoveFile(fileName As String)
    Dim files As List(Of HttpPostedFile) = DirectCast(HttpContext.Current.Session("Files"), List(Of HttpPostedFile))
    files.RemoveAll(Function(f) f.FileName.ToLower().EndsWith(fileName.ToLower()))
End Sub
 
Sending the email with multiple attachment

Finally here’s the code to send email using GMAIL account.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Session["Files"] = new List<HttpPostedFile>();
    }
}
protected void btnSend_Click(object sender, EventArgs e)
{
    using (MailMessage mailMessage = new MailMessage())
    {
        mailMessage.From = new MailAddress("user@gmail.com");
        mailMessage.Subject = txtSubject.Text.Trim();
        mailMessage.Body = txtBody.Text.Trim();
        mailMessage.IsBodyHtml = true;
        mailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
        List<HttpPostedFile> files = (List<HttpPostedFile>)Session["Files"];
        foreach (HttpPostedFile file in files)
        {
            mailMessage.Attachments.Add(new Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType));
        }
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
        NetworkCred.UserName = mailMessage.From.Address;
        NetworkCred.Password = "<Password>";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mailMessage);
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Session("Files") = New List(Of HttpPostedFile)
    End If
End Sub
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim mailMessage As MailMessage = New MailMessage
    mailMessage.From = New MailAddress("user@gmail.com")
    mailMessage.Subject = txtSubject.Text.Trim
    mailMessage.Body = txtBody.Text.Trim
    mailMessage.IsBodyHtml = True
    mailMessage.To.Add(New MailAddress(txtTo.Text.Trim))
    Dim files As List(Of HttpPostedFile) = CType(Session("Files"), List(Of HttpPostedFile))
    For Each file As HttpPostedFile In files
        mailMessage.Attachments.Add(New Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType))
    Next
    Dim smtp As SmtpClient = New SmtpClient
    smtp.Host = "smtp.gmail.com"
    smtp.EnableSsl = True
    Dim NetworkCred As System.Net.NetworkCredential = New System.Net.NetworkCredential
    NetworkCred.UserName = mailMessage.From.Address
    NetworkCred.Password = "<Password>"
    smtp.UseDefaultCredentials = True
    smtp.Credentials = NetworkCred
    smtp.Port = 587
    smtp.Send(mailMessage)
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub
  Screenshot
Send email with multiple attachments like GMAIL in ASP.Net