How to return custom objects with WebServices

Gavin Chin picture Gavin Chin · Sep 24, 2009 · Viewed 8k times · Source

[Problem]
Having created a shared library that is to be deployed on a server machine and client machine how do I communicate between the client-server with the classes provided by the library?

Transferring the information via webservices does not seem to work as the serialised object returned by the web service is a webservice class which does not convert to the shared library.

Am I using the webservices incorrectly? Is there a better way?

[Example]

MyLibrary.cs and SubLibrary.cs is in a shared assembly that is to be used by the client app.

MyLibrary.cs

public class MyLibrary
{
    private SubLibrary sublib = new SubLibrary();

    public class MyLibrary()
    {
    }

    public string GetValue()
    {
        return sublib.GetValue();
    }
}

SubLibrary.cs

public class SubLibrary
{
    private string str = "Hello World";

    public SubLibrary()
    {
    }

    public string GetValue()
    {
        return str;
    }
}

WebService.asmx.cs

[WebMethod]
public MyLibrary GetInfo()
{
    return new MyLibrary();
}

Client App

private void GetInfo_Click(object sender, System.EventArgs e)
{
  WS.WebService services = new WS.WebService();

  MyLibrary info = services.GetInfo();  // This of course doesn't convert.

  MessageBox.Show(info.GetValue());
}

Answer

Marc Gravell picture Marc Gravell · Sep 24, 2009

In short this is a pain in 1.1 (and partly 2.0 too). Assembly-sharing (or type-sharing) only really started being a feature in WCF (.NET 3.0). The proxies generated in 1.1 will never be directly compatible with the "actual" classes; you can share the same proxies between multiple services ("sharetypes" ?), but not with independent source files, IIRC.

And since it is C# 1.2 you have neither partial classes nor extension methods to cheat with to translate them.

Options (that I can see):

  • write a static utility method to laboriously translate between the two object models
  • ditto but using XmlSerializer (less code, but not as quick)
  • live with it
  • upgrade to WCF (quite a significant change)