Thursday 26 May 2016

Load the popup on just the first time page request only


protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            ClientScript.RegisterHiddenField("isPostBack", "1");
        }
}
<script type="text/javascript" >

        $(document).ready(function() {

            var isPostBackObject = document.getElementById('isPostBack');
            if (isPostBackObject == null) {
                var id = '#dialog';
                //modal: true
                //Get the screen height and width
                var maskHeight = $(document).height();
                var maskWidth = $(window).width();

                //Set heigth and width to mask to fill up the whole screen
                $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

                //transition effect  
                $('#mask').fadeIn(1000);
                $('#mask').fadeTo("slow", 0.9);

                //Get the window height and width
                var winH = $(window).height();
                var winW = $(window).width();

                //Set the popup window to center
                $(id).css('top', winH / 2 - $(id).height() / 2);
                $(id).css('left', winW / 2 - $(id).width() / 2);

                //transition effect
                $(id).fadeIn(2000);

                //if close button is clicked
                $('.window .close').click(function(e) {
                    //Cancel the link behavior
                    e.preventDefault();

                    $('#mask').hide();
                    $('.window').hide();
                });

            }
<style type="text/css">
  #mask {
  position:absolute;
  padding-left:60px;
  padding-top:80px;
  padding-bottom:80px;
  padding-right:50px; /*-- These Padding is for the border of jquery Pop-up --*/
  left:0;
  top:0;
  z-index:9999;
  background-color:#000000;
  display:none;
}  
#boxes .window {
  position:absolute;
  left:0;
  top:0;
  width:330px;
  height:147px;
  display:none;
  z-index:9999;
  padding:20px;
  background-color:#000000;  
  border: 20px solid #79BBFD;  
  border-radius: 10px;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;

}
#boxes #dialog {
  padding:10px;
  background:url('images/localOffers-bg.jpg'); 
  width:330px; height:147px; 
  background-repeat:no-repeat; 
  margin-top:20px;
  
}

<div id="boxes">
<div id="mask" >
<div id="dialog" class="window">
<span class="LocalOffersHeading">Find Local Offers                                     
<a href="#"  style="float: right; margin: -45px -45px 0 0;"  class="close"> 
<img src="Images/close_pop.png" alt="CLOSE" /></a> </span> <br /> <br />
Finding local offers has never been easier. Just select your city location from
the drop down and find the most recent local discounts in your area. We've also
made simple to stay in touch with you favorite merchants but signing up for the
email discounts! <br /><br />
<asp:DropDownList ID="ddlj" runat="server"  style="Width:228px;  Height:20px;" 
 OnSelectedIndexChanged="popup_SelectedIndexChanged" >
</asp:DropDownList>
                                     
<asp:ImageButton ID="jqbutton" runat="server" ImageUrl="~/images/bt-go.jpg"
 OnClick="imgBtnGo_Click"
 CausesValidation="false" Style="height: 16px;"  />
                                       
</div>
<!-- Mask to cover the whole screen -->
<%--<div style="width: 1478px; height: 602px; display: none; opacity: 0.8;" id="mask">
</div>--%>
                                </div>
                            </div>

How to send email Asynchronously in ASP.Net using Background Thread

HTML Markup

<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 80px">
            To:
        </td>
        <td>
            <asp:TextBox ID="txtTo" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Subject:
        </td>
        <td>
            <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td valign = "top">
            Body:
        </td>
        <td>
            <asp:TextBox ID="txtBody" runat="server" TextMode = "MultiLine" Height = "150" Width = "200"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            File Attachment:
        </td>
        <td>
            <asp:FileUpload ID="fuAttachment" runat="server" />
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Email:
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
            Gmail Password:
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" TextMode = "Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;
        </td>
    </tr>
    <tr>
        <td>
        </td>
        <td>
            <asp:Button Text="Send" OnClick="SendAsyncEmail" runat="server" />
        </td>
    </tr>
</table>



Namespaces
You will need to import the following namespaces
C#

using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;

VB.Net

Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Threading


Sending email asynchronously in background using Thread


C#

protected void SendAsyncEmail(object sender, EventArgs e)
{
    string to = txtTo.Text;
    string from = txtEmail.Text;
    string password = txtPassword.Text;
    string subject = txtSubject.Text;
    string body = txtBody.Text;
    HttpPostedFile postedFile = fuAttachment.PostedFile;
    Thread email = new Thread(delegate()
    {
        SendEmail(to, from, password, subject, body, postedFile);
    });
 
    email.IsBackground = true;
    email.Start();
    ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
 
private void SendEmail(string to, string from, string password, string subject, string body, HttpPostedFile postedFile)
{
    using (MailMessage mm = new MailMessage(from, to))
    {
        mm.Subject = subject;
        mm.Body = body;
        if (postedFile.ContentLength > 0)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            mm.Attachments.Add(new Attachment(postedFile.InputStream, fileName));
        }
        mm.IsBodyHtml = false;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential(from, password);
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}

VB.Net

Protected Sub SendAsyncEmail(sender As Object, e As EventArgs)
    Dim [to] As String = txtTo.Text
    Dim from As String = txtEmail.Text
    Dim password As String = txtPassword.Text
    Dim subject As String = txtSubject.Text
    Dim body As String = txtBody.Text
    Dim postedFile As HttpPostedFile = fuAttachment.PostedFile
    Dim email As New Thread(Sub() SendEmail([to], from, password, subject, body, postedFile))
    email.IsBackground = True
    email.Start()
    ClientScript.RegisterStartupScript([GetType](), "alert", "alert('Email sent.');", True)
End Sub
 
Private Sub SendEmail([to] As String, from As String, password As String, subject As String, body As String, postedFile As HttpPostedFile)
    Using mm As New MailMessage(from, [to])
        mm.Subject = subject
        mm.Body = body
        If postedFile.ContentLength > 0 Then
            Dim fileName As String = Path.GetFileName(postedFile.FileName)
            mm.Attachments.Add(New Attachment(postedFile.InputStream, fileName))
        End If
        mm.IsBodyHtml = False
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        smtp.EnableSsl = True
        Dim NetworkCred As New NetworkCredential(from, password)
        smtp.UseDefaultCredentials = True
        smtp.Credentials = NetworkCred
        smtp.Port = 587
        smtp.Send(mm)
    End Using
End Sub

Tuesday 24 May 2016

Asp.net Registration Page with Email Activation Page and Login Page


How to make Registration and Login Page in ASP.NET


ASP.NET Tutorial - How to Create a Login website - Validation Controls -Registration Page - Part 1


C# - Insert ,Update ,Delete


ASP.NET Tutorial 1- Introduction and Creating Your First ASP.NET Web Site


Razor - C# Loops and Arrays

For Loops

If you need to run the same statements repeatedly, you can program a loop.
If you know how many times you want to loop, you can use a for loop. This kind of loop is especially useful for counting up or counting down:

<html>
<body>
@for(var i = 10; i < 21; i++)
    {<p>Line @i</p>}
</body>
</html>

For Each Loops

If you work with a collection or an array, you often use a for each loop.
A collection is a group of similar objects, and the for each loop lets you carry out a task on each item. The for each loop walks through a collection until it is finished.
The example below walks through the ASP.NET Request.ServerVariables collection.

<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
    {<li>@x</li>}
</ul>
</body>
</html>

While Loops

The while loop is a general purpose loop.
A while loop begins with the while keyword, followed by parentheses, where you specify how long the loop continues, then a block to repeat.
While loops typically add to, or subtract from, a variable used for counting.
In the example below, the += operator adds 1 to the variable i, each time the loop runs.

<html>
<body>
@{
var i = 0;
while (i < 5)
    {
    i += 1;
    <p>Line @i</p>
    }
}

</body>
</html>

Arrays

An array is useful when you want to store similar variables but don't want to create a separate variable for each of them:

@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai")+1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}

<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>

Difference between ListView and GridView

ListView
GridView
It was introduced with Asp.Net 3.5.
It was introduced with Asp.Net 2.0.
Template driven.
Rendered as Table.
Built-in supports for Data grouping.
Need to write custom code.
Built-in supports for Insert operation.
Need to write custom code.
Provides flexible layout to your data.
Need to write custom code.
Performance is fast is compared to GridView.
Performance is slow as compared to ListView.

Difference Between GridView and DataGrid and ListView

GridView
DataGrid
It was introduced with Asp.Net 2.0.
It was introduced with Asp.Net 1.0.
Built-in supports for Paging and Sorting.
For sorting you need to handle SortCommand event and rebind grid required and for paging you need to handle the PageIndexChanged event and rebind grid required.
Built-in supports for Update and Delete operations.
Need to write code for implementing Update and Delete operations.
Supports auto format or style features.
This features is not supported.
Performance is slow as compared to DataGrid
Performance is fast as compared to GridView.

Monday 23 May 2016

MVC Sending Email

Create Action

The next step is to create an Action method that takes care of sending the email. Let us create a new class called Emailer.java with the following contents.
package com.tutorialspoint.struts2;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;

public class Emailer extends ActionSupport {

   private String from;
   private String password;
   private String to;
   private String subject;
   private String body;

   static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }

   public String execute() 
   {
      String ret = SUCCESS;
      try
      {
         Session session = Session.getDefaultInstance(properties,  
            new javax.mail.Authenticator() {
            protected PasswordAuthentication 
            getPasswordAuthentication() {
            return new 
            PasswordAuthentication(from, password);
            }});

         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO, 
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(body);
         Transport.send(message);
      }
      catch(Exception e)
      {
         ret = ERROR;
         e.printStackTrace();
      }
      return ret;
   }

   public String getFrom() {
      return from;
   }

   public void setFrom(String from) {
      this.from = from;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getTo() {
      return to;
   }

   public void setTo(String to) {
      this.to = to;
   }

   public String getSubject() {
      return subject;
   }

   public void setSubject(String subject) {
      this.subject = subject;
   }

   public String getBody() {
      return body;
   }

   public void setBody(String body) {
      this.body = body;
   }

   public static Properties getProperties() {
      return properties;
   }

   public static void setProperties(Properties properties) {
      Emailer.properties = properties;
   }
}
As seen in the source code above, the Emailer.java has properties that correspond to the form attributes in the email.jsp page given below. These attributes are
  • from - The email address of the sender. As we are using Google's SMTP, we need a valid gtalk id
  • password - The password of the above account
  • to - Who to send the email to?
  • Subject - subject of the email
  • body - The actual email message
We have not considered any validations on the above fields, validations will be added in the next chapter. Let us now look at the execute() method. The execute() method uses the javax Mail library to send an email using the supplied parameters. If the mail is sent successfuly, action returns SUCCESS, otherwise it returns ERROR.

Create main page

Let us write main page JSP file index.jsp, which will be used to collect email related information mentioned above:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Form</title>
</head>
<body>
   <em>The form below uses Google's SMTP server. 
   So you need to enter a gmail username and password
   </em>
   <form action="emailer" method="post">
   <label for="from">From</label><br/>
   <input type="text" name="from"/><br/>
   <label for="password">Password</label><br/>
   <input type="password" name="password"/><br/>
   <label for="to">To</label><br/>
   <input type="text" name="to"/><br/>
   <label for="subject">Subject</label><br/>
   <input type="text" name="subject"/><br/>
   <label for="body">Body</label><br/>
   <input type="text" name="body"/><br/>
   <input type="submit" value="Send Email"/>
   </form>
</body>
</html>

Create Views

We will use JSP file success.jsp which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Success</title>
</head>
<body>
   Your email to <s:property value="to"/> was sent successfully.
</body>
</html>
Following will be the view file error.jsp in case of an ERROR is returned from the action.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Error</title>
</head>
<body>
   There is a problem sending your email to <s:property value="to"/>.
</body>
</html>

Configuration Files

Now let us put everything together using the struts.xml configuration file as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="emailer" 
         class="com.tutorialspoint.struts2.Emailer"
         method="execute">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>

   </package>

</struts>
Following is the content of web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>