Subscribe For Free Updates!

We'll not spam mate! We promise.

Thursday, 24 October 2013

jQuery Autocomplete Getting Data From Database in ASP.Net

Introduction
This article describes how to add an Auto Complete feature to a text box and get the data from a database in ASP.Net using a jQuery UI .

Description
To create this application you need the jQuery files listed below.

  • jquery-1.9.1.js
  • jquery-ui.js
  • jquery-ui.css
You can download them from the source code attached to this page.
Design
Go to the database and design your table or execute the following script:
CREATE TABLE [dbo].[DEPT]
(DEPTNO NUMERIC(2),
DNAME VARCHAR(14),
LOC VARCHAR(13) );
GO

INSERT INTO [dbo].[DEPT] VALUES (10, 'ACCOUNTING', 'NEW YORK');
INSERT INTO [dbo].[DEPT] VALUES (20, 'RESEARCH', 'DALLAS');
INSERT INTO [dbo].[DEPT] VALUES (30, 'SALES', 'CHICAGO');
INSERT INTO [dbo].[DEPT] VALUES (40, 'OPERATIONS', 'BOSTON'); 
In Visual Studio create a website and add a page.

Add a Text Box to the page for searching.

Now design your screen as in the following screen:

JQuery-Autocomplete-1.jpg

Or you can copy the following source code:



<body>
   <form id="form1" runat="server">
    Search Department :<asp:TextBox ID="txtSearch" runat="server" ></asp:TextBox>
    </form>
</body>

Next add the following JavaScript and CSS style code in the head tag of an aspx file
(this is used to get the data to show the auto complete).


<head id="Head1" runat="server">
    <title></title>
    <link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui.js" type="text/javascript"></script>
    <script type="text/javascript">
               $(document).ready(function () {
    $("#txtSearch").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/GetData",
                data: "{'DName':'" + document.getElementById('txtSearch').value + "'}",
                dataType: "json",
                success: function (data) {
                    response(data.d);
                },
                error: function (result) {
                    alert("Error......");
                }
            });
        }
    });
});
   </script>
</head>

JQuery-Autocomplete-2.jpg

Now go to Solution Explorer and add a Web Service to the project (for example, "WebService.asmx").
Now write the following code in the .cs file of the Web Service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public List<string> GetData(string DName)
    {
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection("Data Source=SYSTEM-30;database=DB_Test_Trainees;user id=test;password=Test"))
        {
            using (SqlCommand cmd = new SqlCommand("select Dname from DEPTDHII where Dname like '%'+@SearchText+'%'", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", DName);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["DName"].ToString());
                }
                return result;
            }
        }
    }
}

Now check this line in the code above:

[System.Web.Script.Services.ScriptService]

By default this line is commented. To allow this Web Service to be called from a script using ASP.NET AJAX, uncomment the line.

Now build your application. Enter a search query in the TextBox.

JQuery-Autocomplete-3.jpg 
To download Source Click Here

Tuesday, 22 October 2013

How to use a Web Service in Windows Form Application

Introduction

This blog describes how to Communicate with a web service in Windows Form application.

In previous article we saw How to Create a Simple Web Service and Use it in ASP.Net.

Now here I am going to use that same service in Windows Form application.

Creating the client application

Now create a Windows Form Application and design your form as in the following screen.

index.jpg
Add a web reference to the Application

Go to Solution Explorer then select the solution then click on "Add Service Reference". it will open an window

Then click on Advanced button on that window.

index1.jpg

A new window will open. then click on "Add Web Reference". 


index2.jpg
A new window will open. Then within the URL type the service reference path.

(For example: http://localhost:65312/WebServiceSample/Airthmatic.asmx) then click on the "Go" button.

Nowyou will see your service methods. Change the web reference name from "localhost" to any other name as you like (for example: Airthmatic).

Click on the "Add Reference" button. It will create a Proxy at the client side.

index3.jpg
Now go to the cs code and add a reference for the Service.

Write the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsAirthmatic
{
    public partial class Form1 : Form
    {
        Airthmatic.Airthmatic obj = new Airthmatic.Airthmatic();
        int a, b, c;
        public Form1()
        {
            InitializeComponent();
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(textBox1.Text);
            b = Convert.ToInt32(textBox3.Text);
            c = obj.Add(a, b);
            label4.Text = c.ToString();
        }
        private void btnSub_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(textBox1.Text);
            b = Convert.ToInt32(textBox3.Text);
            c = obj.Sub(a, b);
            label4.Text = c.ToString();
        }
        private void btnMul_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(textBox1.Text);
            b = Convert.ToInt32(textBox3.Text);
            c = obj.Mul(a, b);
            label4.Text = c.ToString();
        }
        private void btnDiv_Click(object sender, EventArgs e)
        {
            a = Convert.ToInt32(textBox1.Text);
            b = Convert.ToInt32(textBox3.Text);
            c = obj.Div(a, b);
            label4.Text = c.ToString();
        }
    }
}

Now first run the Web service then the application.

index3.png

How to Create a Simple Web Service and Use it in ASP.Net

Introduction

This article describes how to create a web service in ASP.NET and use it in a client application.

What is Web Service?

A Web Service is a reusable piece of code used to communicate among Heterogeneous Applications.

Once a web service is created and hosted on the server in the internet it can be consumed by any kind of application developed in any technology.

How to create a Web Service

Step 1
Go to Visual Studio then click on "File" -> "Website" -> "ASP.NET empty website template".

Then provide the website name (for example: WebServiceSample).

1.jpg


Step 2: Add a Web Service File

Go to Solution Explorer, then select the solution then click on "Add new item".

Choose the Web Service template.

Enter the name (for example: Airthmatic.cs) then click on "Add".

2.jpeg

This will create the following two files:

  1. Airthmatic.asmx (the service file)
  2. Airthmatic.cs (the code file for the service; it will be in the "App_code" folder)
3.jpeg

Open the file Airthmatic.cs and write the following code:

using System;
 using
System.Collections.Generic;
 using
System.Linq;
 using
System.Web;
 using
System.Web.Services;
 ///
<summary>
 ///
used for Airthmatic calculation
 ///
</summary>
 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 // [System.Web.Script.Services.ScriptService]

 public
class Airthmatic : System.Web.Services.WebService
 {
     public Airthmatic()   {
         //Uncomment the following line if using designed components
         //InitializeComponent();
     }
     [WebMethod]
     public int Add(int x, int y)
     {
         return x + y;
     }
     [WebMethod]
     public int Sub(int x, int y)
     {
         return x - y;
     }
     [WebMethod]
     public int Mul(int x, int y)
     {
         return x * y;
     }
     [WebMethod]
     public int Div(int x, int y)
     {
         return x / y;
     }
 }


Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. You can also use the properties of this attribute to further configure the behavior of the XML Web service method. The WebMethod attribute provides the following properties:

  • BufferResponse
  • CacheDuration
  • Description
  • EnableSession
  • MessageName
  • TransactionOption

For more details of web methods click here.

Step 3

To see whether the service is running correctly go to the Solution Explorer then open "Airthmatic.asmx" and run your application.

Now you will find all the method names in the browser.

4.jpeg

To see the WSDL format click on the service description link or add "?WSDL" to the URL.

Example: http://localhost:65312/WebServiceSample/Airthmatic.asmx?WSDL

It will show the WSDL.

5.jpeg

To determine whether the functions are working, click on one of the functions (for example: "Add").

Now you will see two TextBoxes for checking. Enter the value for x and y and click on the "Invoke" button.

Now you will see the result in an open standard form (XML).

6.jpg

Now your service is ready for use.

Step 4: Creating the client application

Now create a website and design your form as in the following screen.

 7.jpeg

Or you can copy the following source code.

<body>
     <form id="form1" runat="server">
     <div>
         <table border="2" cellpadding="2" cellspacing="2">
             <tr>
                 <td align="right">
                     <asp:Label ID="Label1" runat="server" Text="Enter 1st Number"></asp:Label>
                 </td>
                 <td align="left">
                     <asp:TextBox ID="txtFno" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td align="right">
                     <asp:Label ID="Label2" runat="server" Text="Enter 2nd Number"></asp:Label>
                 </td>
                 <td align="left">
                     <asp:TextBox ID="txtSno" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td align="right">
                     <asp:Label ID="Label3" runat="server" Text="Result"></asp:Label>
                 </td>
                 <td align="left">
                     <asp:Label ID="lblResult" runat="server"></asp:Label>
                 </td>
             </tr>
             <tr>
                 <td align="center">
                     <asp:Button ID="btnAdd" runat="server" Text="Add(+)" OnClick="btnAdd_Click" />
                 </td>
                 <td align="center">
                     <asp:Button ID="btnSub" runat="server" Text="Sub(-)" OnClick="btnSub_Click" />
                 </td>
             </tr>
             <tr>
                 <td align="center">
                     <asp:Button ID="BtnMul" runat="server" Text="Mul(*)" OnClick="BtnMul_Click" />
                 </td>
                 <td align="center">
                     <asp:Button ID="btnDiv" runat="server" Text="Div(/)" OnClick="btnDiv_Click" />
                 </td>
             </tr>
         </table>
     </div>
     </form>

 </
body>

Step 5: Add a web reference to the Website

Go to Solution Explorer then select the solution then click on "AddWeb Reference" then within the URL type the service reference path.

(For example: http://localhost:65312/WebServiceSample/Airthmatic.asmx) then click on the "Go" button.

Now you will see your service methods. Change the web reference name from "localhost" to any other name as you like (for example: WebAirthmatic).

Click on the "Add Reference" button. It will create a Proxy at the client side.

8.jpeg

Now go to the cs code and add a reference for the Service.

Example:  using WebAirthmatic;

Write the following code.

using System;
 using
System.Collections.Generic;
 using
System.Linq;
 using
System.Web;
 using
System.Web.UI;
 using
System.Web.UI.WebControls;
 using
WebAirthmatic;
 public
partial class _Default : System.Web.UI.Page
 {
     Airthmatic obj = new Airthmatic();
     int a, b, c;
     protected void Page_Load(object sender, EventArgs e)
     {
     }
     protected void btnAdd_Click(object sender, EventArgs e)
     {
         a = Convert.ToInt32(txtFno.Text);
         b = Convert.ToInt32(txtSno.Text);
         c = obj.Add(a, b);
         lblResult.Text = c.ToString();
     }
     protected void btnSub_Click(object sender, EventArgs e)
     {
         a = Convert.ToInt32(txtFno.Text);
         b = Convert.ToInt32(txtSno.Text);
         c = obj.Sub(a, b);
         lblResult.Text = c.ToString();
     }
     protected void BtnMul_Click(object sender, EventArgs e)
     {
         a = Convert.ToInt32(txtFno.Text);
         b = Convert.ToInt32(txtSno.Text);
         c = obj.Mul(a, b);
         lblResult.Text = c.ToString();
     }
     protected void btnDiv_Click(object sender, EventArgs e)
     {
         a = Convert.ToInt32(txtFno.Text);
         b = Convert.ToInt32(txtSno.Text);
         c = obj.Div(a, b);
         lblResult.Text = c.ToString();
     }
 }


Now first run the Web service then the application.

9.jpeg

Now you will be able to communicate with the web service.

Monday, 21 October 2013

Translate Your Web Site Using Bing Translator Widget



Introduction
This article describes how to translate your website using the Bing Translator Widget.

Description
The Translator web page widget allows you to bring real-time, in-place translation to your web site.

You just need to copy and paste some JavaScript code or API to your website.
Open the following link:
http://www.bing.com/widget/translator
Copy the code.

1.jpeg

Or copy the following code that I copied from that link and paste it into your HTML.
 
<div id='MicrosoftTranslatorWidget' class='Dark' style='color: white; background-color: #555555'>
</div>
<script type='text/javascript'>
                         setTimeout(function () {
{
    var s = document.createElement('script');
    s.type = 'text/javascript'; s.charset = 'UTF-8';
    s.src = ((location && location.href && location.href.indexOf('https') == 0) ? 'https://ssl.microsofttranslator.com' : 'http://www.microsofttranslator.com') + '/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&from=en';
    var p = document.getElementsByTagName('head')[0] || document.documentElement; p.insertBefore(s,
p.firstChild);
    }
}, 0);
</script>

Sample to check
Now create a website and a page and add some content to it.

Now design your screen as in the following screen.

2.jpeg

Or you can copy the following source code:

 
<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <div id='MicrosoftTranslatorWidget' class='Dark' style='color: white; background-color: #555555'>
                    </div>
                    <script type='text/javascript'>
                            setTimeout(function () {
    {
        var s = document.createElement('script');
        s.type = 'text/javascript'; s.charset = 'UTF-8';
        s.src = ((location && location.href && location.href.indexOf('https') == 0) ? 'https://ssl.microsofttranslator.com' : 'http://www.microsofttranslator.com') + '/ajax/v3/WidgetV3.ashx?siteData=ueOIGRSKkd965FeEGM5JtQ**&ctf=True&ui=true&settings=Manual&from=en';
        var p = document.getElementsByTagName('head')[0] || document.documentElement; p.insertBefore(s,
p.firstChild);
    }
}, 0);
                        </script>
                </td>
            </tr>
            <tr>
                <td style="width: 300px; color:Red; padding-top:10px;">
                    C# (pronounced see sharp) is a multi-paradigm programming language encompassing
                    strong typing, imperative, declarative, functional, procedural, generic, object-oriented
                    (class-based), and component-oriented programming disciplines. It was developed
                    by Microsoft within its .NET initiative and later approved as a standard by Ecma
                    (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the programming languages
                    designed for the Common Language Infrastructure. C# is intended to be a simple,
                    modern, general-purpose, object-oriented programming language.[6] Its development
                    team is led by Anders Hejlsberg. The most recent version is C# 5.0, which was released
                    on August 15, 2012.
                </td>
            </tr>
        </table>
    </div>
</form>

Now build your application.

And click on the "Translate" button.

3.jpeg

It will open a panel with all languages and select the language from the list to translate.

4.jpeg

 Here I selected Hindi. So my webpage content will be translated to Hindi.

5.jpeg

Thank you.

To download the Source Click here.

Thursday, 17 October 2013

Get the Battery Details of Your System in Windows Form

Introduction

This article explains how to get the details of the
battery connected to your system. Here I will get the information from the Win32_Battery class.

What Win32_Battery is

The Win32_Battery WMI class a represents battery connected to the computer system..

Design

Create a new Windows Forms Application Project.

Add one button control to the form.

Design your screen as in the following screen:

1.jpeg

Next add a reference for "System.Management".
 


To add the reference use the following procedure.

Go to Solution Explorer, select the project and right-click on that and choose "Add Reference" from the menu.

2.png

A window will open; in that choose the ".Net" tab.

3.jpg

It will show a list. In that list, choose "System.Management" and click the "OK" Button.
4.jpg
 Now go to code view
Add the namespace "using System.Management;".

Write the following code in the Button Click event
:

private
void button1_Click(object sender, EventArgs e)
{
        SelectQuery Sq = new SelectQuery("Win32_Battery");
        ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher(Sq);
        ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
        StringBuilder sb = new StringBuilder();
        foreach (ManagementObject mo in osDetailsCollection)
        {
              sb.AppendLine(string.Format("Availability: {0}", (ushort)mo["Availability"]));
              sb.AppendLine(string.Format("BatteryRechargeTime: {0}", (string)mo["BatteryRechargeTime"]));
              sb.AppendLine(string.Format("BatteryStatus: {0}", (ushort)mo["BatteryStatus"]));
              sb.AppendLine(string.Format("Caption: {0}", (string)mo["Caption"]));
              sb.AppendLine(string.Format("Chemistry: {0}", (ushort)mo["Chemistry"]));
              sb.AppendLine(string.Format("ConfigManagerErrorCode: {0}", (string)mo["ConfigManagerErrorCode"]));
              sb.AppendLine(string.Format("InstallDate: {0}", Convert.ToDateTime(mo["InstallDate"]).ToString()));
              sb.AppendLine(string.Format("ConfigManagerUserConfig: {0}", (string)mo["ConfigManagerUserConfig"]));
              sb.AppendLine(string.Format("CreationClassName : {0}", (string)mo["CreationClassName"]));
              sb.AppendLine(string.Format("Description: {0}", (string)mo["Description"]));
              sb.AppendLine(string.Format("DesignCapacity : {0}", (string)mo["DesignCapacity"]));
              sb.AppendLine(string.Format("DesignVoltage: {0}", (ulong)mo["DesignVoltage"]));
              sb.AppendLine(string.Format("DeviceID : {0}", (string)mo["DeviceID"]));
              sb.AppendLine(string.Format("ErrorCleared: {0}", (string)mo["ErrorCleared"]));
              sb.AppendLine(string.Format("ErrorDescription : {0}", (string)mo["ErrorDescription"]));
              sb.AppendLine(string.Format("EstimatedChargeRemaining: {0}", (ushort)mo["EstimatedChargeRemaining"]));
              sb.AppendLine(string.Format("EstimatedRunTime : {0}", mo["EstimatedRunTime"]).ToString());
              sb.AppendLine(string.Format("ExpectedBatteryLife: {0}", (string)mo["ExpectedBatteryLife"]));
              sb.AppendLine(string.Format("ExpectedLife : {0}", (string)mo["ExpectedLife"]));
              sb.AppendLine(string.Format("FullChargeCapacity: {0}", (string)mo["FullChargeCapacity"]));
              sb.AppendLine(string.Format("LastErrorCode : {0}", (string)mo["LastErrorCode"]));
              sb.AppendLine(string.Format("MaxRechargeTime: {0}", (string)mo["MaxRechargeTime"]));
              sb.AppendLine(string.Format("Name : {0}", (string)mo["Name"]));
              sb.AppendLine(string.Format("PNPDeviceID: {0}", (string)mo["PNPDeviceID"]));
              sb.AppendLine(string.Format("PowerManagementSupported : {0}", mo["PowerManagementSupported"]).ToString());
              sb.AppendLine(string.Format("SmartBatteryVersion: {0}", (string)mo["SmartBatteryVersion"]));
              sb.AppendLine(string.Format("Status : {0}", (string)mo["Status"]));
              sb.AppendLine(string.Format("SystemCreationClassName : {0}", (string)mo["SystemCreationClassName"]));
              sb.AppendLine(string.Format("SystemName: {0}", (string)mo["SystemName"]));
              sb.AppendLine(string.Format("TimeToFullCharge : {0}", (string)mo["TimeToFullCharge"]));
              sb.AppendLine(string.Format("TimeOnBattery: {0}", (string)mo["TimeOnBattery"]));
              UInt16[] PowerManagement = (UInt16[])mo["PowerManagementCapabilities"];
              foreach (uint version in PowerManagement)
              {
                    sb.AppendLine(string.Format("PowerManagementCapabilities: {0}", version.ToString()));
             }
        }
        MessageBox.Show(sb.ToString());
 }


In the code above I am getting the information from Win32_Battery and showing it in a Message Box on a button click.

SelectQuery

It represents a WQL (WMI Query Language) SELECT data query.

ManagementObjectSearcher

It retrieves a collection of management objects based on a specified query.

This class is one of the more commonly used entry points to retrieving management information.

ManagementObjectCollection

It represents various collections of management objects retrieved using WMI.

Now build your application. Click on the button; it will show the Battery details in a Message box.

5.jpeg

  Click here to download Source
Thank you.