MoonKnight
MoonKnight

Reputation: 23833

Pulling Information from 'Server' via WCF

I have two WinForms applications: a 'server' and a 'client'. On the server

private ServiceHost host;
private const string serviceEnd = "Done";

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    List<string> sqlList = new List<string>();
    foreach (string line in this.richTextBoxSql.Lines)
        sqlList.Add(line);
    SqlInfo sqlInfo = new SqlInfo(sqlList);

    host = new ServiceHost(
        typeof(SqlInfo),
        new Uri[] { new Uri("net.pipe://localhost") });

    host.AddServiceEndpoint(typeof(ISqlListing),
            new NetNamedPipeBinding(),
            serviceEnd);

    host.Open();
}

Where

public class SqlInfo : ISqlListing
{
    public SqlInfo() {}

    private List<string> sqlList;
    public SqlInfo(List<string> sqlList) : this() 
    {
        this.sqlList = sqlList;
    }

    public List<string> PullSql()
    {
        return sqlList;
    }
}

[ServiceContract]
public interface ISqlListing
{
    [OperationContract]
    List<string> PullSql();
}

On the client I have

private ISqlListing pipeProxy { get; set; }
private const string serviceEnd = "Done";

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    List<string> l = pipeProxy.PullSql();
    string s = String.Empty;
    foreach (string str in l)
        s += str + " ";
    this.richTextBoxSql.AppendText(s.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
    ChannelFactory<ISqlListing> pipeFactory =
    new ChannelFactory<ISqlListing>(
      new NetNamedPipeBinding(),
      new EndpointAddress(
         String.Format("net.pipe://localhost/{0}", serviceEnd)));

    pipeProxy = pipeFactory.CreateChannel();
}

The problem is, that when I 'pull' the List<string> from the server using pipeProxy.PullSql() it is calling the public SqlInfo() {} default constructor and setting the sqlList = null.

How do I get this code to return the text in the RichTextBox on the server app?

Upvotes: 0

Views: 114

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33242

This is because you are using this kind of service host:

 host = new ServiceHost(
        typeof(SqlInfo),
        new Uri[] { new Uri("net.pipe://localhost") });

you are passing a type and the WCF framework guess it have to create an instance of type SqlInfo to handle the request. Try to pass a reference to your constructed SqlInfo instance, ie sqlInfo in your case. Use this overload of ServiceHost, it allow tyou to pass the instance directly:

host = new ServiceHost(
            sqlInfo,
            new Uri[] { new Uri("net.pipe://localhost") });

Upvotes: 2

Related Questions