SOAP Client Examplw with CSharp.net

Gurus,

Can you throw me a CSharp.net SOAP example that works? I have looked the ones online already, please do not point me to the websites that doesn't work.

A simple example will do.

Thanks
Leo0
Leo01Asked:
Who is Participating?
 
GeorgeGerguesCommented:
really there is nothing else to it

here is another full example.
http://www.deitel.com/articles/csharp_tutorials/20051126/csharpWebServices_Part1.html

it is all managed by .NET

best of luck.
0
 
bartvdCommented:
This SOAP example is a combination of two posted on the internet, it works for me.

Use it like this: UPnP.OpenFirewallPort(80,"MyBrowser",true);//open port
Use it like this: UPnP.OpenFirewallPort(80,"MyBrowser",false);//close port

If this does not work check if your router is UPnP enabled.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;

namespace SendFiles
{
   
public class UPnP
{
public UPnP()
{

}
public static void OpenFirewallPort(int port,string description, bool enable)
{
System.Net.NetworkInformation.NetworkInterface[] nics =
System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

//for each nic in computer...
foreach (System.Net.NetworkInformation.NetworkInterface nic
in nics)
{
try
{
    string machineIP =Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
//send msg to each gateway configured on this nic
foreach
(System.Net.NetworkInformation.GatewayIPAddressInformation gwInfo in
nic.GetIPProperties().GatewayAddresses)
{
try
{
OpenFirewallPort(machineIP,
gwInfo.Address.ToString(), port,description,enable);
Console.WriteLine("ip: "+gwInfo.Address.ToString());
}
catch
{ }
}
}
catch { }
}

}
public static void OpenFirewallPort(string machineIP, string
firewallIP, int openPort,string description,bool enable)
{
string svc = getServicesFromDevice(firewallIP);

openPortFromService(svc,"urn:schemas-upnp-org:service:WANIPConnection:1",machineIP,
firewallIP, 2869, openPort,description,enable);
openPortFromService(svc,
"urn:schemas-upnp-org:service:WANPPPConnection:1", machineIP,
firewallIP, 2869, openPort, description,enable);
}
private static string getServicesFromDevice(string firewallIP)
{
//To send a broadcast and get responses from all, send to
//239.255.255.250
string queryResponse = "";
try
{
string query = "M-SEARCH * HTTP/1.1\r\n" +
"Host:" + firewallIP + ":1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"Man:\"ssdp:discover\"\r\n" +
"MX:3\r\n" +
"\r\n" +
"\r\n";

//use sockets instead of UdpClient so we can set a
//timeout easier
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint endPoint = new
IPEndPoint(IPAddress.Parse(firewallIP), 1900);

//1.5 second timeout because firewall should be on same
//segment (fast)
client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 2500);

byte[] q = Encoding.ASCII.GetBytes(query);
client.SendTo(q, q.Length, SocketFlags.None, endPoint);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint senderEP = (EndPoint)sender;

byte[] data = new byte[1024];
int recv = client.ReceiveFrom(data, ref senderEP);
queryResponse = Encoding.ASCII.GetString(data);
}
catch { }

if(queryResponse.Length == 0)
return "";


/* QueryResult is somthing like this:
*
HTTP/1.1 200 OK
Cache-Control:max-age=60
Location:http://10.10.10.1:80/upnp/service/des_ppp.xml
Server:NT/5.0 UPnP/1.0
ST:upnp:rootdevice
EXT:

USN:uuid:upnp-InternetGatewayDevice-1_0-00095bd945a2::upnp:rootdevice
*/

string location = "";
string[] parts = queryResponse.Split(new string[] {
System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
foreach (string part in parts)
{
if (part.ToLower().StartsWith("location"))
{
location = part.Substring(part.IndexOf(':') + 1);
break;
}
}
if (location.Length == 0)
return "";

//then using the location url, we get more information:

System.Net.WebClient webClient = new WebClient();
try
{
string ret = webClient.DownloadString(location);
Debug.WriteLine(ret);
return ret;//return services
}
catch (System.Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
webClient.Dispose();
}
return "";
}



private static void openPortFromService(string services, string
serviceType, string machineIP, string firewallIP, int gatewayPort, int
portToForward,string description,bool enable)
{
if (services.Length == 0)
return;
int svcIndex = services.IndexOf(serviceType);
if (svcIndex == -1)
return;
string controlUrl = services.Substring(svcIndex);
string tag1 = "<controlURL>";
string tag2 = "</controlURL>";
controlUrl = controlUrl.Substring(controlUrl.IndexOf(tag1)
+ tag1.Length);
controlUrl =
controlUrl.Substring(0,controlUrl.IndexOf(tag2));


string soapBody = "<s:Envelope " +
"xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/ \" " +

"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/ \">" +
"<s:Body>" +
"<u:AddPortMapping xmlns:u=\"" + serviceType + "\">" +
"<NewRemoteHost></NewRemoteHost>" +
"<NewExternalPort>" + portToForward.ToString() +
"</NewExternalPort>" +
"<NewProtocol>TCP</NewProtocol>" +
"<NewInternalPort>" + portToForward.ToString() +
"</NewInternalPort>" +
"<NewInternalClient>" + machineIP +
"</NewInternalClient>" +
"<NewEnabled>1</NewEnabled>" +
"<NewPortMappingDescription>"+description+"</NewPortMappingDescription>" +
"<NewLeaseDuration>0</NewLeaseDuration>" +
"</u:AddPortMapping>" +
"</s:Body>" +
"</s:Envelope>";

if (!enable)
{
    soapBody = "<s:Envelope " +
    "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/ \" " +

    "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/ \">" +
    "<s:Body>" + "<u:DeletePortMapping xmlns:u=\"" + serviceType + "\">" +
                "<NewRemoteHost>" +
                "</NewRemoteHost>" +
                "<NewExternalPort>" + portToForward.ToString() + "</NewExternalPort>" +
                "<NewProtocol>" + ProtocolType.Tcp.ToString().ToUpper() + "</NewProtocol>" +
                "</u:DeletePortMapping>" + "</s:Body>" +
    "</s:Envelope>";
}
byte[] body =
System.Text.UTF8Encoding.ASCII.GetBytes(soapBody);

string url = "http://" + firewallIP + ":" +
gatewayPort.ToString() + controlUrl;
System.Net.WebRequest wr =
System.Net.WebRequest.Create(url);//+ controlUrl);
wr.Method = "POST";
if (enable)
{
    wr.Headers.Add("SOAPAction", "\"" + serviceType +
    "#AddPortMapping\"");
}
else
{
    wr.Headers.Add("SOAPAction", "\"" + serviceType +
    "#DeletePortMapping\"");
}
wr.ContentType = "text/xml;charset=\"utf-8\"";
wr.ContentLength = body.Length;
//wr.Credentials = new NetworkCredential("btservices", "xxxxx", "se");
//wr.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("admin" + ":" + "h")));
System.IO.Stream stream = wr.GetRequestStream();

stream.Write(body, 0, body.Length);
stream.Flush();
stream.Close();
//wr.Credentials = new NetworkCredential("btservices", "xxxxx", "se");
WebResponse wres = wr.GetResponse();
System.IO.StreamReader sr = new
System.IO.StreamReader(wres.GetResponseStream());
string ret = sr.ReadToEnd();
sr.Close();

Debug.WriteLine("Setting port forwarding:" +
portToForward.ToString() + "\r\r" + ret);
}
}
}

Open in new window

0
 
Leo01Author Commented:
Thanks for the quick reply. Will review it and post my experience. Wanted to acknowledge your post immediately.
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
Leo01Author Commented:
Hi There,

I'm finding hard to reconcile the code. Basically, I have a Soap-Service running on http://localhist:8081/services/ABC (java)
ABC being the service name. It's exposing two methods:
GetCount()...returns int ( java)
GetString()...returns string(java)

I want to be able to call these two methods and store the values locally in C# client.

I'll raise the points by another 250, if you can help me reconcile the chnges
0
 
Leo01Author Commented:
Increasing the points to max value
0
 
GeorgeGerguesCommented:

Start Visual studio


- Create a console app.

Under references , right click and create web reference.


on the web  ref. type the url for the service  http://localhist:8081/services/ABC

in your code you can simply use it as any other class

also read more here
http://msdn.microsoft.com/en-us/library/d9w023sx(VS.71).aspx


Best of luck.

0
 
Leo01Author Commented:
Gerge, That doesn't seem right. This is a SOAP service, I think there's more to it.
bartvd's example appears right, but need a way to reconcile that approach with my service.

0
 
Leo01Author Commented:
Thanks for your responses.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.