webservice?
#1
Posted 03 January 2011 - 09:22 PM
#2
Posted 03 January 2011 - 09:55 PM
#3
Posted 03 January 2011 - 09:56 PM
#4
Posted 03 January 2011 - 10:06 PM
#5
Posted 06 January 2011 - 02:05 PM
I used socketclient sample from .Net Microframework SDK to call a web service. There is a better way I'm sure, but I'm newbie and I wanted to port my Arduino code fast.
It works.
Regards,
Mark
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.NetduinoPlus; using Socket = System.Net.Sockets.Socket; namespace NetduinoPlus_Temperature_Logger { public class Program { static OutputPort led = new OutputPort(Pins.ONBOARD_LED, false); static bool pressing = false; static string httpserver = "10.146.104.211"; static Int32 httpport = 81; static string SensorID = "000000000000000000000000000000000001"; public static void Main() { InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth); button.OnInterrupt += new NativeEventHandler(button_OnInterrupt); while (true) { if (!pressing) { led.Write(true); Thread.Sleep(250); led.Write(false); Thread.Sleep(250); } } } static void button_OnInterrupt(uint data1, uint data2, DateTime time) { pressing = data2 == 0; String request = "POST /SensorService.asmx HTTP/1.1\n"; request += "Host: " + httpserver + "\n"; request += "Content-Type: text/xml; charset=utf-8\n"; request += "Content-Length: 418\n"; request += "SOAPAction: \"http://" + httpserver + "/StoreData\"\n\n"; request += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; request += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"; request += "<soap:Body>\n"; request += "<StoreData xmlns=\"http://" + httpserver + "/\">\n"; request += "<password>upstempdata</password>\n"; request += "<Value>"; request += "22.22"; request += "</Value>\n"; request += "<SensorID>"; request += SensorID; request += "</SensorID>\n"; request += "</StoreData>\n"; request += "</soap:Body>\n"; request += "</soap:Envelope>\n\n"; try { String html = Post(httpserver, httpport, request); Debug.Print(html); } catch (SocketException se) { Debug.Print("SocketException when connecting to " + httpserver + ":" + httpport); Debug.Print("If your network uses IPSec, you may need enable the port manually"); Debug.Print("Socket Error Code: " + se.ErrorCode.ToString()); Debug.Print(se.ToString()); } } /// <summary> /// Issues a http POST request on the specified server. /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <param name="request"></param> /// <returns></returns> private static String Post(String server, Int32 port, String request) { const Int32 c_microsecondsPerSecond = 1000000; // Create a socket connection to the specified server and port. using (Socket serverSocket = ConnectSocket(server, port)) { // Send request to the server. Byte[] bytesToSend = Encoding.UTF8.GetBytes(request); serverSocket.Send(bytesToSend, bytesToSend.Length, 0); // Reusable buffer for receiving chunks of the document. Byte[] buffer = new Byte[1024]; // Accumulates the received page as it is built from the buffer. String page = String.Empty; // Wait up to 30 seconds for initial data to be available. Throws an exception if the connection is closed with no data sent. DateTime timeoutAt = DateTime.Now.AddSeconds(30); while (serverSocket.Available == 0 && DateTime.Now < timeoutAt) { System.Threading.Thread.Sleep(100); } // Poll for data until 30-second timeout. Returns true for data and connection closed. while (serverSocket.Poll(30 * c_microsecondsPerSecond, SelectMode.SelectRead)) { // If there are 0 bytes in the buffer, then the connection is closed, or we have timed out. if (serverSocket.Available == 0) break; // Zero all bytes in the re-usable buffer. Array.Clear(buffer, 0, buffer.Length); // Read a buffer-sized HTML chunk. Int32 bytesRead = serverSocket.Receive(buffer); // Append the chunk to the string. page = page + new String(Encoding.UTF8.GetChars(buffer)); } // Return the complete string. return page; } } /// <summary> /// Creates a socket and uses the socket to connect to the server's IP address and port. /// </summary> /// <param name="server"></param> /// <param name="port"></param> /// <returns></returns> private static Socket ConnectSocket(String server, Int32 port) { // Get server's IP address. IPHostEntry hostEntry = Dns.GetHostEntry(server); // Create socket and connect to the server's IP address and port Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(hostEntry.AddressList[0], port)); return socket; } } }
- TechnoGuy likes this
#6
Posted 08 January 2011 - 07:02 PM
RESTful web services use basic HTTP GET/POST commands to process stuff. Normally the data returned is a JSON format (alot easier to work with compared to XML).
You can create a WCF RESTFul web services using IIS or selfhosted (exe).
Here is a Self-Hosted Web Service:
Imports System.ServiceModel Imports System.ServiceModel.Channels Imports System.ServiceModel.Web <ServiceContract()> _ Public Class WCF <OperationContract()> _ <WebGet(RequestFormat:=WebMessageFormat.Json, UriTemplate:="add&a={A1}&b={B1}")> _ Public Function Add(ByVal A1 As String, ByVal B1 As String) As Integer Return A1 + B1 End Function End Class
Imports System Imports System.ServiceModel Imports System.ServiceModel.Description Module Program Private _WS As servicehost Sub Main() Dim _uri As New Uri("http://" + Environment.MachineName + ":81/Pool") _WS = New ServiceHost(GetType(WCF), _uri) Dim ep As ServiceEndpoint = _WS.AddServiceEndpoint(GetType(WCF), New WebHttpBinding, String.Empty) ep.Behaviors.Add(New WebHttpBehavior) _WS.Open() Console.WriteLine("Ready") Console.Read() End Sub End Module
Then to call the web service, you can use your web broswer to test. For example
http://hostname:81/P...ool/add?a=1&b=2
Hope that makes since....
#7
Posted 09 January 2011 - 01:44 AM
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://xxx:81/Pool/add?a=1&b=4"); myReq.Method = "GET"; HttpWebResponse WebResp = (HttpWebResponse)myReq.GetResponse();
#8
Posted 28 February 2011 - 06:57 PM
BTW, you could call the RESTful web service like this from the Netduino:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://xxx:81/Pool/add?a=1&b=4"); myReq.Method = "GET"; HttpWebResponse WebResp = (HttpWebResponse)myReq.GetResponse();
I can't import HttpWebRequest. Are you sure this is possible?
#9
Posted 01 March 2011 - 01:25 AM
I can't import HttpWebRequest. Are you sure this is possible?
Have you added the System.Net.Http.dll assembly as a reference to your project (or equivalent)?
Chris
#10
Posted 01 March 2011 - 12:19 PM
#11
Posted 27 November 2011 - 04:57 PM
#12
Posted 28 November 2011 - 09:18 AM
An unhandled exception of type 'System.Net.WebException' occurred in System.Http.dll
please help me
Could you show us the code area in which this exception is thrown?
NeonMika.Webserver
> Control your N+ and write webservice methods easyily
> Receive data from you N+ (in XML or JSON)
> Browse the SD on your N+ directly in the browser and down - and upload files
If you need help with NeonMika.Webserver, please just leave a note in the thread and/or contact me via Skype
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
--- Mistakes teach you important lessons. Every time you make one, you are one step closer to your goal. ----
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
#13
Posted 15 July 2012 - 12:05 PM
BTW, you could call the RESTful web service like this from the Netduino:
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://xxx:81/Pool/add?a=1&b=4"); myReq.Method = "GET"; HttpWebResponse WebResp = (HttpWebResponse)myReq.GetResponse();
Does anyone have an complete example of this?.. I cant get it to work..(been fiddling all weekend..), managed to get a REST webservice on asp.net up and running,
but cant read it with my netduino.
#14
Posted 16 July 2012 - 09:59 AM
#15
Posted 17 July 2012 - 06:54 AM
That's pretty much all their is to it, however that snippet you posted is using port 81 not port 80.
Also have you opened the relevant ports on your windows firewall?
By default you need to allow all traffic on port 80 (for http) to your windows box for your web service to connect
Nak.
guess port 80, for http, is always open.. thats not my issue...
i am struggling and confused with all the drivers/dll to be used, and how they relate to each other..
System.Net, System.Net.Sockets System.Threading Microsoft.SPOT Microsoft.SPOT.Hardware, SecretLabs.NETMF.Hardware SecretLabs.NETMF.Hardware.NetduinoPlus?
i was getting close.. i get the message that .GetResponse is not recognized.. and should be .GetBeginResponse which, after googling, opened a few pages of additional code i dont understand.
#16
Posted 17 July 2012 - 09:10 AM
Where is the computer located that you are trying to connect to?
If you want a simple to use HTTP client for your netduino i would recommend the one in Stefan's netmf toolbox. Then you can use simple code like this:
using System; using System.IO.Ports; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using Microsoft.SPOT.Net.NetworkInformation; using SecretLabs.NETMF.Hardware.NetduinoPlus; using Toolbox.NETMF.NET; namespace HTTPClient { public class Program { var webClient = new HttpClient(new IntegratedSocket(http://xxx, 80)); var response = webClient.Get("/Pool/add?a=1&b=4"); if(response.ResponseCode != 200) { Debug.Print("Invalid Response"); } Debug.Print(response.ResponseBody); Thread.Sleep(Timeout.Infinite); } }
Nak.
#17
Posted 17 July 2012 - 12:29 PM
Check that inbound port 80 is allowed, outbound port 80 is always open, but inbound is nearly always closed unless you have explicitly opened it.
Where is the computer located that you are trying to connect to?
If you want a simple to use HTTP client for your netduino i would recommend the one in Stefan's netmf toolbox. Then you can use simple code like this:
using System; using System.IO.Ports; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using Microsoft.SPOT.Net.NetworkInformation; using SecretLabs.NETMF.Hardware.NetduinoPlus; using Toolbox.NETMF.NET; namespace HTTPClient { public class Program { var webClient = new HttpClient(new IntegratedSocket(http://xxx, 80)); var response = webClient.Get("/Pool/add?a=1&b=4"); if(response.ResponseCode != 200) { Debug.Print("Invalid Response"); } Debug.Print(response.ResponseBody); Thread.Sleep(Timeout.Infinite); } }
Nak.
I still have the same issue::
using System;
using System.IO.Ports;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Net.NetworkInformation;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using Toolbox.NETMF.NET;
namespace HTTPClient {
public class Readservice {
public static void Main()
{
var webClient = new HttpClient(new IntegratedSocket("http://xxx, 80"));
it cant find HttpClient!
Error 1 The type or namespace name 'HttpClient' could not be found (are you missing a using directive or an assembly reference?)
Error 2 The type or namespace name 'IntegratedSocket' could not be found (are you missing a using directive or an assembly reference?) E:\VS2010\Netduino\georgiposted\Readserver.cs
in the Toolbox.NETMF.NET there is a only a Http_Client...
#18
Posted 17 July 2012 - 12:34 PM
Interesting, I can't recall I renamed that class once. But it should be HTTP_Client indeed.in the Toolbox.NETMF.NET there is a only a Http_Client...
My .NETMF projects: .NETMF Toolbox / Gadgeteer Light / Some PCB designs
#19
Posted 17 July 2012 - 12:40 PM
Interesting, I can't recall I renamed that class once. But it should be HTTP_Client indeed.
And Integratedsocket renamed itself into SimpleSocket?
#20
Posted 17 July 2012 - 12:56 PM
Nope, SimpleSocket is an interface, Integratedsocket follows that interface.And Integratedsocket renamed itself into SimpleSocket?
The reason for that interfacing is to also support managed network drivers, like the wifly driver. As explained here
My .NETMF projects: .NETMF Toolbox / Gadgeteer Light / Some PCB designs
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users