Archive

Archive for the ‘C#’ Category

Using BackgroundWorker Class

March 19th, 2009

When running a large task on windows from application the application may seems to be un-responsive and some time it looks that the application is in the state of non-responding.

 Start a new Windows Form Application. Drag a button and a Label on the form write the following lines of code in the click event of the button.

for (int i = 0; i < 10; i++)
{
     label1.Text =
” Itreation No “
+ i.ToString();
     System.Threading.
Thread
.Sleep(1000);
 }

Now run the application and u will see that the text on the label is not updating and the application looks like non-responsive.

To overcome this problem the BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events (DoWork , ProgressChanged , RunWorkerCompleted )  that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox.

 To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

  //Create a background worker

private System.ComponentModel.BackgroundWorker backgroundWorker1;

Call this method from the constructor of the form to initialize the background worker object.

private void InitializeBackgoundWorker()
{
    //create a new Background Worker
     this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();     
      
     
// backgroundworker can report progress updates.

   this.backgroundWorker1.WorkerReportsProgress = true;
       
     
// Set up the BackgroundWorker object by attaching event handlers. 

     backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
     backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}

 


private int showMessage(BackgroundWorker worker, DoWorkEventArgs e)
{
for (int i = 0; i < 10; i++)
{
label1.Text = ” Itreation No “ + i.ToString();
System.Threading.Thread.Sleep(1000);
// call the worker object to show the progress.
//This will call the backgroundWorker1_ProgressChanged Method.

worker.ReportProgress(i * 10);
}
return 1;
}

 


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;


// Assign the result to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.

e.Result = showMessage(worker, e);
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// You can show a progress bar or what ever you want to indicate progress
// This event will fire when you call the ReportProgress method of the Background Worker Object

}

C# , , , , , ,

Advance Screen Scrapping

February 16th, 2009

In the Previous article we disscuss the Simple Screen Scraping task using C#. Now we are moving towards advance Screen Scrapping in this we will Scrap the data which required user to login first. This is a very interesting and challenging task. In the following code we will scrap data from the elance site.

// Create the Web Request Object and pass it the URL of the Login page.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(”https://secure.elance.com/php/reg/main/signInAHR.php”);

// Set that request is coming from some browser e.g. Fire Fox.

req.UserAgent = “User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5″;

// assign a new cookie to the cookie container.

req.CookieContainer = new CookieContainer();

// Set values for the request

req.Method = “POST”;
req.ContentType = “application/x-www-form-urlencoded”;
req.KeepAlive = true;
req.Accept = “text/javascript, text/html, application/xml, text/xml, */*”;
req.Referer = “https://secure.elance.com/php/reg/main/signInIframe.php”;

Now the most trickey section we have to send the user name and password to the requested page.I almost every case the user name and password are sent as post data. so we have to create a post data accordingly.

strNewValue = “referrer=http://www.elance.com/p/landing/provider.html”;
strNewValue += “&mode=signin”;
strNewValue += “&login_name=elance_User”;
strNewValue += “&password=elance_pwd”;
strNewValue += “&email1=”;
strNewValue += “&email2=”;

byte[] byteArray = Encoding.UTF8.GetBytes(strNewValue);

// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;

// Get the request stream.
Stream dataStream = req.GetRequestStream();

// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

// Do the request to get the response
HttpWebResponse wr = (HttpWebResponse)req.GetResponse();

// get the Login Cookie
CookieContainer ccTemp = req.CookieContainer;

Now you can use this cookie Container with every further request you send to the site and in response you will get the logged-in data.

C# , , , , ,

Simple Screen Scraping in C#

January 26th, 2009

In C# Microsoft has provided HttpWebRequest and HttpWebResponse classes for the screen Scraping task. you have to write only few lines to get the work done.

String URL = @”www.abcd.com”;
// Prepare the HttpWebRequest
System.Net.HttpWebRequest htpreq = (HttpWebRequest)System.Net.WebRequest.Create(URL); 
// Define Method Get
htpreq.Method =“GET”; 
// Get the Response

System.Net.WebResponse htpRes = htpreq.GetResponse(); 

// Read the Response Stream
System.IO.StreamReader sr = new System.IO.StreamReader(htpRes.GetResponseStream()); 
 //get the response in string format.
String result = sr.ReadToEnd();
// Create a text File name test.text
System.IO.StreamWriter file = System.IO.File.CreateText(”test.text”);
// write the results in the file
file.Write(result);
// Close the File
file.Close();


Done.

C# , , , , ,

Optical Character Recognition in C# Using MODI Library on 64 bit

January 6th, 2009

Microsoft has provided a solution for OCR with office-2003 onwards. Microsoft Office Document Imaging Library is installed by default with the installation of office-2003 but in 2007 you have to install this library by customizing the setup. You will need to make sure that it is added by using the office 2007 installation setup. Just run the installer, click the continue button with add or remove features and change Imaging component status to “Run from my computer”. Make sure it is installed correctly.

If you have Office 2003 or latest installed, the OCR component is available for you to use. The only dependency that’s added to your software is Office 2007. If your client can guarantee that machines that your software will run on have Office 2007 installed then you can provide this functionality with much ease and without any extra cost.

This library is not compatible with 64 bit OS and you have to make some changes to make it compatible with 64 bit OS (either XP or Vista).

In visual studio 2008 right click the project select properties and then go to build section and change the value of “platform target” to x86.

Adding a Reference to MODI Library.

The name of the COM object that you need to add as a reference is for office 2007 it is Microsoft Office Document Imaging 12.0 Type Library and for office 2003 it is Microsoft Office Document Imaging 11.0 Type Library.

After adding the required library you can use the OCR library in the following lines of code.

Using the MODI Library.

string strText = “” ;

// Instantiate the MODI.Document object

MODI.Document md = new MODI.Document();

// The Create method grabs the picture from

// disk snd prepares for OCR.

md.Create(“c:\abc.bmp”);

// Do the OCR.

md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);

// Get the first (and only image)

MODI.Image image = (MODI.Image)md.Images[0];

// Get the layout.

MODI.Layout layout = image.Layout;

// Loop through the words.

for (int j = 0; j < layout.Words.Count; j++)

{

// Get this word.

MODI.Word word = (MODI.Word)layout.Words[j];

// Add a blank space to separate words.

if (strText.Length > 0)

{

strText += ” “;

}

// Add the word.

strText += word.Text;

}

// Close the MODI.Document object.

md.Close(false);

that’s all .

C# , , , , ,