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.
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.
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 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;
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
, 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;
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. 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;
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 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,
="1.0" ="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 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.
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.
Now your folder would have files like 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 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>();
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>
// 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.
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.
The data in the File is like this,
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