Thursday, December 27, 2007

Disable Selection in Web page

Thursday, November 29, 2007

Writing all data from Dataset to XML (with null value too).

Imports Microsoft.VisualBasic

Imports System.Data


Public Class DatasetToXML


Dim con As New

Public Function DS2XML(ByVal
ds As DataSet) As

Dim xs As New

xs.Indent = True

Dim xw As System.Xml.XmlWriter =

xw.WriteStartElement("DF_TRUCK") 'Name
of schema

For Each dt As DataTable In ds.Tables

Each dr As
DataRow In ds.Tables(dt.TableName).Rows


i As Integer =
0 To ds.Tables(dt.TableName).Columns.Count - 1

IIf(IsDBNull(dr.Item(i)), String.Empty,








End Function

End Class

Wednesday, August 8, 2007

Solution of MsgBox in

You can't use MessageBox
in ASP.NET. You don't have any graphical user

interface, so there is nowhere that you can display the messagebox.

If you were allowed to use a messagebox in ASP.NET, it would pop up on

the web server where noone would see it, and IIS
would hang indefinitely

waiting for someone to click it.

Remember that this code is running on
the web server in a process that is not running as the currently logged on
(to the server) user. Therefore the process will be running under its own
Window Station, and will not be able to interact with the desktop in any way.
Consequently, you cannot display a MessageBox on the
server without setting the flags to indicate that you want to display it on the
currently logged in user's Window Station (effectively the
default desktop).

Typically, displaying message
boxes on servers is regarded as a very bad thing, as a lot of servers are
locked in computer rooms and there is no user to dismiss them. Therefore, are
you really sure that you want to do this, or would you really prefer to display
a message box on the browser (using client-side JavaScript)?

Here I
am showing another way to display the MsgBox in page.

shows an alert on page_load (or else).

No need to create an instance of the class.


Protected Sub Page_Load(ByVal
sender As Object, ByVal e As System.EventArgs)
Handles Me.Load


End Sub

Note that you won't need to 'format' special characters like \ and " etc..

Public Shared Sub Client_Alert_OnLoad(ByVal sMessage As String,
Optional ByVal sURL As
String = "")

On Error Resume Next

Dim str As String

Dim P As System.Web.UI.Page
= CType(System.Web.HttpContext.Current.Handler,

Dim sb As New StringBuilder(Len(sMessage) * 5)

sMessage = sMessage.Replace(Chr(0),

For Each c As String In sMessage
: sb.Append("\x" & Right("0"
& Hex(Asc(c)), 2)) : Next

str = vbCrLf & "<script language=javascript>"
& vbCrLf

str = str & " alert('" & sb.ToString &amp; "');" & vbCrLf

If Len(sURL) > 0
Then str = str & "
window.location='" & sURL &amp; "';" & vbCrLf

str = str & "</script>" & vbCrLf

P.ClientScript.RegisterStartupScript(P.GetType, "", str)

End Sub


cmsgbox.Client_Confirm_OnButton(Me.Button1, Chr(34)
& "hello world \/-=" & Chr(34)
& vbCrLf & "ok to format c:?")

Public Shared Sub Client_Confirm_OnButton(ByRef oButton As System.Web.UI.WebControls.Button, ByVal
sMessage As String)

On Error Resume Next

Dim str
As String

Dim sFunction
As String = ("msgbox_confirm_" & oButton.ClientID).Replace("$", "_")

Dim sb
As New StringBuilder(Len(sMessage)
* 5)

= sMessage.Replace(Chr(0),

For Each c As String In sMessage : sb.Append("\x"
& Right("0" & Hex(Asc(c)), 2)) :

= vbCrLf & "<script language=javascript>" & vbCrLf

= str & "" & vbCrLf

= str & "function " & sFunction &amp; "()" & vbCrLf

str = str
& " if ( !window.confirm('"
& sb.ToString &amp; "') ) {"

= str & " window.event.returnValue
= false;" & vbCrLf

= str & " return 0;" & vbCrLf

= str & " }" & vbCrLf

= str & "}" & vbCrLf

= str & "</script>" & vbCrLf

= "javascript:" & sFunction
&amp; "();"

oButton.Page.ClientScript.RegisterStartupScript(oButton.Page.GetType, sFunction, str)

End Sub

Thursday, July 26, 2007

Sending E-Mail from your .NET application using your GMail Account


Most independent developers like to include a msg sending feature in their application.
Well atleast I tried to.. Of course it is not a problem for a user with a smtp server
access or a registered domain with an smtp server access. But unfortunately I had
none of them. I use msn, gmail and yahoo for my mailing needs. Unfortunately yahoo
does not offer smtp or pop access for their general/basic/free users. And msn it
is not that reliable coz I was expecting a lot of mails to be sent and also to recive
and as far as I know they also donot give you pop/smtp access!.

Typical Example you will find in internet

So I really Hunted for a code segment that help me use my free gmail account to
send E-MAIL from my .NET account.
is a complete referance library and FAQ's regarding to the System.Web.Mail
namespase. And my code is basically I joined different pieces together. And Came
up with succes. Normally you will find thousands of sites offering the code below
which has a very little use. Like

MailMessage mail = new MailMessage();
mail.To = "";
mail.Bcc = ";";
mail.From = "your email or name";
mail.Subject = "your subject";
mail.Body = "your subject";
SmtpMail.SmtpServer = ""; //your
real server goes here or

//you can add the address like ""

Well most smtp server require authentication and sometimes SSL connection so what
then? The code above is USELESS. So what are the things you need
to add? There you go.

//This is fully working tested code. Copy and paste the code
//Edit some parts(UserName, password) and ENJOY!
public string sendMail (string from, string to, string cc, string bcc, string subject, string body) {
// Mail initialization
MailMessage mailMsg = new MailMessage();
mailMsg.From = from;
mailMsg.To = to;
mailMsg.Cc = cc;
mailMsg.Bcc = bcc;
mailMsg.Subject = subject;
mailMsg.BodyFormat = MailFormat.Text;
mailMsg.Body = body;
mailMsg.Priority = MailPriority.High;
// Smtp configuration
SmtpMail.SmtpServer = "";
// - use smtp authentication
mailMsg.Fields.Add("", "1");
mailMsg.Fields.Add("", "");
mailMsg.Fields.Add("", "mypassword");
// - use port 465 or 587
mailMsg.Fields.Add("", "465");
// - use STARTTLS (some call this SSL)
mailMsg.Fields.Add("", "true");
// try to send Mail
return "";
catch (Exception ex)
return ex.Message;

How to use

Copy the above methods and paste in visual studio IDE or any text editor you use.
Add a referance to System.Web or System.Web.Mail dll change your account
info like your mail address, password, etc and Enjoy

Explanation to the code

So what is happening on the example? See

step 1: Create a mail msg object and asign the basic parts like from, To,
cc, bcc subject, body.

step 2: Add some config settings in fields collection of the mailMessage
object. Type of authentication we use basic authentication and your user name, password,
smtp servers port number that you will be using. for example:

//basic authentication
mailMsg.Fields.Add("", "1");
//sender email address
mailMsg.Fields.Add("", "");
//plaintext password.
//you can encrypt your password and keep in a config file
when you parse just decrypt it

mailMsg.Fields.Add("", "mypassword");
// port number - use port 465 or 587. use anyone
of them

you can even make some grouping so different groups use different port to share
the load on server

mailMsg.Fields.Add("", "465");

gmail username require full gmail address as username and you can use /connect
to any of the port.

step 3: This is the coolest and most important part that I had a lot of time
to spend to discover.

mailMsg.Fields.Add("", "true");
//Cool. Ha? Donot Change! This part is a must if you want to
access GMAIL's SMTP server

This line says/declares that your smtp server requires SSL connection which is very
much true/necessary for accessing to gmail's SMTP server.

step 4: assign the smtp server name in System.Web.Mail.SmtpMail class's Smtp
server object like:

SmtpMail.SmtpServer = "";

you can also set the priority of your mail by

mailMsg.Priority = MailPriority.High;// MailPriority is an
enum. It has High,Low, Normal option

step 5: call the send method of System.Web.Mail.SmtpMail. e.g.


.NET2.0 Version

Some Changes are required for .NET v2.0 as .NET2.0 Mail is much organised and stable
and so many extrafeatures. So In the Update I am including .NET2.0 version of my

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
//Mime is Not necerrary if you dont change the msgview and

//if you dont add custom/extra headers
using System.Threading;

namespace SendMailUsingGmail
public partial class Form1 : Form
public Form1()

static bool mailSent = false;

public void SendMail()
//Builed The MSG
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("", "One Ghost",System.Text.Encoding.UTF8);
msg.Subject = "Test mail using .net2.0";
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = "This is my msg Body";
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.High;

//Add the Creddentials
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("", "SecretPass");
client.Port = 587;//or use

client.Host = "";
client.EnableSsl = true;
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
object userState=msg;
//you can also call client.Send(msg)
client.SendAsync(msg, userState);
catch (System.Net.Mail.SmtpException ex)
MessageBox.Show(ex.Message, "Send Mail Error");

void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
MailMessage mail = (MailMessage)e.UserState;
string subject = mail.Subject;

if (e.Cancelled)
string cancelled = string.Format("[{0}] Send canceled.", subject);
if (e.Error != null)
string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
MessageBox.Show("Message sent.");
mailSent = true;

private void button1_Click(object sender, EventArgs e)

Limitation of this code

This code may/will not work with .NET framework v1.0. Because the MailMessage object
of .NETv1.0 does not have the MailMessage.Fields Collection. This was added
in .NETv1.1. So it works fine with .NETv1.1 and v2.0.


The send method does not return anything. But you can add some mechanism(like counter)
to keep track of send message or even keep the return type of your method as a mailmessage
type so that u can save to database for security reasons.