Tuesday 27 December 2011

Basic Interview Questions for Manual Testing By Saravanan on c-sharpcorner


Saravanan the author of above article on c-sharpcorner has nicely collected all the Basic Interview Questions of manual testing.

I would suggest the entire Manual tester to have a look or we should know all this basics of manual testing.

Below is the link of the article published by Saravanan on c-sharpcorner.

Please don’t forget providing your valuable feedback over there.

Thanks,
Md. jawed

.NET Interview Questions complied by Scott Hanselman


While surfing net I came across a fantastic blog. Thought to share with all of you!!
The author of this blog nicely listed out all the Questions being asked in interview or rather Great .net Developers Should know.

So here is the link to get the list of questions from .Net.


Let me know your view about the questions!!
Thanks,
Md. jawed

Tuesday 20 December 2011

Are you Confuse between Abstract class and interface?

If you are unable to find out, when to use abstract class and interface. Then here is the solution of your problem. I found very useful article on Abstract class and interface. The author “Rahman Mahmoodi” has explained the things in very nice way.


Before going through this article even I was not having clear picture of abstract class and interface.

But now I’m clear about abstract class and interface.

I would suggest all of you to at least once go through this article. And fold back your shelve to learn Abstract class and interface.

Link provided below.

http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

And don’t forget providing your feedback or comments below this article.
Thanks,
Md. Jawed

Friday 16 December 2011

Dynamically Find controls Type used in web application using WaTin

Introduction:
Using this WaTin feature user would be able to get all the controls types dynamically used in web page.
Details:
  
While performing automation so many times we have faced the issues to find the control type on fly and perform some basic operation or get the properties of controls.


Let me give an example to explain this with clear picture.

Suppose that developer has placed a table on webpage. This table would contents many controls like textbox, button, picture box, label, dropdown, list etc. etc. all this control would appear in table cells dynamically, it means we are not sure when and at what position of cells it will appear in table.

Now we have to read this control on fly and performed some basic operation.

So being an automation engineer, we have programmed our automation code in such a way to know about this control and where it has appeared then performed operation or read properties of that control.

Its bit tricky to handle this kind of situation.

To solve this kind of issues WaTin have provided one best feature to get the type of controls and then based on control we can call our custom method to either get the properties or performed common action.

Here I will only show to how to read controls types on FLY using WaTin.

Below is the Image of web page (to automate this scenario I have developed one basic web application)

And here is the piece of the code to the same.

try

{
IE ie = IE.AttachTo<IE>(Find.ByUrl("http://localhost:28348/Home.aspx"));
var tablecells = ie.Table("table").TableCells;
var type = new string[tablecells.Count];
int i = 0;
    foreach (TableCell tableCell in tablecells)
    {
      try
       {
          string watinType = tableCell.Elements[0].GetType().FullName;
          if (watinType != null) type[i] = watinType.Split('.')[2];
       }
       catch (Exception)
       {
           throw;
        }
    i++;
    }
}
Catch (Exception)
{
throw;
}

And below is the Result when you run the above piece of code. You can see all the controls type in the Type array of string. Shown in below drop down.
Feel free to provide your valuable comments and suggestion.


Thanks,
Md. Jawed

Wednesday 14 December 2011

Perform action on web application using White framework

Introduction:
Using this user would be able to transfer control from WaTiN framework to White Framework to perform action on target web site which is not provided by WaTin.
you can also read this post on http://www.c-sharpcorner.com/UploadFile/jawedmd/perform-action-on-web-application-using-white-framework/

Details:
Before explain this Article/tips I assume that reader is well aware with WaTiN and White Framework (refer below link to get roll your eyes with WaTin and White framework).

Being automation engineering sometimes while automating web application we have to passes the browser control from one framework to another framework to perform some additional action/task on target application.

Okay so let's talk about some real time scenario.

To automate web application I highly concentrated on WaTin framework, as I'm good in that.But sometimes I have to pass browser control from WaTin to White (framework for Windows application) to get focus of open browser or to bring the Browser on User Focus and/or user wants to Click at some particular coordination of browser for that the white framework is much comfortable doing this.

• To know more about White you can refer my link posted on this site
    Click Here
       "or"
  http://white.codeplex.com/

• And to know more about WaTin framework you can refer below link.
   http://watin.org/

okay so now come to the coding part,To achieve this below is the piece of code doing the same?.

I have commented each lines of the code to get clear picture about logic of the code written. And I think rest of things is self-explanatory.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WatiN.Core;
using WatiN.Core.Logging;
using WatiN.Core.Native.Windows;
using White.Core;
using White.Core.UIItems;
///
///Pass the Browser control from Watin to White
///

class BrowserFocus
{
//Instance of Internet explorer using watin
readonly IE _browser = new IE();
///
/// Method to open browser using watin
///

public void AutomationUsingWaTin()
{
//open browser
_browser.GoTo(http://jawedm.blogspot.com);
_browser.WaitForComplete();
//call white method to pass control from watin to white
PerformActionUsingWhite();

}
///
/// Perform Operation on Web application using White, by passing control from WaTin To White
///

private void PerformActionUsingWhite()
{
try
{
//Get the application from watin using processId
var app = White.Core.Application.Attach(_browser.ProcessID);
//get the open browser by watin for white
var windows = app.GetWindows();
White.Core.UIItems.WindowItems.Window window;
//check whether its having browser control or not
if (windows.Count == 1)
{
window = windows[0];
}
else
{//get the browser control using desktop instance
window = White.Core.Desktop.Instance.Windows().Find(w => w.Title.Contains(_browser.Title));
}
//bring the focus on Browser using white
window.Focus();
//Coordination of point where we want to perform right click
var point = new System.Windows.Point(400, 500);
//Right click on the browser using white.
window.RightClickAt(point);
}
catch (Exception ex)
{
// This happens when one of the open windows doea not respond.
// Logger.TraceException("White caused an exception", ex);
}
}
}

Feel Free to provide you valuable feedback and suggestion.

Thursday 1 December 2011

System EVENLOG for logging

if you are planning to use system even viewer for loging purpose. then,below piece of code will work for you!!

if(System.Diagnostics.EventLog.SourceExists("Application"))
   {
     this.eventLog.Source = "Application";
     this.eventLog.Log = "Application";
     this.eventLog.WriteEntry("This is Warning for evenlog!!", EventLogEntryType.Warning);
     this.eventLog.WriteEntry("This is Information for evenlog!!", EventLogEntryType.Information);
     this.eventLog.WriteEntry("This is Error for evenlog!!", EventLogEntryType.Error);
   }

below is the screen shot from event viewer with logging details.


Thanks,
Md. jawed

Tuesday 29 November 2011

Assert for Image in MStest

Few days back while giving an interview in some R&D company. The interviewer who took my interview asked me one question, how will you assert images in test method and I was unable to answer this question, cuz I had never used this in my automation till now. Let me put this in clear way!!


Question: In your test method how will you assert for image. Like assert that two given images are same or equal?

Answer: I was not having clear answer to this question. Just I told that we have to customize our Assert for images assert.

Then I come back and wrote piece of code to assert the image for AreEqual.

Here is the code. Thanks to interviewer who forced me to think about this.

Test Method:


Assert Class for Image(Assert.AreEqual)



Please feel free to provide your Feedback and comments!!
Thanks,
Md. Jawed


Friday 25 November 2011

White: An UI Automation tool for windows application

White: An UI Automation tool for windows application


Finaly i wrote an article on White. just now published this article on code project.
below is the link for the same.
Please have a look and provide your feedback.
 
http://www.codeproject.com/KB/testing/WhiteCalculatorTest_cs.aspx
 
 
 
Thanks,
Md. jawed
 
 

Thursday 17 November 2011

Adding a Code Snippet into Visual Studio2010 to enclose a block of code.

While surfing web I came across a nice blog post by PRABATH .


Who has nicely explained about adding the code snippet in visual studio 2010 to enclose the block of code?. The best part about this post is that he tried best to explain all the steps through screen shot which make the blog post more clear and easy to understand.




Thanks to Prabath for this nice work.

Follow the below link to get the details.

http://prabathf.blogspot.com/2010/02/code-snippets-in-visual-studio-2010.html
 
Keep up the good job buddy :)
 
Thanks,
Md. jawed

Tuesday 15 November 2011

Get the Table Header names using watin

The following code will get Table header names.


TableRow tableRow = Browser.Table("headerTable").TableRow("headerRow");
StringCollection headerValues = new StringCollection();

foreach (Element e in tableRow.Elements)
 {
    if (e.TagName.ToUpper()=="TH")
    {
        headerValues.Add(e.Text);
     }
 }

Thanks,
Md. Jawed

Tuesday 25 October 2011

Tools To Validate Output\Get all dependencies objects From Store Procedure.


                                **********TALK 2 DB**************
I have developed an application/tool to get the output from a store procedure after connecting to the source and target storprocedure on a specific server.


Just you need to pass inputs parameter on UI and this will show all the output values generated by selected store procedure. Even you will get flexibility to get all the dependencies object names on particular selected store procedure name. These entire interfaces on UI itself.

Still i am working to come with full article or details.

Soon I will share an article with all of you.

To just give a glimpse of the application, i have added few snaps shot of tool.

"Talk2DB" that’s the name of this tool.
1. Main Window:

Main Window
  2. Connecting to DataBase
Connecting to DataBase
 3. Getting all the dependecies from Sp.
Getting all the dependecies from Sp.
4. Showing Out Put from Store procedure
Showing Out Put from Store procedure
Thank you,
Md. jawed

Tuesday 4 October 2011

Get List of open windows in a machine including pop up windows

class Program
{
{
foreach (KeyValuePair<IntPtr, string>lWindow in OpenWindowGetter.GetOpenWindows())

IntPtr lHandle = lWindow.Key;
string lTitle = lWindow.Value;
Console.WriteLine("{0}: {1}", lHandle, lTitle);}}
}

================
using System;

using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace GetOpenWindows
{
using HWND = IntPtr;/// Contains a method to get all the open windows.
public static class OpenWindowGetter{/// Returns a dictionary that contains the handle and title of all the open windows./// A dictionary that contains the handle and title of all the open windows.
 {
    EnumWindows(delegate(HWND hWnd, int lParam)
     {
        if (hWnd == lShellWindow) return true;



        if (!IsWindowVisible(hWnd)) return true;
        int processId;
        processId= GetWindowThreadProcessId(hWnd,out processId);
        int lLength = GetWindowTextLength(hWnd);
        if (lLength == 0) return true;
        StringBuilder lBuilder = new StringBuilder(lLength);
        GetWindowText(hWnd, lBuilder, lLength + 1);
        lWindows[hWnd] = lBuilder.ToString();
         return true;
      }, 0);
   return lWindows;
 }

delegate bool EnumWindowsProc(HWND hWnd, int lParam);

[DllImport("USER32.DLL")]
static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

[DllImport("USER32.DLL")]
static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("USER32.DLL")]
static extern int GetWindowTextLength(HWND hWnd);

[DllImport("USER32.DLL")]
static extern int GetWindowThreadProcessId(HWND hWnd, out int processId);

[DllImport("USER32.DLL")]
static extern bool IsWindowVisible(HWND hWnd);

[DllImport("USER32.DLL")]
static extern IntPtr GetShellWindow();

 }
}

Thanks,
Md. Jawed

Monday 3 October 2011

Compare bitmaps images.

Here is the code to compare 2 bitmaps images.
public class ComparingImages
 {
   public enum CompareResult
   {
      Match,
      Mismatch,
      SizeMismatch
   };

public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
 {
   CompareResult cr = CompareResult.Match;
   //Test to see if we have the same size of image
   if (bmp1.Size != bmp2.Size)
   {
     cr = CompareResult.SizeMismatch;
   }
  else
  {
    //Convert each image to a byte array
    ImageConverter ic = new ImageConverter();
   byte[] btImage1 = new byte[1];
   btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
   byte[] btImage2 = new byte[1];
   btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());
   //Compute a hash for each image
   var shaM = new SHA256Managed();
   byte[] hash1 = shaM.ComputeHash(btImage1);
   byte[] hash2 = shaM.ComputeHash(btImage2);
   //Compare the hash values
   for (int i = 0; i < hash1.Length && i < hash2.Length
   && cr == CompareResult.Match; i++)
   {
     if (hash1[i] != hash2[i])
     cr = CompareResult.Mismatch;
    }
   }
   return cr;
  }
  }

Thanks!
~jawed

Wednesday 21 September 2011

Resizing an Array

I have seen people declaring an array of fixed size. But sometimes while working on dynamic elements size this would be capable enough to hold all the elements in the array. But unfortunately it’s not true. Sometimes you need to handle with small set of data and sometimes with big set of data. Then, how to resize the array. So that it would be capable enough to hold this situation.

Simple:
The .NET Framework Version 2.0 introduced a solution to this problem by adding the

Array.Resize method, which is used to change the size of an array.

 Assume that, you have an array named firstArray initialized with five

Elements, you can extend its size to ten elements by using the following

statement:

Array.Resize (ref firstArray, 10);

This is very small method. but, very useful
See the example with the code below.


Thanks,
Md. Jawed

Tuesday 16 August 2011

Unit Testing Framework and Type of Assert.

Few days back i had prepared a presentation about Unit Testing Framework and Type of assert in MStest.
which i have collected from ms website.
i had arranged all this in images formates so that it would be easy to access.
Thought to share the same with all of you!!
Happy Reading!!
  

Slide 1: The Title

Slide 2: Unit Testing Framework

Slide 3: Attributes Used to Establish a Calling Order

Slide 4: Assert Type

Slide 5:StringAssert Type

Slide 5: CollectionAssert Type

Slide 6: The End

Your Comments are always welcome!!
Thanks,
Md. Jawed 

What ia dumb file and how to capture it.

A nice article to read about What is a dump, and how do I create one?

i found this while surfing..so thought to share with all of you!!

http://blogs.msdn.com/b/debugger/archive/2009/12/30/what-is-a-dump-and-how-do-i-create-one.aspx

Using Visual studio you can capture the Dump file also.
make sure that under Debuge the Save Dump As menu item is added in visual atudio. if not then follow the below steps to add this menu item:

a. Select Tools -> Customize

b. Select the Commands tab

c. Select Debug from the Menu bar dropdown

d. Click Add Command...

e. Select Debug from the Categories list.

f. Find the Save Dump As entry in the Commands window.

g. Click OK (the Save Dump As... command is added to the top of the Debug menu).

h. Click Close

You can use the following steps to get a mini dump file:


1. Start Visual Studio.

2. Start another instance of VS.

3. In the second instance click Tools
Attach to Process...

4. In the list of processes locate devenv.exe.

5. Click Select... and explicitly choose 'Native' and 'Managed' code.

6. Click OK and OK to close Select dialog and Attach to Process dialog.

7. Go back to the first instance of VS and repro the crash\hang.

8. Upon the crash\hang, control should go to the second instance of VS.

9. In the second instance click Debug
Save Mini Dump (without heap).

http://connect.microsoft.com/VisualStudio/feedback/details/610988/qtagent32-crashes-on-running-unit-tests



Tuesday 26 July 2011

Measure Execution Time taken by your code.

To measure an execution time taken by your code, just use the below piece of code at appropriate place in your code block.
using System.Diagnostics;

public static void Main(string[] args)
{
Console.WriteLine("In Main");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();

//Your Code will go here

stopwatch.Stop();
var timeSpan = stopwatch.Elapsed;
var executionTimeTaken=String.Format("{0:00}:{1:00}:{2:00}.{3:00}",timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
Console.WriteLine(executionTimeTaken);
}

Thanks,
Md. jawed

Sunday 17 July 2011

J-AXE: A File Splitter in C#

Introduction

 J-AXE file splitter is a windows application developed using C# .Net to split file in to time interval,Based on size and total files after splits. I would not ignore the fact that this is some kind of new application, Already there is so many open source project are available to achieve the same purpose. Then the question is why I have spent lots of time to develop this app: allow me to explain the question: whatever application is available as open and/or paid, you will not get the options to splits the file based on Time interval or duration. But here you will get this functionality along with other functionality with new flavor; and the main point is that I wanted to develop this using C#.Net and by developing this kind of application I will get a chance to learn something new And even I would utilize my free time into something productive .So I did this and here is the UI of this J-AXE file splitter application.
 (http://www.codeproject.com/KB/applications/JAXEFileSplitter.aspx)


                                                  Fig 1. JAXE File Splitter UI.


Might be you will think that why this application name is J-AXE? Actually the letter J came from Jawed and AXE is to cut some wooden block. So, I have chosen this application name as J-AXE.

Background

 Of course there was something which triggers me to come up with this ideas/application. Last month I recorded family videos using my camcorder after that I added few songs and effect in to recorded video to make it movies so that I can distribute this among family’s members. Now I wanted to split this file into durations instead of size so that I can make it into different parts, something like Part1 as 30 minutes and Part2 as45 Minutes. I searched here and there for open source but whatever I got all were having functionality to splits file only by size not by the time interval.

Then this requirement triggered some chemical imagination into my mind to come up with some application to fulfill my requirement and here it is an application “J-AXE: A file Splitter”.
 
Using the code

 J-AXE: A file Splitter a Windows application is very handy in use. The whole solution is divided into 2 Projects .One project would be User interface and Second Project would be nothing but our main logic which is in DLL format. The idea to separate logic from UI and make logic as DLL so, that anybody can use it easily without referring to my UI implementation.

Let me give you some pictorial presentation of the whole scenario (Class Diagram):
 
                                Fig 2. Class Diagram of JAXE File Splitter with JAXE DLL.


First I would like to explain the implementation of UI part. Then, I will explain the Logic part :

PART1: User Interface
The Block diagram would be something like this:

                                   Fig 3. Block Digaram of JAXE File Splitter.


On UI User will get below option to splits the file:
1. Based on Duration (Time duration in sec/min)
2. Size(in Bytes/KB/MB)
3. And Number of files

Based on the option selected we will call the corresponding function to splits the file:

I have already published this application on Code project., for code details and explanation you can visit the below link for the same:

J-AXE: A File Splitter in C# on Code project by Me. Jawed.

~jawed

Saturday 9 July 2011

Move Items from one listbox to other list box

So,here is the piece of code for that:

public static void MoveSelItems(ListBox from, ListBox to)
{
for (var i = 0; i < from.SelectedItems.Count; i++)
{
to.Items.Add(from.SelectedItems[i].ToString());
from.Items.Remove(from.SelectedItems[i]);
}
}
~jawed

Splites files using C#

Here is the code snippet to Put files under AXE to splits the particular file and then place the output files at target location.

Using System.io;
Using System;

//Method to split files
public void SplitFileBasedOnNumberOfFiles(string inputFile, int noOfFiles,string outPutLocation)

{
//Open the file in read mode

var fs = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
//read the inputs for how many files user want after splitting
var numberOfFiles = Convert.ToInt32(noOfFiles);
//get the size of each file after splitting
var sizeOfEachFile = (int)Math.Ceiling((double)fs.Length / numberOfFiles);
//start the for loop to go through num of file and split that
var baseFileName = Path.GetFileNameWithoutExtension(inputFile);
var extension = Path.GetExtension(inputFile);

for (var i = 1; i <= numberOfFiles; i++)
{
//get the base name
//get the extension of the file
//get the out put location with output file name
var outputFile = new FileStream(outPutLocation + "\\" + baseFileName + "_" + i.ToString().PadLeft(5, Convert.ToChar("0")) + extension, FileMode.Create, FileAccess.Write);
var bytesRead = 0;
//array of bytes
var buffer = new byte[sizeOfEachFile];
//read the file bytes by bytes and put into output buffer
if ((bytesRead = fs.Read(buffer, 0, sizeOfEachFile))
outputFile.Write(buffer, 0, bytesRead);
outputFile.Close();
}
fs.Close();
}


Print html or any files from Windows form using C#

Using this code you would be able to print any type of pages.
just copy and paste this code on any button event handler.

private void buttonPrint_Click(object sender, EventArgs e)
{
try
{
Process printProc = new Process();

 printProc.StartInfo.FileName =" yourFileName";
printProc.StartInfo.UseShellExecute = true;
printProc.StartInfo.Verb = "print";
printProc.StartInfo.CreateNoWindow = true;
printProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
printProc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Jawed Blog say!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

Thanks,
Md. Jawed

Saturday 5 March 2011

C# Code snippet to send an Email with attachment from Outlook, Yahoo, HotMail, AOL and Gmail

1. Down Load Source Code click here.
Introduction
Using this code snippet user would be able to send an email with attachment through Outlook, Yahoo, AOL, HOTMAIL and Gmail.
Background
Already loads of information are available on internet for the same purpose. But not all the code is placed at one place. So here is my small effort to accumulate all the code at one place and that is nothing better than CodeProject. Hopefully it will be helpful for the beginners or whoever in needs of it.
Using the code
Name Space:

Block Diagram(SMTP Setting for various client):
Below is the Block diagram for the SMTP settings i have used to send out an email from various client providers.
Wherever needed I have explain the code in details. The codes are self explanatory, any way for the same I have included comments. So here is the code snippet to achieve your purpose.
1. Using Outlook:
To send an email using outlook, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll.
For the same follow the below steps
1. Go to your solution explorer
2. Click on add a reference
3. Click on .Net Tab
4. Go through the DLL and select Microsoft.Office.Interop.Outlook.dll correctly.
5. When you have selected the correct reference you select the “OK” button and this reference will be added to your project under references.

6. Now we need to add a reference in our class to the Outlook reference we have added to the project in our previous example.
using Outlook = Microsoft.Office.Interop.Outlook;
And finally the code would look something like this:

2. Using HOTMAIL:
To send an email using HotMail, we need to add a reference to the dynamic link library for Hotmail/Gmail/AOL/Yahoo which is called System.Net.Mail.
For the same follow the below steps:
1. Go to solution explorer of your project
2. Select add a reference
3. Click on .Net Tab
4. Go through the DLL and select System.Net.Mail.
5. When you have selected the correct reference you select the “OK” button and this reference will be added to your project under references.
6. Now we need to add a reference in our class to the Hotmail/gmail/aol/yahoo reference we have added to the project.
using System.Net.Mail;
Note: The HOTMAIL SMTP Server requires an encrypted connection (SSL) on port 25.
And finally the code would look something like this:

3. Using Yahoo! 4. Using AOL:
5. Using Gmail:
Note:
The GMAIL SMTP Server requires an encrypted connection (SSL) on port 487.




Already I am using the above code snippet for my automation purpose and its working fine for me!!

Thank you!!
Feel Free to provide your comments and suggestion.
Md. Jawed.

Saturday 26 February 2011

QC DATA PULLER using C#

Using this application user can generate report of test case execution from QC(Quality center) in to HTML web page with fancy pie chart and tabular format using C# and OTA API expose from QC(Quality Center).
i have pulished an Articles on Code project for generating report for test cases executed from QC. the report would be in HTML web page format with pie chart and tabullar format.

for more details you visit below link for that:
QC Data Puller on Code Project.
Please go through the link and provide your valuabe comments and suggestion!!
Thank you!!
~jawed

Monday 21 February 2011

Post Comments web page in ASP.Net using C#

Recently I have developed a web application automation application in which I have added a functionality for the user to post their comments, experience and questions for the admin.
Thought to share this approach with all of you.
So here is my approach what I have done.
1. An aspx page with name URComments.aspx.
2. we will use XML file to store all the comments posted by the users.
3. Used GridView to show all the comments posted by the users.
4. On page load and/or on post button click we will call a funtion to read all the comments
posted till now by the user and show that in to GridView.
5. Below controls we will on design view of URComments.aspx.
a. Text box to get the Emailid from the user.
b. Text box for the user to entered Comments and/or suggestion.
c. Button to submit comments.
d. GridView to show all the comments posted till that time.
The web page would look something like this:

Fig 1. Web Page with Post Comments Feature

6. The XML file format would be something as below. This XML file we will use to store all the comments provided by the user. B d way you can customize this as per your requirement.


fig 2. XMl File to store Comments posted by User
Page Load :
public static string xmlPath =ConfigurationSettings.AppSettings["xmlFilePath"].ToString();
//on page load redirect the user to the specific url and then show all the comments
//posted //till //now
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
showThePostOnWebPage();
}

}

Showing Post in Web Page:
//Display the Post on webPage
public bool showThePostOnWebPage()
{
bool result = false;
try
{
DataSet dsForWebPage = readXMFile();
GridViewPost.DataSource = dsForWebPage.Tables[0];
GridViewPost.DataBind();
result = true;
}
catch (Exception ex)
{

}
return result ;
}


Reading the XML file for the comments posted till now:
//Read the xml File
public DataSet readXMFile()
{
DataSet ds = new DataSet();
System.IO.FileStream fsReadXml = null;
try
{
//Read an XML file to generate serial number
fsReadXml = new System.IO.FileStream(xmlPath, System.IO.FileMode.Open);
//Declare a dataset to hold all the XML value
//Read the value from XML reader to the dataset
ds.ReadXml(fsReadXml);
}
catch (Exception ex)
{
ds = null;
}
finally
{
fsReadXml.Close();
}
return ds;
}

On Button click (when user tried to submit the post):
protected void ButtonPost_Click(object sender, EventArgs e)
{
FileStream fsxml = null;
FileStream fs = null;
try
{
//check that the comments textbox is not empty
if (TextBoxComments.Text != null && TextBoxComments.Text != string.Empty )
{
//Read an xml file to get all the post commented till now
DataSet dsSet = readXMFile();
if (dsSet != null)
{
//make sure that table exist
int totalRowCount = dsSet.Tables[0].Rows.Count;
string strSerialNumber = null;
string getTheNumber = null;
if (totalRowCount <= 0) { getTheNumber = "1"; } else
{
//get the number
strSerialNumber = dsSet.Tables[0].Rows[totalRowCount - 1][4].ToString();
getTheNumber = strSerialNumber.Remove(0, 3);
}

Int32 currentSerialNumber = Convert.ToInt32(getTheNumber);
Int32 nextSerilaNumber = currentSerialNumber + 1;
string strSerialNumberToadd = "CFG" + nextSerilaNumber.ToString();
fs = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fs);
// New XML Element Created
XmlElement newcatalogentry = xmldoc.CreateElement("CFGPost");
// New Attribute Created
XmlAttribute newcatalogattr = xmldoc.CreateAttribute("ID");
// Value given for the new attribute
newcatalogattr.Value = strSerialNumberToadd;
// Attach the attribute to the XML element
newcatalogentry.SetAttributeNode(newcatalogattr);
// First Element - Comments
XmlElement firstelement = xmldoc.CreateElement("Comments");
// Value given for the first element
firstelement.InnerText = TextBoxComments.Text.ToString();
// Append the newly created element as a child element
newcatalogentry.AppendChild(firstelement);
// Second Element - Date
XmlElement secondelement = xmldoc.CreateElement("Date");
// Value given for the second element
secondelement.InnerText = DateTime.Now.ToString();
// Append the newly created element as a child element
newcatalogentry.AppendChild(secondelement);
// Third Element - EmailID
XmlElement thridelement = xmldoc.CreateElement("EmailId");
// Value given for the third element
thridelement.InnerText = TextBoxEmailId.Text;
// Append the newly created element as a child element
newcatalogentry.AppendChild(thridelement);
// Fourth Element - UserName
XmlElement fourthelement = xmldoc.CreateElement("UserName");
// Value given for the fourth element
fourthelement.InnerText = hostName.ToString();
// Append the newly created element as a child element
newcatalogentry.AppendChild(fourthelement);
// New XML element inserted into the document
xmldoc.DocumentElement.InsertAfter(newcatalogentry,xmldoc.DocumentElement.LastChild);
fs.Close();
// An instance of FileStream class created
// The first parameter is the path to the XML file
fsxml = new FileStream(xmlPath, FileMode.Truncate,
FileAccess.Write,
FileShare.ReadWrite);
// XML Document Saved
xmldoc.Save(fsxml);
fsxml.Close();
//Clean the text box area
TextBoxEmailId.Text = string.Empty;
TextBoxComments.Text = string.Empty;
bool flag = showThePostOnWebPage();
RegisterClientScriptBlock("js", "
");
}
else
{
//show the message to the user that currently we are facing some issue
RegisterClientScriptBlock("js", "
"
);
}
}
//if it is empty then show the message to user
else
{
RegisterClientScriptBlock("js", "
"
);

}
}
catch (Exception ex)
{

}
}

Method whenever user clicked on Pagination of Grid View
//fire this even whenever user clicked on pagination at gridView
protected void GridViewPost_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GridViewPost.PageIndex = e.NewPageIndex;
showThePostOnWebPage();

}
catch (Exception ex)
{

}
}

Now you are ready with the Post Comments project.
You can integrate this with your web application to provide the user an option to share their suggestion/comments and issues with others.
Hope you would get benefited form this.

Feel free to provide your comments.
*************************
Thank You,
Md. Jawed

Wednesday 16 February 2011

Debugging, Tracing and Instrumentation in .NET and ASP.NET (14 FAQ) by Shivprasad koirala

A nicely explained article about Debugging, Tracing and Instrumentation in .Net.
This article is posted on Code Project by Shivprasad koirala.
He has explained everything in such a nice way with nice images and videos that you will understand all the pin point of Debugging, Tracing and Instrumentation in .Net.
Let me put some contents from his post:
What is Instrumentation?
Debugging application is not just about pressing F 10 or F 11 and watching “add watch windows” using visual studio IDE. Debugging becomes pretty complex on production environments where the project is deployed in a release mode and you need to figure out till what point the code ran and when did it crash. The worst part is you are enjoying your sleep at home and suddenly someone calls up and says, “Hey! the application crashed in production”.If your application is well planned with proper instrumentation you can just say the person to view the event viewer or a log file for further details and you can give the solution on the phone itself.So defining instrumentation in short, it’s the ability of the application to monitor execution path at critical points to do debugging and measure performance.
What is debugging and tracing?
We would like to enable application instrumentation in two situations while you are doing development and while your application is in production. When you monitor application execution and performance in development stage is termed as “Debugging” and when you do in deployed environment it’s termed as ‘Tracing’.


Thanks to Shivprasad koirala for posting such a useful and knowledgeable articles.
Hats off to you!!!
~jawed