Click here to Skip to main content
15,880,469 members
Articles / Web Development / HTML

Creating a Web Service to be consumed by connected Devices via Internet

Rate me:
Please Sign up or sign in to vote.
4.96/5 (10 votes)
12 Nov 2014CPOL12 min read 60.6K   1.1K   26   15
This article provides an overview for creating a .NET WCF Web Service project that can be used by web applications or devices connected to it through the internet connection.

Introduction

This article is written in order to provide an overview and samples for creating your own Web Service for letting your devices connected through Internet communicate with each other, store the data in one place, access and manage the entire database in one place and perform different tasks. 

Internet of Things is a concept and phenomenon used to connect the hardware of your house or office through over beloved communication connection, the "Internet". This article will provide an overview for you to create your own Web Service and create and manage clients, that would be the devices sending the data to your service. Allow them to send the data to your service, then manage the data, save it or perform any other service according to the data. 

By the end, you will be able to create a simple (or even the enterprise level; if you get the understanding and are willing to create a system of) web service that can run devices connected to it through Internet, no matter what device is calling the service, and in which protocol the service is being called, the server would response and your services would be invoked and ran.

Internet of Things Service

Internet of Things provide us with some services that can be used in managing and performing different tasks depending on the data that was sent to us. You can think of a service like, "start the bulb when it is 6:00AM". Seems fair? 

Similar different task are performed through Internet of Things. Internet of Things itself is a concept of connecting the devices, more like household appliance, to each other through a common network, the "Internet". From where, they send/recieved data from each other and perform the tasks assigned to them. In the above example, if the clock ticks 6:00 in the morning, the message is sent to the bulb for lighting up. I agree this is a bit of exaggeration. 

Creating a service

You create a service where you tell the devices to perform a task when a command is passed down to them. Usually a common hub or host takes a control and each device sends the data to the hub and then the hub decides what to do and from which devices to take the work. Hub acts like a server it accepts requests, sends responses and then the clients (devices) perform their tasks. Thus, everything seems like working as a "magic".

Since only on hub is acting as a server, the service is installed on the hub. Each device connects to it to transmit the data and the hub manipulates the data and executes a service. The service is connected to any device connected and thus that devices get a trigger for its job. 

Web Service

A Web Service is a service (service can be a method) defined to be executed among more than one devices connected to each other through Internet. This is a method, to control the working of the devices connected to the network. 

Not only houses, offices but many giants are also using this service to control their data from each and every device. This provides a better methodology to control the data and the functions being performed by each and every device. You can think of a security service in companies. "If the thumb fingerprint pattern is OK, open the door". This is a service, it depends how people apply it. 

Interacting

Interaction of the devices among each other can be done using many protocols, mechanisms. You can use SOAP, HTML and many more for sending the data and commands to the devices. You can send the data in the format of XML too. 

WCF is a new technology provided by Microsoft, which allows the devices to communicate and send the Metadata over HTML, SOAP, WSDL, XML Schema and WS-Policy. REST services, JSON is also usable. 

Security

It is of a good importance that the Web Service must be made secure so that any unauthorized can be made invalid and only authorized devices and clients can communicate to the hub. SSL and some other standards can be used to set up the security for the devices. 

Customization

A best software service is the one that you can always change and make it suitable for your needs. If the software is unviable to be changed and customized to make it more secure, more efficient then the software is of no good. 

Responses

Web Service must respond to each and every request that has been sent to it. 

WCF is one of the new foundations in the Web Services world and is introduced by Mirosoft. It allows to be hosted in a console application, or in the IIS and can be accessed through Console applications, WPF applications or even websites. This makes it a good fit for today's needs. In this article we will be creating a Web Service that will be hosted in a Console Application and we will use that service through a website to provide an overview of the concept "Internet" connection. 

Web Services

Creating a Web Service

First step is to create a web service. A Web Service is actually just a bunch of methods and functions that are executed whenever a client visits and asks the services to do something or get something. Don't get under the fancy name of "Web Service" it is just a bunch of methods. Similar to a website, or a software, you will be able to create functions, create properties, classes and objects. 

Our Web Service: A service which provides an interface to the user to enter a data in the service and the service saves that data. Service also looks in for any present data, if the data is present it is shown other wise nothing is shown instead of a form to enter the data. 

You can make it more complex and add more functionalities to it to create an enterprise level Web Service to be fully capable of performing the tasks.

Template of the Service

A Service needs to be an interface, why? Because when you need to be calling the service from the client, you don't need to tell him each and every step you're going through and every task you perform. Take an example of you going to your fortune company and giving them an application, the company would just tell you "Application under review", the underlying processes like, "Boss waiting for Application", "Boss reviewing it", "Boss calling secretory to call the employee" etc. 

This is why, you will just create a signature of the actual service so that once passing it down to the client, the client only asks you to "I want to get a job" and then expects a result "Job given" or "Not qualified enough" only. 

Create a Class Library in Visual Studio, and name it WebServices_Interfaces, add references to the libraries required. Once done, add the following code to it. The ISaveData is an interface. 

// Add the references; must also be added to the Project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// Required and added
using System.ServiceModel;
using System.Runtime.Serialization;

// Name of this Class Library Project = WebServices_Interfaces
namespace WebServices_Interfaces
{
    // Following are the ServiceContracts
    [ServiceContract]
    public interface ISaveData
    {
        [OperationContract]
        void AddData(Data s);

        [OperationContract]
        Data[] GetCurrentData();
    }
    
    // DataContracts for the Web Service
    [DataContract]
    public class Data
    {
        private string text;

        [DataMember]
        public string DataLabel
        {
            set { this.text = value; }
            get { return this.text; }
        }
    }
}

Creating a source for the Data

You can however, if you want, continue running the service in its environment for ever and keep the data that is attached to it in the memory or if you want, you can use your storage device to store the data coming to the service and that goes from the service in one place. 

Create a new library, and this time, name it to be WebServices_DataSources, add the references to the libraries and add a new Class file called "DataSource". Once done, the following would be the code inside your file. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// Add this reference, for working with Files
using System.IO;

namespace WebServices_DataSources
{
    public class DataSource
    {
        // Get the current users MyDocuments folder
        static string directory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        // Our File Name. You can change it in your project.
        static string fileName = "/myServiceFile.txt";

        // static variable
        // Will contain the content, for accessing and saving the data
        static List<string> currentData = File.ReadAllLines(directory + fileName).ToList();

        // This method saves the Data sent
        public void Save(string dataLabel)
        {
            currentData.Add(dataLabel);
            Directory.CreateDirectory(directory);
            File.Create(directory + fileName).Close();

            File.WriteAllLines(directory + fileName, currentData);
        }

        // Gets the current list.
        public List<string> GetDataList()
        {
            return currentData;
        }
    }
}

Implementing the Service in your Application

The next step is to implement the service in an application, that can be used and would contain the methods for your actual Web Service. You can see the Interface however only contains the signatures for your web service. This would serve as the actual web service and will be reached our by the devices each time they need to save the data. 

Create a new library, add references to your WebServices_Interfaces and WebServices_DataSources, which are required by your web service to use. Name this library project to be WebServices_Service, and this class would implement the ISaveData interface, so that you can add the body to the signatures the interface has. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// add the projects in this project
using WebServices_DataSources;
using WebServices_Interfaces;


namespace WebServices_Service
{
    // Implements the ISaveData
    public class WebService : ISaveData
    {
        // Adds the Body to the methods
        public void AddData(Data d)
        {
            DataSource ds = new DataSource();
            ds.Save(d.DataLabel);
        }

        public Data[] GetCurrentData()
        {
            DataSource sd = new DataSource();
            List<string> dataList = sd.GetDataList();
            Data[] dataArray = new Data[dataList.Count];
            for (int i = 0; i < dataList.Count; i++)
            {
                Data s = new Data();
                s.DataLabel = dataList[i];
                dataArray[i] = s;
            }
            return dataArray;
        }
    }
}

You can see, this code has the actual job of the service, when you call AddData you can see that it actually adds the data in the DataSource and upon GetCurrentData it gets the data from the DataSource and returns it to the user. User can then use it, to perform other tasks. 

Hosting your Web Service

You've created the application, good. But how are others going to use it when you're not going to set any location for it to be present at. Think of it as a bag of money, but you've no idea where it is. 

You can host your web service in almost any application, from Console to Web Applications. But since this article seems to provide an overview I will cover this topic using a Console Application that will continue running and hosting the application. The Console would accept all of the requests being made to it, you can set a Uri for the resources and the console would serve as a server at that location. 

Create a Console application, add the references to our three libraries and then add the following code to the Program.cs file created in your application. Name

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// add the references to the libraries required.
using WebServices_Interfaces;
using WebServices_Service;
using WebServices_DataSources;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WebServices_HostingAndRunning
{
    class Program
    {
        static void Main(string[] args)
        {
            // the Uri for this Web Service.
            Uri baseAddress = new Uri("http://localhost:8080/My_WebService");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(WebService), baseAddress))
            {
                // Enable metadata publishing. 
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}

Note: The above code was captured through MSDN's document. That document has more codes for hosting the applications in mananged applications. 

Configuring your web service server 

Your console application has an App.Config file, that can be used to configure its properties and setting some properties to it. Edit it, or replace it with the following code, 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <!-- Server Configuration is as following -->
  <system.serviceModel>
    <services>
      <service name="WebServices_Service.WebService">
        <!-- baseAddress and the Interface of the Service is added.  -->
        <endpoint
                address="http://localhost:8080/My_WebService" 
                binding="wsHttpBinding" 
                contract="WebServices_Interfaces.ISaveData" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

You can run your application, mostly you're going to get an error saying it was not able to get the Uri http://+:8080 something like this. Don't worry, just close the Visual Studio, re-run the Visual Studio in the Administrator mode and re-run the application, this time it will run and will show the message saying the service is running at the {baseAddress}. You can always change the baseAddress for your application. 

The serving of the Metadata is also necessary, don't remove that code. Service won't be usable if you remove that part.

Service Running

Creating a Client

The client is the device or a program that consumes the service that you've created. You can use a website as a service client, or an application developed as a console or Windows Forms to consume your web service and communicate with other devices. 

In our project, we will create a website to consume the web service. This web site will provide an interface to the user where he can enter data (text) and submit to add the data, he can also view the currently added data to the storage devices. 

Create a Website

You should first of all create a website, you don't need to worry about creating a website or web application, using MVC, Win Forms etc. Just create a website, I used ASP.NET StarterSite (Empty CSHTML) website. 

To use the service, you will be required to add the references to your service. But first add the references to the System.ServiceModel. Once done, add the reference to your libraries. 

Adding a reference to the Service is a tricky part here, you need to be Right clicking on the App_WebReferences folder (where all of service references are present); if the folder isn't present, create it because it is initially not created, and then select Add Service Reference. The pop up would generate for you, to enter the Uri for the service. At this stage before continuing, you need to make sure that your service is running (you need to make sure the Console Application is running, and the message saying Web Service is running at {baseAddress}). You can enter the Uri, and continue. It will automatically find the web service and will add the required code and files for using the services. 

Adding reference (Website)

Now your folder would have files like this hierarchy, 

Folder of Web Service reference

Creating a landing page

Now once these things are done, you can create a good looking home page to land the user (client) on. Where he will be able to find a form to send the data to the service. 

Remember: The service must be running, otherwise Exception will be raised that nothing was found to capture the request.

This page is just for the sake of letting user understand the interface, if you're creating the service application for devices where you don't want to create any form. You can simply get the data from the requests that the device makes and get the data associated with the request. 

@using System.ServiceModel;
@using WebServices_Interfaces;

@{
    List<string> currentData = new List<string>();
    // Enroll the student
    
    if (IsPost)
    {
        using (ChannelFactory<ISaveData> myServiceProxy =
        new ChannelFactory<ISaveData>("My_WebService_EndPoint"))
        {
            myServiceProxy.Open();
            ISaveData saveDataService = myServiceProxy.CreateChannel();
            // Create the Instance...
            Data s = new Data();
            
            // Get the Text
            s.DataLabel = Request["text"];
            saveDataService.AddData(s);
            myServiceProxy.Close();
        }
    }

    // Load the data from the Server
    using (ChannelFactory<ISaveData> myServiceProxy =
    new ChannelFactory<ISaveData>("My_WebService_EndPoint"))
    {
        myServiceProxy.Open();
        
        // Create the Channel for the Client to work from
        ISaveData getDataService = myServiceProxy.CreateChannel();
        
        // Get the current Data
        Data[] savedData = getDataService.GetCurrentData();
        
        // Work on Each of the Data
        foreach (Data data in savedData)
        {
            // Add the data to the List (Look in the first line)
            currentData.Add(data.DataLabel);
        }
        // Close the service proxy
        myServiceProxy.Close();
    }
}

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Home Page";
}

<ul>
    @if (currentData.Count > 0)
    {
        <p>Current data in the file is as: </p>
        // if there is any content present, then
        foreach (string str in currentData)
        {
            // Write those data.
            <li>@str</li>
        }
    }
</ul>

<div>
    <p>Use the following form to add the content.</p>
    <form method="post">
        <input type="text" name="text" />
        <input type="submit" value="Submit" />
    </form>
</div>

Initially the page wouldn't contain anything but just a form since there is no data in the back end file that we're having right now. using is used when you're using any resources, to trigger .NET's functionality to clean and flush the resources. 

Form input only

What happens when the user triggers the Submit

When the user hits the submit button, the website makes a request to the Web Service (that is currently being hosted and run in the Console Application; and it must be running) and executes the function to save the data. This is only present if the request is POST Http request. When the user submits the form, the form alongwith the text data is submitted to the server (web service) and there the function is executed to save the data (in the .txt file). 

If the request is not POST, a simple request then the above code block would not execute and nothing will be saved, however the GET function would still execute and causing the web service to return the currently available data in the storage medium. 

So, if there is any data present the page would like this. 

HTML page with some data

The data in the File is like this, 

Data in the txt file

Points of Interest

WCF is the best method to use while creating a Web Service, it runs on your Windows OS since it is developed on .NET framework. You can send requests and get responses in SOAP, REST and many more. XML, JSON and other syntaxes are supported in it. You can host this service in any application and get any device as its client. 

History

First post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
Questionwwsapi Web Service in native c++ to be consumed via Internet Pin
Member 1141522030-Jan-15 6:11
Member 1141522030-Jan-15 6:11 
AnswerRe: wwsapi Web Service in native c++ to be consumed via Internet Pin
Afzaal Ahmad Zeeshan4-Jul-15 4:31
professionalAfzaal Ahmad Zeeshan4-Jul-15 4:31 
GeneralMy vote of 5 Pin
Sergey Alexandrovich Kryukov22-Dec-14 4:35
mvaSergey Alexandrovich Kryukov22-Dec-14 4:35 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan22-Dec-14 5:03
professionalAfzaal Ahmad Zeeshan22-Dec-14 5:03 
GeneralMy vote of 5 Pin
User 110609792-Dec-14 22:27
User 110609792-Dec-14 22:27 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan3-Dec-14 0:30
professionalAfzaal Ahmad Zeeshan3-Dec-14 0:30 
GeneralMy vote of 5 Pin
Abhishek Nandy23-Nov-14 21:35
professionalAbhishek Nandy23-Nov-14 21:35 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan24-Nov-14 2:01
professionalAfzaal Ahmad Zeeshan24-Nov-14 2:01 
GeneralMy vote of 3 Pin
Member 1123288813-Nov-14 20:24
Member 1123288813-Nov-14 20:24 
AnswerRe: My vote of 3 Pin
Afzaal Ahmad Zeeshan13-Nov-14 21:38
professionalAfzaal Ahmad Zeeshan13-Nov-14 21:38 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun12-Nov-14 17:41
Humayun Kabir Mamun12-Nov-14 17:41 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan12-Nov-14 17:54
professionalAfzaal Ahmad Zeeshan12-Nov-14 17:54 
GeneralMy vote of 5 Pin
Mahsa Hassankashi12-Nov-14 8:20
Mahsa Hassankashi12-Nov-14 8:20 
AnswerRe: My vote of 5 Pin
Afzaal Ahmad Zeeshan12-Nov-14 8:22
professionalAfzaal Ahmad Zeeshan12-Nov-14 8:22 
GeneralRe: My vote of 5 Pin
lissacoffey3-Jul-15 21:10
lissacoffey3-Jul-15 21:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.