Monday, May 29, 2017

Know How to Consuming SOAP(asmx) Web Service through Android

This article will help you call a SOAP web service in the simplest way. We will pass a parameter to the web service an will receive it's result. In this tutorial I have used w3school's TempConvert web service. It's publicly available to everyone to consume the web service.

Before we begin with the code, we would to have download KSOAP library for our android project. The library used in this article is ksoap2-android-assembly-2.6.1-jar-with-dependencies.jar. To include this library in your project - Right Click on the project> Select Properties> Java Build Path> Libraries Tab> Add External JARs and then select your downloaded library. Now, on the Order and Export Tab checkmark the checkbox for this library.

The web service has two methods i.e CelsiusToFahrenheit and FahrenheitToCelsius so we have to design a simple android activity for the same.

Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TempConvert"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Input:" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_marginBottom="5dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert To:" />

    <RadioGroup android:id="@+id/rgTemp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Celsius" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"        
        android:text="Fahrenheit" />
    
    </RadioGroup>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result:" />

   <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:editable="false"
        android:ems="10" />

</LinearLayout>
 

To make a call to a SOAP web service, we mainly need four variables i.e namespace, method_name, address and soap_action. Here's how to get them.  


Now, we have to pass the parameter to web to get the result. We use the PropertyInfo class of the KSOAP library to pass the value and it's description.
PropertyInfo pi=new PropertyInfo();
pi.setName(PROPERTY_NAME);
pi.setValue(val);
pi.setType(String.class);
request.addProperty(pi);

We have set a setOnCheckedChangeListener on our radio group. So, whenever user selects an option we will take the value from the input edittext and then call our function which will pass the user input to the web service. Also, if user selects convert to Fahrenheit(or vice-versa) that means he has entered a Celsius value wants to convert it to Fahrenheit. Hence, we will call CelsiusToFahrenheit method of the web service and change variables accordingly.

Here's is the whole code-

package com.loginworks.demo;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class SOAPDemoActivity extends Activity {
    EditText input,result;
    RadioButton cel,fah;
    RadioGroup rGroup;
    String PROPERTY_NAME;
    
    public  String SOAP_ACTION;

    public  String METHOD_NAME; 

    public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

    public  final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        input = (EditText) findViewById(R.id.editText1);
        result = (EditText) findViewById(R.id.editText2);
        
        cel= (RadioButton) findViewById(R.id.radioButton1);
        fah= (RadioButton) findViewById(R.id.radioButton2);
        
        rGroup = (RadioGroup) findViewById(R.id.rgTemp);
        

       rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()  {
            public void onCheckedChanged(RadioGroup rGroup, int checkedId)  {
                
            String in = input.getText().toString();
            
               if (cel.isChecked()) {
                   PROPERTY_NAME = "Fahrenheit";
                   METHOD_NAME = "FahrenheitToCelsius";
                   SOAP_ACTION  = "http://tempuri.org/FahrenheitToCelsius";                   
               }
               else {
                   PROPERTY_NAME = "Celsius";
                   METHOD_NAME = "CelsiusToFahrenheit";
                   SOAP_ACTION  = "http://tempuri.org/CelsiusToFahrenheit";
               }
                                           
               Convert(in);
               
            }            
        });        
      }   
    
    public void Convert(String val) {
         SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, METHOD_NAME);
         
         PropertyInfo pi=new PropertyInfo();

             pi.setName(PROPERTY_NAME);
                pi.setValue(val);
                pi.setType(String.class);
                request.addProperty(pi);
                         
             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true;

             envelope.setOutputSoapObject(request);

             HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

             Object response= null;
             
             try    {
                 
             httpTransport.call(SOAP_ACTION, envelope);
             response = envelope.getResponse();

                 }
             catch (Exception exception) {   
                 
                 response=exception;                     
                 }
                 
             result.setText(response.toString());
    }
}



Note: When you will select an option, you would notice that your activity gets stuck for few seconds that is because we are working with network on the UI thread. So, it's advisable to create a new thread or AsyncTask for network related functions.
Also, don't forget to register your Activity in your Manifest file and add the following permission
<uses-permission android:name="android.permission.INTERNET" />



 

Exporting Telerik WPF GridView to CSV, Excel and Word

As everybody knows, Windows 8 is coming very soon and now a wave of developers and companies are making a big effort to implement their products for this new platform with its new style, etc. This desktop applications are based on Windows Presentation Foundation (or WPF) that it is a computer-software graphical subsystem for rendering user interfaces in Windows-based applications. WPF employs XAML, a derivative of XML, to define and link various UI elements. WPF applications can also be deployed as standalone desktop programs, or hosted as an embedded object in a website. WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, fixed and adaptive documents, typography, vector graphics, runtime animation, and pre-rendered media. These elements can then be linked and manipulated based on various events, user interactions, and data bindings. Microsoft Silverlight provides functionality that is mostly a subset of WPF to provide embedded web controls comparable to Adobe Flash. 3D runtime rendering is supported in Silverlight since Silverlight 5 
Now everybody are seeing that with the controls that Windows is giving inside of Visual Studio 2010 are not fitting their needs or to accomplish them they need more time to develop exactly what they exactly need. But, fortunately we have another options that are doing much easier our lives. They are third party controls with an huge extension of choices, as Infragistics,   DevExpress, Mindscape, Telerik, etc.

<Window x:Class="WpfApplication1.Window1"
    Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
    Xmlns:telerik = "http://schemas.telerik.com/2008/xaml/presentation"
    Xmlns:local = "clr-namespace:WpfApplication1"
    Title="Window1">
    <Grid>
        <Grid.Resources>
            <ObjectDataProvider x:Key = "Customers" 
                 ObjectType = "{x:Type local:NorthwindDataContext}" MethodName = "get_Customers">
            </ObjectDataProvider>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100" />
            <ColumnDefinition Width="100" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="10" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ComboBox x:Name="ComboBox1" SelectedIndex="0">
            <ComboBoxItem Content="Excel"/>
            <ComboBoxItem Content="Word"/>
            <ComboBoxItem Content="Csv"/>
        </ComboBox>
        <Button Content="Export" Grid.Column="1" Click="Button_Click" />
        <telerik:RadGridView Name="RadGridView1" ShowGroupPanel="False" 
                             Grid.ColumnSpan="3" Grid.Row="2"
                             ItemsSource="{Binding Source={StaticResource Customers}}" />
    </Grid>
</Window>

After this, we have to write the code to export in the “.cs” file of the Xaml view, with the Button_Click event, that it is calling the method to export the gridview:
private void Button_Click(object sender, RoutedEventArgs e)
{
  string content = "";
  ComboBoxItem comboItem = ComboBox1.SelectedItem as ComboBoxItem;
  string selectedItem = comboItem.Content.ToString();
  if (selectedItem == "Excel")
  {
    extension = "xls";
    content = RadGridView1.ToHtml(true);
  }
  else if (selectedItem == "Word")
  {
    extension = "doc";
    content = RadGridView1.ToHtml(true);
  }
  else if (selectedItem == "Csv")
  {
    extension = "csv";
    content = RadGridView1.ToCsv(true);
  }
  string path = String.Format("Export.{0}", extension);
  if (File.Exists(path)) { File.Delete(path);
  }
  using (FileStream fs = File.Create(path))
  {
    Byte[] info = Encoding.Default.GetBytes(content);
    fs.Write(info, 0, info.Length);
  }
}

As you can see, this process is very simple and easy, but it doesn’t stop here. Telerik have an huge control collections also for another technologies, as well as, Silverlight, Ajax, ASP .NET, Mobilphones and for the most recent Metro Styles of Windows 8 for the new Visual Studio 2012.
I add also the project example to this post to download and see with more detail how I accomplished it.
I hope I have helped you.


How To Consuming WCF Data Service(OData) in Android/Java

WCF Data Service(previously known as ado.net Data Service) has been developed by Microsoft to support the Open Data Protocol(OData) . OData enables you to expose your data as resources that are addressable by URIs. This enables you to access and change data by using the semantics of representational state transfer (REST).

There are basically 2 libraries that support WCF Data Service for java and android i.e Restlet and OData4j.

However, Restlet being the popular one was not upto the mark for me. It invovles a lot time in setting up and is a lot slower. OData4j is comparatively new but it's much easier to use and even faster than Restlet.

As you have already guessed I would be showing how to use OData4j library to consume a WCF Data Service.

Step - 1 Download the latest OData4j library. At this point the latest version is 0.7. Extract it.

Step - 2 Click on the project> Select Properties> Java Build Path> Libraries Tab> Add External JARs > Navigate to your extracted folder and select odata4j-0.7.0-clientbundle from the bundles sub-folder. Now, on the Order and Export Tab checkmark your imported library.

The service that I would be using is a svc service from Odata.org itself http://services.odata.org/Northwind/Northwind.svc/.
It will look something like this:


Step - 3 Create a new Project or use your existing and design the layout for your web service consuming activity.

layout-wcf_example.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical" >

 <Button
 android:id="@+id/mybtn"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Call WCF" />

 <ListView
 android:id="@+id/mylistview"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" >
 </ListView>
 
</LinearLayout>
 
 

Now decide which property to extract from which table. You can view data from a table by apending the table name at the of the URL. This is what is displayed when we append Categories at the end of our URL i.e http://services.odata.org/Northwind/Northwind.svc/Categories.

Note: If you are not able to view the xml and seeing AtomPub format instead you can turn off feed reading for your browser. In Internet Explorer, Go To Tools> Internet Options > Content Tab> Feeds and Web Slices> Settings and then uncheck "Turn on feed reading view". Restart Internet Explorer.

For this example, we will extract the CategorID and CategoryName.

So here is the much-awaited code:

 ODataConsumer c = ODataJerseyConsumer
                    .create("http://services.odata.org/Northwind/Northwind.svc");
            List<OEntity>  listEntities = c.getEntities("Categories").execute().toList();
            System.out.println("Size - " + listEntities.size());
            if (listEntities.size() > 0) {
                for (OEntity entity : listEntities) {
                    categories.add(entity.getProperty("CategoryID").getValue()
                            .toString()
                            + " - "
                            + entity.getProperty("CategoryName").getValue()
                                    .toString());
                }
 
 

We are creating a ODataConsumer object with our service URL. Then we are specifying our entity from which we want to extract the data. Finally, looped all the entries we receive and extracted the required values and added them to ArrayList. You can perform all OData query functions and filter expressions .
You can also retrieve more information about a Property. H
ere are some sample queries:
? List listEntities = c.getEntities("Categories").expand("Products").top(5).execute().toList();
? System.out.println(""+entity.getProperty("CategoryName").getType ().getFullyQualifiedTypeName());

Here's the whole java class:
WCFExample.java

import java.util.ArrayList;
import java.util.List;

import org.odata4j.consumer.ODataConsumer;
import org.odata4j.core.OEntity;
import org.odata4j.jersey.consumer.ODataJerseyConsumer;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class WCFExample extends Activity {
Button call;
ListView list;
ArrayList categories;
ArrayAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate (savedInstanceState);
setContentView(R.layout.wcf_example);
setTitle("WCF Example");

call = (Button) findViewById (R.id.mybtn);
list = (ListView) findViewById(R.id.mylistview);
categories = new ArrayList();

call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto- generated method stub
new callService().execute();
        }
    });
}

 public class callService extends AsyncTask<Void, Void, ArrayList<String>> {

  @Override
  protected ArrayList<String> doInBackground(Void... params) {
  // TODO Auto-generated method stub

  ODataConsumer c = ODataJerseyConsumer.create("http://services.odata.org/Northwind/Northwind.svc");

  List<OEntity> listEntities = c.getEntities("Categories").execute().toList();

  System.out.println("Size - " + listEntities.size());

  if (listEntities.size() > 0) {
      for (OEntity entity : listEntities) {
          categories.add(entity.getProperty("CategoryID").getValue()
          .toString()
          + " - "
          + entity.getProperty("CategoryName").getValue()
          .toString());
          }
      }
  return categories;
  }

  @Override
  protected void onPostExecute(ArrayList<String> result) {
  // TODO Auto-generated method stub
  super.onPostExecute(result);

  adapter = new ArrayAdapter<String>(WCFExample.this,
  android.R.layout.simple_list_item_1, result);
  list.setAdapter(adapter);
  }
 }
}

I have just created a list to show the output and used a AsyncTask to perform the functions but you can choose to create a new thread or a new service but never use UI thread. Don't forget to Register your Activity in your Manifest file and also add the following permission:

<uses-permission android:name="android.permission.INTERNET" />

You have any problem you can comment.
Also see the second part: Write Functions through WCF Data Service(OData) in Android

How to Download image from Url For Web Scraping

/// <summary> /// Function to download Image from Url
 /// </summary>
 /// URL address to download image
 /// <returns>Image</returns> 
 private Image DownloadImage(string _URL)
 {
        Image _tmpImage = null;
        Application.DoEvents();
        try
        {
                    // Open a connection
                    System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);
                    _HttpWebRequest.AllowWriteStreamBuffering = true; 
                    // You can also specify additional header values like the user agent or the referer: (Optional)
                    _HttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6b) Gecko/20031212 Firebird/0.7+";
                    _HttpWebRequest.Referer = "http://www.google.com/";
                     // set timeout for 20 seconds (Optional)
                    _HttpWebRequest.Timeout = 20000;

                     // Request response:
                     System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

                     // Open data stream:
                     System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

                     // convert webstream to image
                     _tmpImage = Image.FromStream(_WebStream);

                     // Cleanup
                     _WebResponse.Close();
                     _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                     // Error
                     Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                     return null;
             }
            return _tmpImage;
 }

How to Set Internet explorer proxy from code behind

using Microsoft.Win32;

private void SetIeProxy(string Proxy)
 {
         RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
         registry.SetValue("ProxyServer", Proxy);
         registry.SetValue("ProxyEnable", 1);
 
         // These lines implement the Interface in the beginning of program
         // They cause the OS to refresh the settings, causing IP to realy update
         bool settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
         bool refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
 }

Developing a simple BlackBerry Application through Java

 How to develop a simple BlackBerry application in java, for absolute beginners.

Setting Up

There is no need to download eclipse or BlackBerry JDE, just download BlackBerry Plug-In for eclipse from here. It includes Eclipse IDE, BlackBerry plug-in and a Simulator to test and debug your apps.

Creating a Project

After you have installed the plug-in, open it and specify your workspace folder. Select "WorkBench" at start screen that appears. Right click on the project explorer and select New>BlackBerry Project. Name your project and click finish.




You will notice your project has the following files pre-built.





In the BlackBerry_App_Descriptor.xml you can define your app's name, version, description etc. You can also specify the app's launch icon that will appear on the blackberry app menu. For adding icon, you would first have to add it to res folder then select it from the "Add" button in Application Icons panel. If you check rollover, the specified icon(obviosly a differrent icon) will appear when the app is hovered in the BlackBerry app menu.

MyApp.java

It's simple basic work is to create a new instance of UiApplication and push a screen to stack for rendering. Leave it as it is.

MyScreen.java

This is the main screen which is push onto the stack. In this class we will define our layout and implement methods as required.

Creating a simple login screen
If you would run your project now on the simulator, you would see a dos like icon in the app menu named "TutorialApp". If you will open it, a white screen will appear with the title "MyTitle". Many tutorials will show how to develop a HelloWorld app or a simple calculator, but I will show something that is required in almost every app i.e a log-in screen.

First we will change our title by editing the setTitle() method. Then we will add a LabelField (similar to JLabel in java) for displaying a simple heading. After that we will add two HorizontalFieldManagers in which we will put our two Labels("Username" and "Password") and one BasicEditField (similar to JTextField in java) and one PasswordEditField in which we will get our userinput.

Here's the whole code:


package mypackage;

import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.PasswordEditField;

/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen
{
BasicEditField username;
PasswordEditField password;

/**
* Creates a new MyScreen object
*/
public MyScreen()
{        
// Set the displayed title of the screen       
setTitle("Welcome");

LabelField login = new LabelField("Log-In", LabelField.FIELD_HCENTER);
login.setFont(Font.getDefault().derive(Font.BOLD, 30));
login.setMargin(10, 0, 20, 0); //To leave some space from top and bottom


HorizontalFieldManager user = new HorizontalFieldManager();
user.setMargin(0, 0, 10, 0);
HorizontalFieldManager pass = new HorizontalFieldManager();
pass.setMargin(0, 0, 20, 0);
HorizontalFieldManager btns = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);

LabelField usernameTxt = new LabelField("Username :");
LabelField passwordTxt = new LabelField("Password :");

  username = new BasicEditField();
  password = new PasswordEditField();

ButtonField loginBtn = new ButtonField("Log-In", ButtonField.CONSUME_CLICK);
ButtonField exitBtn = new ButtonField("Exit", ButtonField.CONSUME_CLICK);

user.add(usernameTxt);
user.add(username);
pass.add(passwordTxt);
pass.add(password);
btns.add(loginBtn);
btns.add(exitBtn);
add(login);
add(user);
add(pass);
add(btns);
}
}
 

Our layout is ready, but we will add another java class in our src folder which will open if we receive the correct username and password. Right Click on mypackage>New>Class.

Now we will add some functionality to receive user input and open our new screen. Below the line in which we declared the exitBtn write these two lines of code

loginBtn.setChangeListener(btnlistener);
exitBtn.setChangeListener(btnlistener2);

Now, after the closing curly brace of the constructor and before the class ends write following codes to finish our application.

FieldChangeListener btnlistener = new FieldChangeListener() {

public void fieldChanged(Field field, int context) {
//Open a new screen
String uname = username.getText();
String pwd = password.getText();

//If there is no input
if (uname.length() == 0 || pwd.length()==0)
Dialog.alert("One of the textfield is empty!");
else if (uname.equals("user") && pwd.equals("admin"))
UiApplication.getUiApplication().pushScreen(new NewScreen()); //Open a new Screen
else
Dialog.alert("Username or password not found!");
}

};

FieldChangeListener btnlistener2 = new FieldChangeListener() {

public void fieldChanged(Field field, int context) {
//Open a new screen if variables are not empty

//To quit application
System.exit(0);        
}
};
 

When the textfields are empty i.e user does not input any thing, then user is notified of the same through a dialog. There is also an alert if the username and password is not matched. A new screen is visible if the username and password is correct.

I hope this post will help you understand the basics of BlackBerry Java Development. If you have any query please comment.
 

Highlight text in webbrowser control on mouse doble click C#

 
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
        if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
        {
               HtmlDocument _document = webBrowser1.Document;
               _document.MouseLeave += new HtmlElementEventHandler(document_MouseLeave);

               IHTMLDocument2 currentDoc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
               HTMLDocumentEvents2_Event iEvent = (mshtml.HTMLDocumentEvents2_Event)currentDoc;
               iEvent.ondblclick += new HTMLDocumentEvents2_ondblclickEventHandler(iEvent_ondblclick);
        }
}
 
 
 
 
 
private void document_MouseLeave(object sender, HtmlElementEventArgs e)
{
         HtmlElement element = e.FromElement;
         mshtml.HTMLElementEvents2_Event iEvent;
         iEvent = element.DomElement as mshtml.HTMLElementEvents2_Event;
         iEvent.ondblclick -=new HTMLElementEvents2_ondblclickEventHandler(iEvent_ondblclick);
}

bool iEvent_ondblclick(IHTMLEventObj pEvtObj)
{
         if (pEvtObj.srcElement.innerText != null)
         {
               //
               // Stop navigation on current click if it contains link.
               //
               if (pEvtObj.srcElement.outerHTML.Contains("href"))
                      webBrowser1.Stop();

               IHTMLDocument2 doc2 = wbMainPage.Document.DomDocument as IHTMLDocument2;
               StringBuilder html = new StringBuilder(doc2.body.outerHTML);
               String substitution = "" + pEvtObj.srcElement.innerText + "";
               html.Replace(pEvtObj.srcElement.outerHTML, substitution);
               doc2.body.innerHTML = html.ToString();
         }
         return false;
}