Introduction
This article is written to provide an overview and samples for creating your own Web Service for letting your devices connect and communicate over a network (including the internet) with each other, store the data in one place, access and manage the entire database in one place and do various tasks.
The Internet of Things is a concept and phenomenon used to connect the hardware of your house or office over a beloved communication connection, including the nework called the "Internet". This article will provide an overview for you of how 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 and then save it or perform any other service depending on 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 the Internet and ohter networks. No matter what device is calling the service and in which protocol the service is being called, the server would respond and your services would be invoked and ran.
Internet of Things Service
The Internet of Things provides us with some services that can be used in managing and performing various 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 as well as different tasks are done using the Internet of Things. The Internet of Things itself is a concept of connecting devices, more like household appliances, to each other through a common network, the "Internet". From where, they send/receive data from each other and perform the tasks assigned to them. In the preceding 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 an exaggeration.
Creating a service
You create a service where you tell the devices to perform a task when a command is ed 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. A hub acts like a server; it accepts requests, sends responses and then the clients (devices) perform their tasks. Thus, everything seems to work "magically".
Since only one hub is acting as the 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 device gets a trigger for its job.
Web Service
A Web Service is a service (a service can be a method) defined to be executed among more than one devices connected to each other using the 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 and 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 that 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 anything unauthorized can be made invalid and only authorized devices and clients can communicate with 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 suitable for your needs. If the software cannot be changed and customized to make it more secure and more efficient then the software is of no good.
Responses
A 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 was introduced by Microsoft. It can be hosted in a console application or in IIS and can be accessed using 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 using a website to provide an overview of the concept "Internet" connection.
Creating a Web Service
The 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 accustomed to the fancy name "Web Service", it is just a bunch of methods. Similar to a website or other software, you will be able to create functions, create properties, classes and objects.
Our Web Service: A service that provides an interface to the user to enter a data in the service and the service saves that data. The service also looks in for any present data, if the data is present it is shown otherwise 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 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" and so on.
This is why, you will just create a signature of the actual service so that once ing 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 and add references to the libraries required. Once done, add the following code to it. The ISaveData is an interface.
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
-
- using System.ServiceModel;
- using System.Runtime.Serialization;
-
-
- namespace WebServices_Interfaces
- {
-
- [ServiceContract]
- public interface ISaveData
- {
- [OperationContract]
- void AddData(Data s);
-
- [OperationContract]
- Data[] GetCurrentData();
- }
-
-
- [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
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;
-
-
- using System.IO;
-
- namespace WebServices_DataSources
- {
- public class DataSource
- {
-
- static string directory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
-
- static string fileName = "/myServiceFile.txt";
-
-
-
- static List<string> currentData = File.ReadAllLines(directory + fileName).ToList();
-
-
- public void Save(string dataLabel)
- {
- currentData.Add(dataLabel);
- Directory.CreateDirectory(directory);
- File.Create(directory + fileName).Close();
-
- File.WriteAllLines(directory + fileName, currentData);
- }
-
-
- 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 that 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;
-
-
- using WebServices_DataSources;
- using WebServices_Interfaces;
-
-
- namespace WebServices_Service
- {
-
- public class WebService : ISaveData
- {
-
- 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. The 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 nearly 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;
-
-
- 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)
- {
-
- Uri baseAddress = new Uri("http://localhost:8080/My_WebService");
-
-
- using (ServiceHost host = new ServiceHost(typeof(WebService), baseAddress))
- {
-
- ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
- smb.HttpGetEnabled = true;
- smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
- host.Description.Behaviors.Add(smb);
-
-
-
-
-
- host.Open();
-
- Console.WriteLine("The service is ready at {0}", baseAddress);
- Console.WriteLine("Press <Enter> to stop the service.");
- Console.ReadLine();
-
-
- host.Close();
- }
- }
- }
- }
Note: The preceding code was captured using MSDN's document. That document has more code for hosting the applications in managed applications.
Configuring your web service server
Your console application has an App.Config file that can be used to configure its properties and set 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>
-
- <system.serviceModel>
- <services>
- <service name="WebServices_Service.WebService">
-
- <endpoint
- address="http://localhost:8080/My_WebService"
- binding="wsHttpBinding"
- contract="WebServices_Interfaces.ISaveData" />
- </service>
- </services>
- </system.serviceModel>
- </configuration>
You can now run your application. Usually 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 Visual Studio, re-run Visual Studio in 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. the service won't be usable if you remove that part.
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 create a website. You don't need to worry about creating a website or web application using MVC, Windows Forms and so on. Just create a website, I used an 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 right-click on the App_WebReferences folder (where all of the 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 ensure that your service is running (you need to ensure 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.
Now your folder will have files as in this hierarchy:
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 an exception will be raised that nothing was found to capture the request.
This page is just for the sake of letting the 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>();
-
-
- if (IsPost)
- {
- using (ChannelFactory<ISaveData> myServiceProxy =
- new ChannelFactory<ISaveData>("My_WebService_EndPoint"))
- {
- myServiceProxy.Open();
- ISaveData saveDataService = myServiceProxy.CreateChannel();
-
- Data s = new Data();
-
-
- s.DataLabel = Request["text"];
- saveDataService.AddData(s);
- myServiceProxy.Close();
- }
- }
-
-
- using (ChannelFactory<ISaveData> myServiceProxy =
- new ChannelFactory<ISaveData>("My_WebService_EndPoint"))
- {
- myServiceProxy.Open();
-
-
- ISaveData getDataService = myServiceProxy.CreateChannel();
-
-
- Data[] savedData = getDataService.GetCurrentData();
-
-
- foreach (Data data in savedData)
- {
-
- currentData.Add(data.DataLabel);
- }
-
- myServiceProxy.Close();
- }
- }
-
- @{
- Layout = "~/_SiteLayout.cshtml";
- Page.Title = "Home Page";
- }
-
- <ul>
- @if (currentData.Count > 0)
- {
- <p>Current data in the file is as: </p>
-
- foreach (string str in currentData)
- {
-
- <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 backend file that we're having right now. A using is used when you're using any resources, to trigger .NET's functionality to clean and flush the resources.
What happens when the user triggers the SubmitWhen 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 a POST HTTP request. When the user submits the form, the form, along with the text data, is submitted to the server (web service) and there the function is executed to save the data (in the text file).
If the request is not a POST of a simple request then the preceding code block would not execute and nothing will be saved, however the GET function would still execute and cause 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.
The data in the file is like this:
Points of Interest
WCF is the best method to use when creating a Web Service, it runs on your Windows OS since it is developed on the .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.