Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

webservice?


  • Please log in to reply
22 replies to this topic

#1 kenNET

kenNET

    Advanced Member

  • Members
  • PipPipPip
  • 69 posts
  • LocationSweden

Posted 03 January 2011 - 09:22 PM

Hi, Can I connect to a webservice (developed in .NET) and get/post as I do with a regular C# windows application? Thanks!

#2 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 03 January 2011 - 09:55 PM

Hi kenNET, You can call web services, but you'll need to parse the results manually. There might be a component for this, but I'm not sure if it will fit on small microcontrollers like Netduino. Chris

#3 Fred

Fred

    Advanced Member

  • Members
  • PipPipPip
  • 302 posts
  • LocationUK

Posted 03 January 2011 - 09:56 PM

You should be able to, but you'll have to do the work of constructing the HTTP request yourself. Keep it simple. If you're not committed to a web service already I'd suggest looking at something like MVC so you just need to construct a URL or a basic HTTP post on the Netduino. If you do get it working please let us all know how it went.

#4 kenNET

kenNET

    Advanced Member

  • Members
  • PipPipPip
  • 69 posts
  • LocationSweden

Posted 03 January 2011 - 10:06 PM

Thanks for your quick answers. I think I will go for a simple http post to a regular .aspx webpage where I just return commaseparate data, this will reduce data and is easy to parse. Now I just wait for the netduino Plus to be on sale, I want one now ;-) /Ken

#5 Osi

Osi

    New Member

  • Members
  • Pip
  • 3 posts

Posted 06 January 2011 - 02:05 PM

Hello

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;
        }
    }
}


#6 Carsten Dressler

Carsten Dressler

    Member

  • Members
  • PipPip
  • 20 posts

Posted 08 January 2011 - 07:02 PM

I'd suggest you use a RESTful web service instead of a .NET (SOAP/XML) Web Service.

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 Carsten Dressler

Carsten Dressler

    Member

  • Members
  • PipPip
  • 20 posts

Posted 09 January 2011 - 01:44 AM

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();


#8 alum

alum

    New Member

  • Members
  • Pip
  • 2 posts

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 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

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 alum

alum

    New Member

  • Members
  • Pip
  • 2 posts

Posted 01 March 2011 - 12:19 PM

Of course! Thanks alot! No need for socket programming! yay!

#11 Hector Cubillos

Hector Cubillos

    New Member

  • Members
  • Pip
  • 1 posts

Posted 27 November 2011 - 04:57 PM

An unhandled exception of type 'System.Net.WebException' occurred in System.Http.dll please help me :(

#12 NeonMika / Markus VV.

NeonMika / Markus VV.

    Advanced Member

  • Members
  • PipPipPip
  • 209 posts
  • LocationUpper Austria

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 d
own - 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 Hans75

Hans75

    Member

  • Members
  • PipPip
  • 12 posts
  • LocationDen Bosch, Netherlands

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 nakchak

nakchak

    Advanced Member

  • Members
  • PipPipPip
  • 404 posts
  • LocationBristol, UK

Posted 16 July 2012 - 09:59 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.

#15 Hans75

Hans75

    Member

  • Members
  • PipPip
  • 12 posts
  • LocationDen Bosch, Netherlands

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 nakchak

nakchak

    Advanced Member

  • Members
  • PipPipPip
  • 404 posts
  • LocationBristol, UK

Posted 17 July 2012 - 09:10 AM

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.

#17 Hans75

Hans75

    Member

  • Members
  • PipPip
  • 12 posts
  • LocationDen Bosch, Netherlands

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 Stefan

Stefan

    Moderator

  • Members
  • PipPipPip
  • 1965 posts
  • LocationBreda, the Netherlands

Posted 17 July 2012 - 12:34 PM

in the Toolbox.NETMF.NET there is a only a Http_Client...

Interesting, I can't recall I renamed that class once. But it should be HTTP_Client indeed.
"Fact that I'm a moderator doesn't make me an expert in things." Stefan, the eternal newb!
My .NETMF projects: .NETMF Toolbox / Gadgeteer Light / Some PCB designs

#19 Hans75

Hans75

    Member

  • Members
  • PipPip
  • 12 posts
  • LocationDen Bosch, Netherlands

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 Stefan

Stefan

    Moderator

  • Members
  • PipPipPip
  • 1965 posts
  • LocationBreda, the Netherlands

Posted 17 July 2012 - 12:56 PM

And Integratedsocket renamed itself into SimpleSocket?

Nope, SimpleSocket is an interface, Integratedsocket follows that interface.

The reason for that interfacing is to also support managed network drivers, like the wifly driver. As explained here :)
"Fact that I'm a moderator doesn't make me an expert in things." Stefan, the eternal newb!
My .NETMF projects: .NETMF Toolbox / Gadgeteer Light / Some PCB designs




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.