Sending Email Asynchronously

Posted by Venkat | Labels: , ,

Good Morning to Everybody this is my First article.
Now i am going to see how to send email Asynchronously, actually we send email normally using asp.net Example check here..
Send Email Using ASP.NET

By default smtpClient has one method called SendAsync to send an email ansynchronously. so if you sending an email normally it will take some time for each mail sent. But if you send an email Asynchronously it will not wait for each mail sent it will do the other process , while mail sending is done at background process.
So Here is the code.

//creating mail message object
 MailMessage mailMessage = new MailMessage();
 mailMessage.From = new MailAddress("venkat@gmail.com");
 mailMessage.To.Add(new MailAddress("msdotnettechies@gmail.com"));
 mailMessage.CC.Add(new MailAddress("user1@gmail.com"));
 mailMessage.Bcc.Add(new MailAddress("user2@gmail.com"));
 mailMessage.Subject = "Email Checking Asynchronously";
 mailMessage.Body = "Email test asynchronous";
 mailMessage.IsBodyHtml = true;//to send mail in html or not

 SmtpClient smtpClient = new SmtpClient();//portno here
 smtpClient.Host = "smtp.gmail.com";
 smtpClient.EnableSsl = true ; //True or False depends on SSL Require or not
 smtpClient.Credentials = new NetworkCredential("yourGmail@gmail.com", "yourpassword");
 //smtpClient.UseDefaultCredentials = true; //true or false depends on you want to default credentials or not
 Object mailState = mailMessage;

 //this code adds event handler to notify that mail is sent or not
 smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
 try
 {
 smtpClient.SendAsync(mailMessage, mailState);
 }
 catch (Exception ex)
 {
 Response.Write(ex.Message);
 Response.Write(ex.StackTrace);
 }

// this is the event called on main method
void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
 MailMessage mailMessage = e.UserState as MailMessage;
 if (e.Cancelled || e.Error != null)
 {

 Response.Write(e.Error.Message);
 Response.Write(e.Error.StackTrace);
 }
 else
 {
 Response.Write("Email sent successfully");
 }
 } 
 

Ref :  http://jalpesh.blogspot.com/2010/02/how-to-send-mail-asynchronously-in.html

Sams Teach Yourself ASP.NET 3.5 in 24 Hours, Complete Starter Kit How to Train Your DragonHarry Potter Box Set

Logout issue : Copy the URL of the user page and paste user after logout show the page only IE has Issue

Posted by Venkat | Labels: , ,

When i working on the project ,i faced the issue - that i am sharing to u. ex: When the user login in to his account then do some navigation inside User page - at this stage I copied the URL then i Click Logout button. 

Once i logged out if i paste the Copied URL on that page it redirect to the user Page, when i do some navigation (or clicking any button on that page ) its has been redirect to Login page , but this should not occur  like this if i paste the URL it will directly redirect to the Login page only.This issue will not occur on Mozilla , IE 8 version. it occurs only on IE  browser.

Even if  I set the Session on page_load event but no use. So the thing is Cache ie: the page has been cached stored on Client Browser, so we need to disable the cache.

So Add this line on Master Page inside the Head Tag.

 <meta http-equiv="PRAGMA" value="NO-CACHE"></meta>
<meta content="Mon, 01 Jan 1990 12:00:00 GMT" http-equiv="Expires"></meta>



 
 

uploading text and numeric data from an excel file shows NULL Value

Posted by Venkat | Labels: , ,

Good Morning to everyone

I was working with one of the project , where i had the task of uploading excel ie: Read the Excel data to Dataset ie: from DataSet I am going to store the each field value to DB, so the excel sheet may contain numbers ,or string ,.. by default the Excel sheet  accept  the data based on the first rows of excel sheet.

If the first row and first column will be string - so further the whole first rows and first columns accept strings, if there is any Numeric found  on the first rows and first columns it consider as NULL ie: Empty value , as the same for Numeric also so it may also contain alphanumeric on some cells.

So while we read the Excel sheet  these problems are arise. then we tried to select all cell ie: full excel sheet -> Right Click on the Excel sheet - > format Cells - > Choose String - > click ok .Then I upload this Excel sheet to Read the Data.

Why we change the Format cell  to String means if we set it as string it will accept as both numeric , strings , or alphanumeric - so i am going end it up by doing this.

But the problem arises again - it works that time correctly after few day the same problem occurs, then i do some research or googled and came up with a solution :

The short answer is "IMEX=1" 

You have to apply this on Connection String

To connect to an excel file within ADO.NET use the "System.Data.OleDb" provider  a connection string similar to:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Sample.xls";Persist Security Info=False;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1" 

 Thanks for All. 

 

window.open method

Posted by Venkat | Labels: , ,

Window.open method in asp.net - this is used in javascript to open a page on new window.
through this you can hide the menubar ,set the width and hieght of the popupwindow,status,toolbar,resizable etc., for this you can either set the value is 0 | 1 or yes | no

Example

window.open('http://msdn.microsoft.com', '', '');");

Suppose if you want to do on code behind check this code :

Here i have mentioned widht , height of the window ,top and left , menubar,toolbar,
location, resizable, scrollbars
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language="javascript">");
sb.Append("window.open('popuop.aspx', 'CustomPopUp',");
sb.Append("'width=1020, height=750, left=0, top=0, menubar=no, toolbar=no, resizable=no, status=no, location=no, scrollbars=yes');<");
sb.Append("/script>");
Type t = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered(t, "PopupScript"))
{
     Page.ClientScript.RegisterStartupScript(t, "PopupScript", sb.ToString());
 }


If you want to open a new window through in-line code try this.

   <img border="0" id="img_PopUp" onclick="window.open('../PopUp.aspx','custompopop','width=250,height=300,toolbar=no,menubar=no,statusbar=no,resizable=no,scrollbars=no,location=no, directories=no,copyhistory=no,left=250,top=250')" />
                                runat="server" src="../Images/Newwindow.png" style="width: 35px" />

Reference:


http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

Arithmetic Captcha

Posted by Venkat | Labels: , ,

In this post i am going to show how to work with Arithmetic CAPTCHA. Generally we used , Alpha or alphaNumeric Captcha on most of the site but some site like  ASP.SNIPPETS it shows ARITHMETIC CAPTCHA like 18 + 12 = ? so user have to give correct value then only it proceeds.

Here I am getting help from this site

http://www.knowlegezone.com/documents/80/Simple-ASPNET-CAPTCHA-Tutorial/

Which was in VB.NET so I would like to Written in C#, here I have been posted , On the Above link they used normal ASPX image to Generate the Image ie: 18 + 12 = .

So i written the code on Generic Handler File to improve the site performance.
By default Handler file does not Read or write the value to Session so we have to use like this

using System.Web.SessionState;

public class Captcha : IHttpHandler, IRequiresSessionState


suppose if we are going to read the Session value on HTTP Handler file

using System.Web.SessionState;
public class Captcha : IHttpHandler, IReadOnlySessionState

This is the full code for Captcha.ashx file

<%@ WebHandler Language="C#" Class="Captcha" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class Captcha : IHttpHandler, IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        Random num1 = new Random();
        Random num2 = new Random();
        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        int tAnswer = numQ1 + numQ2;
        context.Session["answer"] = tAnswer .ToString ();
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);
        Rectangle Rect = new Rectangle(0, 0, 100, 25);
        Grfx.FillRectangle(Brushes.Snow, Rect);
        Grfx.DrawRectangle(Pens.White, Rect);
        // Border
        Grfx.DrawString(QString, font, Brushes.Black, 0, 0);
        context.Response.ContentType = "Image/jpeg";
        bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bitmap.Dispose();
        Grfx.Dispose();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Here is the code if you are going to write it on Captcha.aspx page

Explanation was given on Comment itself. Write the below code on Page_Load Event

// Getting Random number
        Random num1 = new Random();
        Random num2 = new Random();

        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;

        // here we get the random number for the first and second numer - ie: shows the number in between the range.
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);

        //Total answer has been  stored it on String and assign to the Session["number"]
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        Session["answer"] = numQ1 + numQ2;

        // Here we create  Bitmap width - 85 and height - 25
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);

        // Setting the font name, size etc for the text that we have to write it on the image
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);

        // Here we specify  a Rectangle object of x , y co-ordinate , with width and height 
        Rectangle Rect = new Rectangle(0, 0, 100, 25);

        //Fill the color to the Rectangle
        Grfx.FillRectangle(Brushes.Snow  ,Rect);

        // Now Using Pen Object Drawing a rectangle
        Grfx.DrawRectangle(Pens.White, Rect);

        // Border - here drawing the string of the num1 and num 2, font size , type etc, font color , and x and y co-ordinate
        Grfx.DrawString(QString, font, Brushes.Black   , 0, 0);
        // Specify the Content type of the image - here i am using JPEG
        Response.ContentType = "Image/jpeg";

        // Save the image and show it on page using response object
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        //Dispose the object and release the resources
        bitmap.Dispose();
        Grfx.Dispose();

Google Custom Search

Posted by Venkat | Labels: , ,

Google Custome Search

Google provider Custom search - that can be integrated to our own site - to searh a text,keywords
inside our site.

This is the link go Through and add to your site.

http://code.google.com/apis/customsearch/docs/ui.html

Fetch DB to Xml then bind to Asp.net Server control

Posted by Venkat | Labels: , ,

Today I am going to see how to bind or get the Data from the DB to XML file. so XML is also a
Datasource to store the data or content and you can get the data from xml file easily,it also
improves server performance. ie: instead of creating connection and request the DB to fetch the data
, Getting the Data , Closing Connection. so this operation occurs multiple times or as per
user needs.

Now what i am doing here is , first get the Table Data From DB to the XML file.
first i had created one xml file called Test.xml - to place the Employee Tables Data.

Then OnButton_Click Event i have written the code to bind the data to XML file.

Ex: i am getting the Employee Table from DB bind to the XML file.

Here is the Code :

Include Namespace

using System.IO;
using System.Data.SqlClient;


protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand command = new SqlCommand();
        command.CommandText = "Select * from Employees";
        command.CommandType = CommandType.Text;
        command.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        da.Fill(ds, "Emp");
       
        // Get a StreamWriter object
        StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/Test.xml"), false);

        // Apply the WriteXml method to write an XML document
        ds.WriteXml(xmlDoc, XmlWriteMode .WriteSchema );
        xmlDoc.Close();

       
    }
After that - i am going to bind the all the employeename and empid to the Dropdownlist.

Here is the Code : so we get the emp details on the XML file , we have to retrieve the data
from the XML file using Dataset because - Dataset has two method ReadXML and WriteXML ie: able
to read or write the data from the XML.

so after read the data from XML to Dataset, now we have all the emp details on the Dataset ds,
. just bind as its to the Dropdownlist datasource.


 DataSet ds = new DataSet();

 ds.ReadXml(Server.MapPath("~/Testdo.xml"));

DropDownlist1.DataSource = ds;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();
suppose i want to filter the employees whose salary is greater than 20000

write like this

dt = ds.Tables[0];
  DataRow[] dr ;
        dr = dt.Select("salary >= '20000'");

 DataTable fDt = new DataTable();
        fDt.Columns.Add("empName");
        fDt.Columns.Add("empId");

 foreach (DataRow dr1 in dr)
        {
            DataRow newrow = fDt.NewRow(); 
            newrow[0] = dr1[0];  // here you have to give correct index for the empid or empname field name
            newrow[1] = dr1[1];
           

            fDt.Rows.Add(newrow);
        }

dropdownlist2.DataSource = fDt;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();

Creation Tooltip

Posted by Venkat | Labels: , ,

Good Friday to all.

Now i am going to show how to create  a Tooltip using Javascript there are many scripts,JQuery available to make the work easy and even we can design the tooltip stylish manner.

But finally i have worked with this sample , it shows tooltip , when u click on the Textbox - you can give your own font color, backcolor.

Here is the link Check it

http://lixlpixel.org/javascript-tooltips/

And its a dynamic tool tip..

http://blog.devarchive.net/2008/04/advanced-tooltip-control-aspnet-ajax.html

Here is the Screenshot

How to Create Nifty Round corner

Posted by Venkat | Labels: , ,

I have situation Create a Roundcorner for the table or div or panel ...
So in Ajax there is a built-in-control - RoundCornerExtender is available , but i have used that but i was not showing the round corner sometimes properly.

so i found this Nifty round corner was the good one, no image needed for the Round Corner.

Its full javascript., you can apply the round corner to div,panel,table etc..

Here is the Sample code

First you have to add Javascript on your page. You can get the javascript here ie: niftycube.js and niftycorner.css.

http://www.html.it/articoli/nifty/index.html

http://www.html.it/articoli/niftycube/index.html

You have to write code like this

if you use id use (#) , if you are going to use it for class user (.)


<script type="text/javascript">
window.onload=function(){
Nifty("div#box","big");
Nifty("Panel#" + '<%= contactUs_Panel.ClientID %>',"transparent");
Nifty("Panel.setround","big");
Nifty("Panel#" + '<%= callback_Panel.ClientID %>',"transparent");
Nifty("table.setround","big");

//Nifty("PopupControlExtender","big");
}
</script>


Validate Indian Mobile Number

Posted by Venkat | Labels: ,

Hi , Now i am going to discuss about how to validate a Indian Mobile Number.

First the Mobile Number field should not be null so for that - Add RequiredFieldValidator.

It should not accept any Aplhabets , or any special characters for this you have to write RegularExpression Validator to Accept only Numbers
EX:

Regex \d+


Atlast i have to check whether user entered Number is 10 digit or not and also it should be valid Mobile Number
Regex ^[9][0-9]{9}$


This Regex which first digit should be 9 then followed by 9 digits and totally it accept only 10 digits.

PayOffers.in