Tuesday, November 25, 2008

Overwrite the nAnt Property Value from Commnad Line

In order to change nAnt build file property from command line, set the overwrite attribute of the property to false.



When you execute nant from command line using

nant -D:ServerAddress=google.com

the ServerAddress is set to google.com

Wednesday, November 19, 2008

Read XML Elements using Selenium RC

In order to get XML element using Selenium RC (.NET client) I used the following strategy,


  1. Open XML document in webbrowser using

    selenium.Open(http://www.servername.com/my.xml);

  2. Use selenium GetText method (which returns the inner text of XML tag). I used XPATH expression to locate the tag inside XML document

    String myText = selenium.GetText("//plan[1]");


Thursday, November 13, 2008

Get nAnt Build File Property Attribute Programatically

In order to read nAnt build file and get the Property value I wrote the following code in C#.NET

static String GetNANTAttributeValue(String filePath, String tagName, String attribute1Name, String attribute1Value, String attribute2Name)
{
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(filePath);
XmlNodeList xmlNodeList = xmlDocument.GetElementsByTagName(tagName);
String result = "";
for (int i = 0; i < xmlNodeList.Count; ++i)
{
if (xmlNodeList[i].Attributes[attribute1Name].Value == attribute1Value)
{
result = xmlNodeList[i].Attributes[attribute2Name].Value;
break;
}
}
return result;
}
catch (Exception)
{
throw new Exception("Unable to Retrive XML Attribute, The tagName Provided: " +tagName+ " ");
}
}

Friday, September 19, 2008

Ignore NUnit Test at Runtime

In order to ignore the test at runtime for NUnit framework i used the following code


bool flag;

[Test]
public void Test01()
{
if (flag == flase)
{
Assert.Ignore();
}
}

Friday, August 22, 2008

Execute MySQL commands from console

Using --execute one can query SQL statement from console instead on entering MySql prompt


mysql --user=root --database= healthy-dev_development --execute="SELECT * FROM users where users.email='attestuser1@gmail.com' "

Thursday, August 21, 2008

List Columns of the table

To list the columns of the MySQL table use the following syntax

show columns from table_name;

Bring Data from two tables using SQL JOIN

select T1.id, T2.email from application_details as T1 JOIN users as T2 ON T1.user_id=T2.id where T2.name='attestuser1';

Gmail using Selenium RC


{
// Login to Gmail and get the link
try
{
selenium.Open("http://www.gmail.com"); // Open Gmail Webpage
selenium.WaitForPageToLoad(sel_TimeOut);
selenium.WindowMaximize();
if (selenium.IsElementPresent("//a[contains(text(),'Sign out')]")) // If Already logged on, logout first
{
selenium.Click("//a[contains(text(),'Sign out')]");
selenium.WaitForPageToLoad(sel_TimeOut);
}
selenium.Type("//input[contains(@id,'Email')]", inv_InviteEmailAddress); // Enter Gamil User Account. GAMIL account should be set with HTML view
selenium.Type("//input[contains(@id,'Passwd')]", inv_InviteEmailPassword); // Enter Gmail Password
selenium.Click("//input[contains(@name,'signIn')]"); // Click on Gmail Sign In button
selenium.WaitForPageToLoad(sel_TimeOut); // Wait for web page to load. If page dont load after timeout test is failed
Thread.Sleep(Int32.Parse(com_UserThinkTime)); // Time taken by user to take action after page is loaded
selenium.Click("//*[contains(text(),'" + inv_InviteEmailSubject + "')]"); // Click on email with subject as pointed by variable inv_InviteEmailSubject
selenium.WaitForPageToLoad(sel_TimeOut); // Wait for web page to load. If page dont load after timeout test is failed
Thread.Sleep(Int32.Parse(com_UserThinkTime)); // Time taken by user to take action after page is loaded
selenium.Click("//a[contains(text(),'" + inv_InviteEmailRegisterLinkText + "')]"); // Click on link with text as pointed by variable inv_InviteEmailRegisterLinkText
selenium.WaitForPopUp(selenium.GetAllWindowNames()[1], sel_TimeOut);
selenium.SelectWindow(selenium.GetAllWindowNames()[1]);
selenium.WindowMaximize();
selenium.Type("//input[contains(@id,'user_password')]", inv_InviteEmailPassword); // Enter password
selenium.Type("//input[contains(@id,'user_password_confirmation')]", inv_InviteEmailPassword); // Enter password again
selenium.Check("//input[contains(@id,'terms_of_use_accepted')]"); // Accpet Terms of USe
selenium.Check("//input[contains(@id,'privacy_statement_accepted')]"); // Accept Privacy statment
Thread.Sleep(Int32.Parse(com_UserThinkTime)); // Time taken by user to take action after page is loaded
selenium.Click("//input[contains(@class,'sign_up_btn')]"); // Click on Signup button
selenium.WaitForPageToLoad(sel_TimeOut); // Wait for web page to load. If page dont load after timeout test is failed
Thread.Sleep(5000);
}
catch (SeleniumException selEx)
{
throw new Exception("GMAIL Something went wrong",selEx);
}
// End of Gmail
}

Wednesday, August 13, 2008

Reads Binary file and encodes it to Base64 string using C#.NET

public static string BinaryToBase64String(string filePath)
{
try
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); // Creates new file stream for binary file with read access
BinaryReader binaryReader = new BinaryReader(fileStream); // Creates the binary reader with file as input
byte[] binaryByteArray = binaryReader.ReadBytes((int)fileStream.Length); // Reads the bytes from binay file and stores into byte array
return Convert.ToBase64String(binaryByteArray); // Encodes the byte array to Base64 string and returns the string
}
catch (Exception ex)
{
return ex.Message; // Returns the exception message
}
}

Locate the element inside table row based on text inside row's cell

This is one of the powerfull XPATH query I have seen

selenium.Check("//tr[.//p[contains(text(),'AT Test User 1')]]//input[contains(@name,'members_new')]");

here //tr[.//p[contains(text(),'AT Test User 1')]] returns the table row which has p tag containing text AT Test User 1. Notice the . used here, which refers to the context node
And once that row is selected //input[contains(@name,'members_new')] locates the input element contained in that row.

Retrieve Value from Resource File using C#

// Here IPOhelper is the class name under which method with following implementation is defined. and file is the file path where resource filename (without extension) is located e.g. Namespace.FileName


string resourceValue = string.Empty;
try
{

ResourceManager resourceManager = new ResourceManager(file,typeof(IOHelper).Assembly);
resourceValue = resourceManager.GetString(key);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
resourceValue = string.Empty;
}

Wednesday, August 06, 2008

Locate Link using XPATH and Link Text

If you want to click on link on HTML with the text displayed as 'Sign out' use following for Selenium RC using C#

selenium.Click("//a[contains(text(),'Sign out')]");

Friday, August 01, 2008

Selenium Image Attributes

Get alternate text from image from HTML document. I use here Xpath query to locate image in the HTML Document

String deviceStatus = selenium.GetAttribute("//img/@alt");

Thursday, July 10, 2008

Delete Directory using C#

In order to Delete Directory using C#, use following syntax

System.IO.Directory.Delete(directoryPath, true);


The true varibale delete all contents of the directory (recursively)

Tuesday, June 24, 2008

Required Field Validator for DropDownList

You can use RequiredFieldValidator for DropDownList.

Just select InitialValue of the RequiredFieldValidator to -1 or 0 whatever that you select for the first element (often with text "Please Select") of DropDownList. Now validator will work and you need to select any other value than the InitialValue in order to pass validation.

Tuesday, June 17, 2008

Default Item for the DropDownList

You can bind C# dropdownlist to datasource and then assign the default value to it using following syntax. By default the 0th item is selected but you can specify it explicitly if you want to select item at different location.

dropDownList.Items.Insert(0,"Please Select"); // Inserts at the first location
dropDownList.Items[0].Selected = true; // First location is selected

Tuesday, May 27, 2008

File Upload Limit in ASP.NET

Using ASP.NET fileupload control one can upload by default size upto size of 4 MB which is mentioned in machine.config. I overrided it in web.config and I was able to upload file with size as mentioned by maxrequestlength property. (20480 ≈ 20 MB)

<system.web>
<httpruntime maxrequestlength="20480" executiontimeout="240">
</system.web>

Friday, May 16, 2008

Enable SQL Authentication for MS SQL 2005 Server

In Order to enable SQL authentication for MS SQL 2005 server, I did the following steps

1. Open SQL Server 2005 Surface area configurator and opened Surface area configuration for services and connection. Under database engine, remote connections I enabled Local and Remote connections.

2. In SQl management studio I logged in to SQL server on localhost and right clicked on properties and went into security tab and enabled both Windows and SQL Authentication.

3. Later under the localhost node in management studio, clicked on security\logins folder and created new login using right click.

4. In case the account you created is disabled, make new query as follows (where login name is 'sa')

ALTER LOGIN sa ENABLE
GO

Friday, May 09, 2008

Load ASP.NET UserControl programatically

In order to load UserControl programatically into view control of Multiview control of ASP.NET, I wrote the following piece of code

ViewName.Controls.Add(LoadControl("~/UserControlName.ascx"));

Thursday, April 03, 2008

Display Multiline Text from the Database on ASP.NET webpage

In order to display multiline text from the database, I used the following code. I used textbox and removed its borders (set BorderStyle= None and BorderWidth= 0px) and scrollbar (To hide scrollbar, added style="overflow:hidden in ASP textbox tag).


string newsBody = GetText(); // From the database

NDNewsBody_TextBox.Rows = newsBody.Length;

NDNewsBody_TextBox.Text = newsBody;

Monday, March 31, 2008

Bound custom data to the Column of the GridView

Today I learned how to attach custom value to the column of the GridView control in ASP.NET page. What I did is as follows

First I click on Edit Templates of the GridView and inside ItemTemplate I dragged one Hyperlink control. For that Hyperlink's NavigateUrl and Text I used databindings.

Later I added new column to the GridView and selected TemplateField. Now the template field column in the GridView shows the Hyperlink whose URL and Text are bound to the custom date.

Unique Identifier Generator in .NET

The following code generates the Unique Identifier in string format..
Guid.NewGuid().ToString();

Wednesday, March 26, 2008

Get Columns Names of the MS SQL Table

Following MS SQL query gives the list of column names of the table_Name

select col.name from sysobjects obj inner join syscolumns col on obj.id = col.id where obj.name = 'table_Name'

Wednesday, March 19, 2008

RequiredFieldValidator and Button Click Event

If you use RequiredFieldValidator control on your ASP.NET page, every button click will perform validation. If you have rest buttons on your page on whose click you dont want validation, then set CausesValidation property of button to false

Thursday, March 13, 2008

Passing values between ASP.NET pages

Today I learned how to pass values between two pages in ASP.NET. Lets say you have Page1.aspx and Page2.aspx and want to pass values from Page1.aspx to Page2.aspx. You can put link button control on Page1.aspx and on its click event you can write this code

string mydata = "88";
Response.Redirect("Page2.aspx?value=" + mydata);

The above code will open Page2.aspx and now in order to get the value, you can write code on PageLoad event or any other method in code-behind file of Page2.aspx as follows

string mydata = Request.QueryString["value"];

Tuesday, March 11, 2008

Substring of DataList field

The label control which is bind to the field for DataList control of ASP.NET page can be truncated using following syntax

Eval("FieldName").ToString().Substring(1,20)

Monday, March 10, 2008

Traverse through SQL Table rows

Here is the code to traverse (iterate) through each row in SQL table...

DECLARE @i INT
SET @i = 1

WHILE (@i<= (SELECT count(*) FROM table_name) )
BEGIN
/* Your Code here...*/
SET @i=@i+1
END

Monday, March 03, 2008

Event Trigger on selection changed in the DropDownList

On ASP.NET page....In order to tigger the event when selection of the DropDownList changes...write code in SelectionIndexChanged event of the DropDownList and dont forget to enable AutoPostBack to True.

Empty TextBox Check using RequiredFieldValidator

In order to check if something is entered into textbox...just drag and drop RequiredFieldValidator user control and set its ControlToValidate property to the desired textbox. And enter the custom error message you like to display...

Now when text is not entered into the desired textbox and page is refreshed using button click event the custom message appears......

Absolute Positioning of User Controls on ASP.NET Page

In Order to position ASP.NET usercontrols in visual designer...select control and then Click ( in Visual Studio ) on Layout->Position->Absolute. And then select and move the control on ASP.NET page as you like..

RadioButton GroupName

Simple and Silly but still important...Today I learned how to choose only one radio button among the radio buttons that are placed on the ASP.NET page. Just give the same GroupName (just any text) property of all radio buttons which you either want to select.

Friday, February 29, 2008

Get Logged in Windows User Name in ASP.NET Page

In order to get username of windows user who is logged into ASP.NET website, I used

string winUserName = System.Web.HttpContext.Current.User.Identity.Name;


winUserName contains the name of the user along with domain name.

Wednesday, February 27, 2008

Access the Items of the DataList ASP.NET

Today I learned how to access the selected row items of the datalist. In ItemTemplate of datalist I have added the button and on button click event I can access the items (e.g. MyLabel item of datalist named MyDataList). The steps are as follows

1. Add the button to the Itemtemplate of Datalist
2. enter 'select' in the CommandName property of the button
3. In Datalist SelectedIndexChanged add the following code. The value contained in item MyLabel is stored in the Mystring.

MyDataList.DataBind();
string MyString;
MyString = ((Label)MyDataList.Items[MyDataList.SelectedIndex].FindControl("MyLabel")).Text;

Tuesday, February 26, 2008

ADO.NET Hello World !!!

Today I learned how to connect to Microsoft SQL database from ASP.NET page using ADO.NET.
Here is the Page Load method which connects to the database and assigns the values taken from the database to the dropdownlist control.



protected void Page_Load(object sender, EventArgs e)
{

// SQL Connection
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = "Data Source=COMPUTERV22;Initial Catalog=CIMNET2;User ID=sa;Password=manager;";

//SQL Command
SqlCommand MyCommand = new SqlCommand();
MyCommand.Connection = MyConnection;
MyCommand.CommandText = "Select * from Employees";

//Open a connection to the database
MyConnection.Open();

// SQL Reader, place where rows from database is stored.
SqlDataReader MyReader;
MyReader = MyCommand.ExecuteReader();

// Read each record from the database
while (MyReader.Read())
{
DropDownList1.Items.Add(MyReader.GetString(1));
}

//Close the connection to the database
MyConnection.Close();

}