Monday 27 December 2010

SMTP/POP3 Settings for GMAIL, HOTMAIL, YAHOO, AOL, AIM

Gmail:
Incoming Mail server (POP3): pop.gmail.com
Port Number: 995
Outgoing Mail server (SMTP): smtp.gmail.com
Port number: 995
The Google Gmail SMTP Server requires an encrypted connection (SSL) on port 465.

HOTMAIL:
Incoming Mail server (POP3): pop3.live.com
Port Number: 995
Outgoing Mail server (SMTP): smtp.live.com
Port number: 25
The HOTMAIL SMTP Server requires an encrypted connection (SSL) on port 995 and even on 25.

YAHOO!!:
Incoming Mail server (POP3): Required Yahoo!! Plus account
Port Number: Required Yahoo!! Plus account
Outgoing Mail server (SMTP): smtp.mail.yahoo.com
Port number: 587

AOL/AIM:
Incoming Mail server (POP3): imap.aol.com
Port Number: 143
Outgoing Mail server (SMTP): smtp.aol.com
Port number: 587

Sample code OUTGOING:
SmtpClient sC = new SmtpClient("smtp.gmail.com");
sC.Port = 587;
sC.Credentials = new NetworkCredential(“USERNAME”,”PASSWORD”);
sC.EnableSsl = true;
sC.Send(mM);

Sample code INCOMING:
Pop3 pop3 = new Pop3()
pop3.ConnectSSL("pop3.live.com", 995);
pop3.Login("USERNAME", "PASSWORD");
List<string> uids = pop3.GetAll();
for (int i = totalMesg - 1; i >= 1; i--)
{
IMail email = new MailBuilder().CreateFromEml(pop3.GetMessageByUID(uids[i]));
Console.WriteLine(email.TextData.ToString());
Console.WriteLine(email.Subject);
Console.WriteLine(email.Sender.ToString());
Console.WriteLine(email.Date.ToString());

}
pop3.Close();

Feel Free to Ping me for any kind of help and support!! Thanks!!
~jawed

Sunday 26 December 2010

Force your Thread to start in Single-threaded apartment state

Use the below piece of code if you want to start your thread from main thread passing multiple parameters to that thread:

//by default this thread will start in MTA(Multi Apartment state)
string firstValue;
int secondValue;
bool thridValue;
//create an thread
Thread myAutomationThread;
// The delegate to call.
ThreadStart ts = new ThreadStart(delegate() { callMyFun(firstValue,secondValue,thirdValue); });
// The thread.
myAutomationThread = new Thread(ts);
// Run the thread.
myAutomationThread.Start();
----------
Now if you want to start the same thread in Single apartment state then just add the below line of code.
(We need to start the thread in STA because WATiN will run in STA mode only)

myAutomationThread.SetApartmentState(ApartmentState.STA);

The whole piece of code will look like this:

Thread myAutomationThread;
ThreadStart ts = new ThreadStart(delegate() { callMyFun(firstValue,secondValue,thirdValue); });
myAutomationThread = new Thread(ts);
myAutomationThread.SetApartmentState(ApartmentState.STA);
myAutomationThread.Start();

~Jawed

Download QC OTA API Reference Handbook /Documentation:

Download QC OTA API Reference Handbook /Documentation:

If you are looking for OTA (Open Test Architecture APU provided by hp QC then your search will end here.
I will explain you easy way to download API references details from QC.
a. Login to your QC
b. At Top most corner click on Help Link
c. From the pop-up window select Documentation Library as shown in below figure.



d. As soon as you will select above option a window will appear.
e. Select an option: HP QUALITY Center Open Test Architecture API reference Online
f. Click on online link next to the mentioned text
g. Save the references documentation at your drive.
h. Shown in below figure.


Hope this would be helpful !!

Thanks,

Md. Jawed

Log Visitors details using c#

Recently I have developed one application for the automation. It was web application.
I wanted to track the visitor visited or used my application and then store all the visitors information in "*.csv" file.
For that purpose I have used below code :

try
{
string strVisitorLogLocation=”C://VisitorsLog.csv” ;
string strIpAddress =Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
{
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
}

string hostName = Dns.GetHostByAddress(strIpAddress).HostName;
StreamWriter wrtr = new StreamWriter(strVisitorLogLocation, true);
wrtr.WriteLine(DateTime.Now.ToString() + "," + strIpAddress + "," + hostName + "," + Request.Url.ToString());
wrtr.Close();
}

catch (Exception ex)
{
//
}

you can use this snipet of the code to get the visitor details like hostname,ipaddress of visitor machine and which all pages he is visited on you application. Thanks!!
~jawed.

Monday 15 November 2010

Compare two Images File Using C#

Compare two Images File Using C#

In this post i m going to explain how to compare two images files using C#.
which would be very useful while performing Automation for checking whether two taken screen shot of web pages are same or not.

Below is the Code snippet which i have used for my automation purpose.

public void compareImages()
{
//First Image files
string Image1Location = @"C:\Pictures\For Website\DSCN0444.JPG";
//Second Image File
string Image2Location = @"C:\Pictures\For Website\DSCN0444.JPG";
try
{
string imageRef1, imageRef2;
//First Image BitMap
Bitmap img1Bitmap = new Bitmap(Image1Location);
//Second Image BitMap
Bitmap img2Bitmap = new Bitmap(Image2Location);
//Keep The Count of Pixel
int count1Pix = 0;
int count2Pix= 0;
//Decison whether Images are same or not
bool flag = true;
//Compare by Width
if (img1Bitmap.Width == img2Bitmap.Width)
{
//Compare by Height
if (img1Bitmap.Height == img2Bitmap.Height)
{
for (int i = 0; i < img1Bitmap.Width; i++)
{
for (int j = 0; j < img1Bitmap.Height; j++)
{
imageRef1 = img1Bitmap.GetPixel(i, j).ToString();
imageRef2 = img2Bitmap.GetPixel(i, j).ToString();
if (img1_ref != img2_ref)
{
count2Pix++;
flag = false;
break;
}
count1Pix++;
}
;
}
}
else
{
MessageBox.Show("Images are of Different Height");
}
}
else
{
MessageBox.Show("Images are of Different Width");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

if (flag == false)
MessageBox.Show("Image "+Image1Location+"and "+ Image2Location+"are not same , total wrong pixel found " + count2Pix );
else
MessageBox.Show("Image " + Image1Location + "and " + Image2Location + "are same!! Thank you");
}


Thanks,
Md.Jawed
jawed.ace@gmail.com

Sunday 14 November 2010

How to Read File Name from Pen/Removable derives using C#

How to Read Data from Pen/Removable derives using C#

In this post I would love to explain about how to read data or files from Removal derives/Pen drives etc.
Let me explain the scenario where I need this code to execute my automation.
Actually there was a scenario where I need to take the screen shot of the printer panel or web page and I have to compare that screen shot with predefined images stored in removal derives or pen drives.

Then let me share the code snippet which I have used to execute my purpose.
Public string getFilelocation(string imagename)
{
try
{
//go through all the driver
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
//check whether the driver is readonly or not
if (drive.IsReady)
{
//verify that the deriver is removable only
if (drive.DriveType.ToString() == "Removable")
{
//read the contents of the removable drive
//check whether folder exit or not
if (Directory.Exists(drive.Name + "DCIM\\100HPAIO"))
{
//get the path of the folder
driverPath = drive.Name + "DCIM\\100HPAIO";
//get all the files available in that folder
string[] fileNames = Directory.GetFiles(driverPath);
if (fileNames.Length > 0)
{
foreach (string filepath in fileNames)
{
String imageName= Path.GetFileName(filepath);
If(imageName==ImageNameTaken)
{
retrun filepath;
}
}

} //end of checking file path in USB

}

}
}
return “FileNot Found”;

}
catch (Exception ex)
{

return ex.Message;
}
}
}

Hope that would be useful.
Thanks,
Md. Jawed

Thursday 11 November 2010

*.CFG file used in Printer

*.CFG file used in Printer
Since feb 2010 I m working on Web connected printer which hp has launched in April 2010 and in july launched ePrint functionality in Printer. Now we are targeting all the hp printers families to be enabled with ePrint and web connected.
After this the printer market would not be limit only upto fax,scan and print images. We can do lots of things over the printer.
To read more about ePrint and web connected printers just wait for my next blogs.
Over all it is nice experience to work on this project. Now days most of time I m concentrating on debugging the servers , sharing my knowledge with other members, performing automation, building Simulator and setting up stacks for various press event across the world .
Now come to the point.
While doing development and Testing we need to test and verify the code or build on printer whether it is working correctly or as expected against various Build configurations. Generally we are deploying the various build on various server configuration and we need to test or verify the build on all the stacks/servers. And it’s not possible to hard code the server details in Firmware of printer but for the customer it would be hardcoded in Firmware (cuz Production environment is fixed)
To overcome this issue we are using secure.cfg file copied in SD card and inserted into Printer to perform registration on various servers configuration.
I have seen few new testers frequently using *.cfg file in printer without knowing how it is working and why we needs this *.cfg file.


Then I started sharing my learning with them. Today, I thought to put the same contents over here so that the knowledge would not be limit up to my team only.,
Here is what I have shared with them:
edffef

1. What is this cfg file.

Ø A file that contains data about a specific user, program, computer or servers. Used for a myriad of reasons, configuration files are generally read at startup by the Printer FW/operating system as well as by applications in order to customize the environment for the user.
In the Windows world, especially the earlier versions of Windows, .INI (initialization) files have been used. In Java, configuration data are stored in properties files. The Registry is also a storehouse of configuration data, which is widely used.


Ø A file with a .cfg extension is usually a configuration file. The file will be used by an application to load all the configuration settings. There is no standard format for a .cfg file and how it can be modified will differ from application to application.
Configuration(*.cfg) files typically store data in a key=value structure, which means each item of data (the key) has a name, and its value is its contents.

For example:-

Typical secure.cfg file structure:
[offramp]
offramp_ip=1.2.3.4

offramp_security=on
cert_validation=off
production_server=0
[sips]
sips_home_url=https://ec2-12.23.34.56.compute-1.amazonaws.com:443

allow_security=1
cert_validation=0

2. How *cfg is working in Printer.

Ø Just take the scenario where FW is hard coded with Server details and user has inserted CFG file in the printer.
As soon as user will insert the SD card in the printer, the printer would read the SD card and will check whether any secure.cfg file is present or not. If it content then while doing registration the printer will read that CFG file from SD card and will refer that server details.

Let me explain this through flow chart in broader way:


We need secure.cfg file inserted in to printer to point the printer on various server.

Hope it will be usefull for you. thanks!!

~jawed

Wednesday 10 November 2010

LogonDialogHandler In WATiN

For the automation of some webapplication we have to provide usrname and password in logon poup windows to access that website. For example if you try to access Nagios Monitoring tool it will ask for username and password as popup windows shown in below figure.


To handle this secnario in automation we can use LogonDialogHandler provided in watin framework.

Below is the code snippet to hanlde scenario:

Try
{
Browser browser = new IE();
WatiN.Core.DialogHandlers.LogonDialogHandler ldh = new WatiN.Core.DialogHandlers.LogonDialogHandler(“UserName”,”Password”);
browser.DialogWatcher.Add(ldh);
browser.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.Maximize);

browser.GoTo(“NagiosUrl”);
}
catch (Exception ex)
{

//Handle Exception

}

Embedded Images in Outlook using C#

Embedded Images in Outlook using C#
To monitor all the Host and services we are using Nagios application.
So at some point we felt that why not we should have some kind of application which will take the screen shot of this Nagios with different hosts and send all the screenshots embedded in to outlook instead of as attachment to a group of user.
or
There was an requirement in my project where I need to take the screen shot of the website at regular interval and embedded all the images in outlook as send that email to group of people.
To achieve above requirement I used WATiN ,C# and outlook instance.
Below is the Rough idea how I have done that:
1. Open the Nagios URL using WATiN
2. Login to the web site Uisng WATiN
3. Navigate the Host webpage
4. Take the Screen shot the web page and store at local drive
5. Move through all the host web page and take the screen shot using WATiN
6. Embedded in to Outlook instance and send that email.



Below is the code snippet which I have used to Embedded the images in outlook:

public void Sendemail(string mainUrl,string strToEmail, string[] strFileLocationForAttachamnet)

{

try

{
// Create the Outlook application.

Outlook.Application oApp = new Outlook.Application();

Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem

Outlook.OlItemType.olMailItem);

// Set HTMLBody.

string emailSubject = "**** Auto Generated Email:Nagios Screen Shot Update for

" + mainUrl + " ****";

String sDisplayName = "MyAttachment";

int iPosition = 50;// (int)oMsg.Body.Length + 1;

int iAttachType =(int)Outlook.OlAttachmentType.olByValue; \

string htmlStart ="<html><body><h5><Font

Color=Purpel>Hi,<br/>Please Find below The screen shot of Host

Status as of "+DateTime.Now +"<br/></h5>"; string body=string.Empty;

int i = 1;

foreach (string filelocation in strFileLocationForAttachamnet)

{

if (filelocation != null)

{

Outlook.Attachment oAttach = oMsg.Attachments.Add(filelocation, iAttachType, iPosition,

sDisplayName);

body += "<h4>["+i+"."+"]</h4><img

src=\"cid:" + oAttach.FileName

+"\" /><br/>";

i++;

}

}

string wholeBody = htmlStart + body + "<h5><Font

Color=Purpel>Note:if no Red color means none of the services are

in critical stage.<br/>Regards,<br/>Md.

Jawed<br/>(jawed.md@hp.com)

lt;br/></h5></body></html>";

oMsg.HTMLBody = wholeBody;
// Set the subject.

oMsg.Subject = emailSubject;

// Add a recipient.

Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;

Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(strToEmail); oRecip.Resolve();
// Send

oMsg.Send();

// Clean up.

oRecip = null;

oRecips = null;

oMsg = null;

oApp = null;

}

catch (Exception ex) {
}
}

Thanks,
Md. Jawed

Thursday 1 April 2010

Read data from XML and store into Data Set Using C#

I am using XML file as config file in my automation tool which I have developed to store all the inputs/settings/run time config value etc etc. Because it easy for manual guys also to just open XML file in Notepad and alter the setting based on their requirement and it’s easy to maintain also.

Below is the code which I am using to Read data from XML file and store in to Data set for further use.

//Local vaible to get xml path
string xmlPath=”Inputs.xml”;
//Read all the value to the xml read command
System.IO.FileStream fsReadXml = new System.IO.FileStream(xmlPath,
System.IO.FileMode.Open);
//Declare a dataset to hold all the XML value
DataSet ds = new DataSet();
try
{
//Read the value from XML reader to the dataset
ds.ReadXml(fsReadXml);

}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//Close the reader.
fsReadXml.Close();
}
//your dataset (ds) would be having all the data stored from XML file.

Thanks,
Md.Jawed

Wednesday 31 March 2010

Update the Excel sheet using c#

Some time I got the requiremnt where I need to update the excel sheet corresponding to testcases through the code whether the test case is failed or passed while automation is running and send the updated testcases excel with current status of testcases through the email at the end of automation code.
i hope that this would be very usefull for you.

Below is the code for that purpose :
----------------------------------------------------------------
//write to excel sheet
public void writeToExcelsheet(int rowNumber, string status)
{
try
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = Program.excelSheetDeclaration;
using (DbCommand command = connection.CreateCommand())
{
command.CommandText =
"Update [sheet1$] Set Status =\"" + status + "\" WHERE TestCaseID ="+rowNumber;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (Exception ex)
{
//
}
} //end of writeToExcelsheet method.
----------------------------------------------------
Thanks!!

Tuesday 30 March 2010

How to Read data from Excel sheet using DataSet

While coding the Automation the situation came that we need to read data from excel sheet and store at one place to use that data through out the code and storing the data from excel sheet to the data set is a good option. Reading the data one by one from excel sheet would impact the performance of the automation code.
So below is the code which will read the data from excel sheet and would store in to dataset.
--------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
//
namespace ReadFromExcel
{
//Class to read excel sheet and store in to dataset
class Program
{
static void Main(string[] args)
{
//Local variable to store the excelsheet location
string excelSheetLocation = "c:\\TestCases.xls";
//Local variable to store the connection string to talk with excel sheet
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelSheetLocation + ";Extended Properties=Excel 8.0";
//Declare a dataset
DataSet myDataSet=new DataSet();
//Declare oledb connection
OleDbConnection con = new OleDbConnection(excelConnectionString);
//Open the connection to communicat with excel sheet
con.Open();
//Create Dataset and fill with imformation from the Excel Spreadsheet for easier reference
OleDbDataAdapter myCommand = new OleDbDataAdapter(" SELECT * FROM [sheet1$]", con);
//filled the dataset with the data of excel sheet
myCommand.Fill(myDataSet);
//close the connection
con.Close();
//show the data on console window from dataset
//Total Number of rows in excel sheet
int totalRow = myDataSet.Tables[0].Rows.Count;
//trace through each rows
for (int i = 0; i < totalRow; i++)
{
//trace through each coloumn
for (int j = 0; j < myDataSet.Tables[0].Columns.Count;j++ )
{
//Show the data on to console window
Console.WriteLine(myDataSet.Tables[0].Rows[i][j].ToString());
} //end of for loop
} //end of for loop
} //end of main
} //end of class
} //end
----------------------------------------------------------------------------------------------
Thanks!!