Joseph Michael Pesch
VP Programming

WCF Web Service XML Sample

by 24. September 2012 11:29
This is some sample code demonstrating a WCF web service with XML based class as an input parameter.
// Shared class...

public class MySampleData
  public string UserId { get; set; }
  public Guid RecordId { get; set; }
  public string RecordDesc { get; set; }
  public decimal DataAmount { get; set; }
  public DateTime EffectiveDate { get; set; }

// Sample usage...

using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Serialization;

private void SampleUsage()
  MySampleData data = new MySampleData()
    UserId = "myuser",
    RecordId = Guid.NewGuid(),
    RecordDesc = "This is a test",
    DataAmount = 100.99,
    EffectiveDate = System.DateTime.Now.AddDays(5)
  string msg = SaveMySampleData(data);

// Caller initiating web service transaction...
private void SaveMySampleData(MySampleData data)
  XmlSerializer serializer = new XmlSerializer(data.GetType());
  MemoryStream ms = new MemoryStream();
  serializer.Serialize(ms, data);
  StreamReader rdr = new StreamReader(ms);
  ms.Position = 0;
  HttpWebRequest req = (HttpWebRequest)HttpWebRequest
  req.Method = "POST";
  req.ContentType = "application/xml; charset=utf-8";
  byte[] reqBodyBytes = ms.ToArray();
  Stream reqStream = req.GetRequestStream();
  reqStream.Write(reqBodyBytes, 0, reqBodyBytes.Length);
  HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  XmlDocument xml = new XmlDocument();
  xml.LoadXml(new StreamReader(resp.GetResponseStream()).ReadToEnd());

// Web service code (i.e. MySampleService.svc file)

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

public class MySampleService
  [OperationContract(Name = "SaveMySampleData")]
  [WebInvoke(Method = "POST", UriTemplate = "SaveMySampleData",
              RequestFormat = WebMessageFormat.Xml,
              ResponseFormat = WebMessageFormat.Xml,
              BodyStyle = WebMessageBodyStyle.Bare)]
  public string SaveMySampleData(XmlElement input)
    XmlSerializer serializer = new XmlSerializer(typeof(MySampleData));
    MySampleData data = (MySampleData)serializer.Deserialize
      (new MemoryStream(System.Text.Encoding.ASCII.GetBytes(input.OuterXml)));
    // Save to db here... just echoing data back for the sample...
    StringBuilder msg = new StringBuilder();
    msg.Append("You sent the following data.").Append(Environment.NewLine);
    msg.Append("UserId: ").Append(data.UserId).Append(Environment.NewLine);
    msg.Append("RecordId: ").Append(data.RecordId).Append(Environment.NewLine);
    msg.Append("RecordDesc: ").Append(data.RecordDesc).Append(Environment.NewLine);
    msg.Append("DataAmount: ").Append(data.DataAmount).Append(Environment.NewLine);
    msg.Append("EffectiveDate: ").Append(data.EffectiveDate.ToString()).Append(Environment.NewLine);
    return msg.ToString();


C# | Web Service | Windows Communication Foundation

ASP.Net .ASMX WebService Invocation Test Page Remote Access

by 18. October 2011 07:32

The ASP.Net .ASMX webservice page comes with an automatic invocation test page for each of the available operations defined in the service.  By default the invocation is limited to the service running on a local machine (e.g. if you are running the service on your local machine and browse to it you can invoke it;).  However, if the service is running on a server and you browse from your local machine you will probably see this message "The test form is only available for requests from the local machine" in the spot where the invocation button would normally be.  To enable remote invocation, make sure to add the web config section shown below.

        <add name="HttpGet"/>
        <add name="HttpPost"/>


ASP.Net | Web Service

Simple Web Serivce Call (without Registering Service) Using HttpWebRequest Method

by 22. December 2010 08:13


<%@ WebService Language="C#" Class="SimpleWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
public class SimpleWebService  : System.Web.Services.WebService {
  public string WsTestMethod(long TestId, string TestData)
    return string.Join(" ""You sent TestId:", TestId.ToString(), "; TestData:", TestData);




<%@ Page Language="C#" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Text" %>
<script runat="server">
  protected string RootUrl
      string query = (Request.QueryString == null) ? "" : "?" + Request.QueryString.ToString();
      return Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, string.Empty).Replace(query, string.Empty);
  protected void SubmitButton_Click(object sender, EventArgs e)
    string soap =
    @"<?xml version=""1.0"" encoding=""utf-8""?>
      <soap:Envelope xmlns:xsi="""" 
        <WsTestMethod xmlns="""">
          <TestId>" + this.TestId.Text + @"</TestId>
          <TestData>" + this.TestData.Text + @"</TestData>

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
      string.Join("", RootUrl, ResolveUrl("~/SimpleWebService.asmx")));
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";

    Stream str = req.GetRequestStream();
    using (StreamWriter wri = new StreamWriter(str)) wri.Write(soap);

    WebResponse res = req.GetResponse();
    str = res.GetResponseStream();
    this.WsResults.Text = StreamToString(str);


  private string StreamToString(Stream str)
    using (BinaryReader rdr = new BinaryReader(str))
      using (MemoryStream mem = new MemoryStream())
        byte[] buf = new byte[256];
        int bt;
        int bts = 0;
        while ((bt = rdr.Read(buf, 0, 256)) > 0)
          mem.Write(buf, 0, bt);
          bts += bt;
        mem.Position = 0;
        byte[] bytes = new byte[bts];
        mem.Read(bytes, 0, bytes.Length);
        return Encoding.ASCII.GetString(bytes);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
  <form id="form1" runat="server">
    <asp:TextBox ID="TestId" Text="12345" runat="server"></asp:TextBox>
    <asp:TextBox ID="TestData" Text="Simple Web Service" runat="server"></asp:TextBox>
    <asp:Button ID="SubmitButton" OnClick="SubmitButton_Click" Text="Run Web Service"
      runat="server" />
    <asp:Literal ID="WsResults" runat="server"></asp:Literal>



ASP.Net | C# | Web Service