WebService using C#

Web Service

Web Service is a software component for application to application communication.

There are two types of web services in Microsoft .Net framework. One is XML web services another one is .Net Remoting. In this article we are going to discuss about xml web service.

Web services are invoked remotely using SOAP or HTTP-GET and HTTP-POST protocols. Web service based on xml and returns the values in xml format.

Let we start our first web service…

Here I’m going to start my first web service as follows and named MyFirstService.





There is a .cs file in App_Code will be created. This is our class file for writing program.

Then a file Service.asmx will be created. This is our web service url.

Let me explain the simple web service method that returns an integer value with adding two integer values.

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service ()
{
}

[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public int add(int a, int b)
{
return a + b;
}

}

Here the HelloWorld function is default function when we create the web service project.

The add function which is have two parameters (a & b) and return an integer value.

Running the program, and do as follows,







Click the add function…




Here we should have to give the parameter.
Give the value as a=10 and b=10 and click the button Invoke.

After you will get the xml file as follows,

Hence we could create the service for adding two integer values.

CacheDuration attribute in Web Service

This attribute specifies the length of time in seconds that the method should cache the results.

For example,

[WebMethod(CacheDuration=30)] //Here 30 is seconds
public int add(int a, int b)
{
return a + b;
}

Description in WebMethod

We can add description in our web service’s WebMethod as follows,

[WebMethod(CacheDuration=30,Description="Returns added value.")] public int add(int a, int b)
{
return a + b;
}

We can see the description in the following picture marked in red.



How to use webService in web application using C#

Yes..its a main thing how to use webservice in my application. Its very easy thing to use web service in our application by using AddWebReference. In the solution explorer we can find AddWebReference when we right click that solution explorer. Click that…

There is a window will open as follows,





There is 3 options for adding our web reference.
- Web Services in this solution
Finding web service in your solution.
- Web services on the local machine
Finding web service in local machine or localhost.
- Browse UDDI Servers on the local network

Give your webservice url in that url column. And click Go…and give the web reference name as follows…






Then click the Add Reference button. Now see your solution explorer, there will be some new files with extensions .disco and .wsdl

Then put the namespace as

using myService;

And create object for that service then call the method in web service as follows,

Service service = new Service();
int result = service.add(10, 10);

this will return the value as 20.

That’s it…


...S.VinothkumaR.

Read And Write Registry Value using C#.

Hi Friends….

Here is the code for read the registry value using C#.

First I’m creating registry key value and string value in local machine as follows,

myKey --> key value
myValue --> string name
myReturnValue --> string value

Snapshots for registry values setting...





Code for Registry value Reading using C#...
using Microsoft.Win32;

try
{
RegistryKey registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\myKey");
if (registry != null)
{
MessageBox.Show(registry.GetValue("myValue"));
registry.Close();
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}

Code for Values writing in Registry using C#.

using Microsoft.Win32;

try
{
RegistryKey registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\myKey");
if (registry != null)
{
registry.SetValue("myValue", "myReturnValue");
registry.Close();
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}

Cheers....

... S.VinothkumaR.

CD Door Open and Close

Hi,

Here is sample code for open the CD door and close using C#...

Just try...

using System.Runtime.InteropServices;
using System.Text;

[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)]
protected static extern int mciSendString(string mciCommand, StringBuilder returnValue, int returnLength, IntPtr callback);

int result = mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);

result = mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);


...S.VinothkumaR

Getting IP Address using C#

Hi Viewers,

Here is I'm trying to get IP address in a web application when it's page load using C#. The following code will help u for getting IP address....

using System.Net;

string hostName = Dns.GetHostName();

IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName);

IPAddress[] ipAddress = iPHostEntry.AddressList;

for (int i = 0; i < ipAddress.Length; i++)

{

Response.Write(ipAddress[i].ToString());

}



S.VinothkumaR

Empty the Recycle Bin using C#

Here is sample coding for how to empty the recycle bin using C#.

We can clear the recycle bin easily by using the Shell32.dll as follows,

First of all we need to create an enum as follows,
enum RecycleFlags : uint
{
SHERB_NOCONFIRMATION = 0x00000001,
SHERB_NOPROGRESSUI = 0x00000002,
SHERB_NOSOUND = 0x00000004
}
And then, import the Shell32.dll using the DllImport class which is in System.Runtime.InteropServices namespaces. And creating the functionality SHEmptyRecycleBin as follows,

[DllImport("Shell32.dll",CharSet=CharSet.Unicode)]
static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);

In my project I have two buttons like “Clear the RecycleBin” and “Exit”.

When clicking the Clear the RecycleBin, we have to clear the recyclebin. So the following code will help for do that function. Copy the following code in to that button clicking event.


try
{
uint result = SHEmptyRecycleBin(IntPtr.Zero, null, 0);
MessageBox.Show(this,"Done !","Empty the
RecycleBin",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(this, "Failed ! " + ex.Message, "Empty the
RecycleBin", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Application.Exit();
}


Exit the application when click the “Exit” button.

Application.Exit();

Now run the program,




Click the “Clear the Recycle Bin”




The confirmation window will appear for deleting all items for delete all items in the Recycle Bin.

Give yes to delete all items from Recycle Bin.



Yes…that’s it...
Cheers...
...S.VinothkumaR.

ASP.NET Menu using Sitemap

Asp.Net menu control displays menu statically or dynamically using Sitemap Data Source control, which using site map control in ASP.Net. Here I am going to explain how to display menu using sitemap control.

Creating Sitemap file.


From Visual Studio 2005 we can easily create the sitemap file by right clicking the website in the solution explorer, choosing Add NewItem, and then selecting the Site Map icon. The created file has a few XML elements.

The element can have a number of attributes. Here is some attributes which are mostly using,

- title (Specifies the title of the section).
- url (Specify the url of section. It must have unique).
- description (Specify the description of the section. Used in alt attribute).

Creating Master Page.


Create a master page in our website by right clicking the website in the solution explorer, choosing Add NewItem, and then selecting MasterPage icon. I'm going to link some aspx pages through our menu. So now we have to create some .aspx pages as a content page of masterpage. We can create aspx pages by right clicking the masterpage and choose the add content page, then rename it. Here we are going to create four pages namely Main.aspx, Menu1.aspx, Menu2.aspx and SubMenu1.aspx.

After completing this process go to master page and copy the following code




From the above, SiteMapDataSource is set to asp:Menu datasource. Then copy the following code in to sitemap file.



Now run the project …

That’s it…

If you want to download the program come here...

Cheers....

...VinothkumaR.




Advantages of VB.NET

Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading that makes it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. Other new language features in Visual Basic .NET include structured exception handling, custom attributes, and common language specification (CLS) compliance.

The CLS is a set of rules that standardizes such things as data types and how objects are exposed and interoperate. Visual Basic .NET adds several features that take advantage of the CLS. Any CLS-compliant language can use the classes, objects, and components you create in Visual Basic .NET. And you, as a Visual Basic user, can access classes, components, and objects from other CLS-compliant programming languages without worrying about language-specific differences such as data types. CLS features used by Visual Basic .NET programs include assemblies, namespaces, and attributes. These are the new features to be stated briefly:
Inheritance
Visual Basic .NET supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived classes inherit and can extend the properties and methods of the base class. They can also override inherited methods with new implementations. All classes created with Visual Basic .NET are inheritable by default. Because the forms you design are really classes, you can use inheritance to define new forms based on existing ones.

Exception Handling
Visual Basic .NET supports structured exception handling, using an enhanced version of the Try…Catch…Finally syntax supported by other languages such as C++.Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code, and filters. Structured exception handling makes it easy to create and maintain programs with robust, comprehensive error handlers.
Overloading
Overloading is the ability to define properties, methods, or procedures that have the same name but use different data types. Overloaded procedures allow you to provide as many implementations as necessary to handle different kinds of data, while giving the appearance of a single, versatile procedure. Overriding Properties and Methods The Overrides keyword allows derived objects to override characteristics inherited from parent objects. Overridden members have the same arguments as the members inherited from the base class, but different implementations. A member’s new implementation can call the original implementation in the parent class by preceding the member name with MyBase.
Constructors and Destructors
Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free system resources when a class leaves scope or is set to Nothing. Visual Basic .NET supports constructors and destructors using the Sub New and Sub Finalize procedures.
Data Types
Visual Basic .NET introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode characters. It is equivalent to the .NET Framework System. Char data type. The Short data type, a signed 16-bit integer, was named Integer in earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power of 10. In earlier versions of Visual Basic, it was available only within a Variant.

Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, do not provide implementations. The Interface statement allows you to declare interfaces, while the Implements statement lets you write code that puts the items described in the interface into practice.

Delegates
Delegates objects that can call the methods of objects on your behalf are sometimes described as type-safe, object-oriented function pointers. You can use delegates to let procedures specify an event handler method that runs when an event occurs. You can also use delegates with multithreaded applications. For details, see Delegates and the AddressOf Operator.
Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are useful when multiple objects need to use information that is common to all. Shared class methods can be used without first creating an object from a class.

References
References allow you to use objects defined in other assemblies. In Visual Basic .NET, references point to assemblies instead of type libraries. For details, see References and the Imports Statement. Namespaces Namespaces prevent naming conflicts by organizing classes, interfaces, and methods into hierarchies.

Assemblies
Assemblies replace and extend the capabilities of type libraries by, describing all the required files for a particular component or application. An assembly can contain one or more namespaces.

Attributes
Attributes enable you to provide additional information about program elements. For example, you can use an attribute to specify which methods in a class should be exposed when the class is used as a XML Web service. MultithreadingVisual Basic .NET allows you to write applications that can perform multiple tasks independently. A task that has the potential of holding up other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on threads that are separate from your user interface, multithreading makes your applications more responsive to user input.
Cheers....
...S.VinothkumaR.

Serialization and Deserialization in VB.NET

Serialization is a process through which an object's state is transformed into some serial data format, such as XML or binary format.

The reverse process of Serialization is De Serialization.

For the process of serialization we need two things. One is a Formatter and another is a Stream Object.
The class written below is the class whose object is going to be serialized. For that purpose, the attribute are added.

Public Class DataDescription

Public Data As Integer
Public Description As String

Public Sub New(ByVal NewData As Integer, ByVal NewDescription As String)
Data = NewData
Description = NewDescription
End Sub

Public Overrides Function ToString() As String

Return Description

End Function

End Class

Serialization function is…

Public Function SerializeData(ByVal oDataToBeSerialized As Object) As System.IO.MemoryStream

Dim oFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()

Dim oStream As New System.IO.MemoryStream()
oFormatter.Serialize(oStream, oDataToBeSerialized)
Return oStream

End Function

De-Serialization

Deserialization is the process of using the serialized state information to regain the object from the serialized shape to its original shape.

So, it is basically the reverse process of the Serialization. (The name also suggests De-Serialization)

Public Function DeSerializeData(ByVal oStream As System.IO.MemoryStream) As Object
Dim oFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim oReturnObject As Object
oStream.Position = 0
oReturnObject = oFormatter.Deserialize(oStream)
Return oReturnObject
End Function


Cheers...


...S.VinothkumaR

Delegates in C#

An interesting feature in C# is Delegate. Delegates are best complemented as new type of Object in C#. They are also represented as pointer to functions. Technically delegate is a reference type used to encapsulate a method with a specific signature and return type.



There are two types of delegates available in C#.

1. Single Delegate
2. Multi-cast Delegate

Here is the example of delegate as follows,



using System;
namespace testWinApp
{

// 1. Define delegate.

public delegate double UnitConversion(double from);

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
} // 2. Define handler method.

public static double FeetToInches(double feet)
{
return feet * 12;
}

private void button4_Click(object sender, EventArgs e)
{ // 3. Create delegate instance.

UnitConversion doConversion = new UnitConversion(FeetToInches);

// 4. Use delegate just like a method.

double inch = doConversion(4);
MessageBox.Show(inch.ToString());
}
}
}

Result will be as follows,




Cheers...

...S.VinothkumaR

Draw String in SmartDevice using VC++ Win32.

Normally we can draw string in VC++ win32 files using the TextOut() function which is in the headerfile wingdi.h.

But, smart device not support the TextOut() function. So we can draw string in smart devices using ExtTextOut(). function only.

Here is an example for how to use ExtTextOut() in VC++ Win32 application....

First we need to include the header file windows.h.

then call the function ExtTextOut() in WM_PAINT event for draw string as follows,

case WM_PAINT:
hdc=BeginPaint(hDlg,&ps);
lpString=L"This is the DrawString test"; // Here lpString is LPCWSTR. Declare in global
ExtTextOut(hdc, 10, 10, ETO_CLIPPED, NULL, lpString, _tcslen(lpString), NULL);
EndPaint(hDlg, &ps);
break;

Just run and get.....

Thats it....

Cheers....

...S.VinothkumaR.

Reflection in .NET

All .NET assemblies have metadata information stored about the types defined in modules. This metadata information can be accessed by mechanism called as “Reflection”. System. Reflection can be used to browse through the metadata information.

Using reflection you can also dynamically invoke methods using System.Type.Invokemember. Below is sample source code

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim Pobjtype As Type
Dim PobjObject As Object
Dim PobjButtons As New Windows.Forms.Button()
Pobjtype = PobjButtons.GetType()

For Each PobjObject In Pobjtype.GetMembers
LstDisplay.Items.Add(PobjObject.ToString())
Next
End Sub
End Class




Sample reflection display


Cheers...

...S.VinothkumaR.