How to properly define a variable to be used in multiple webmethods?

J

Jeffery Tyree

The webservice code:

public class WebService1:yadayada
{
public string sFN;

[WebMethod]
public void CreateFile (string strFileName)
{
sFN = "C:\\inetpub\\" + strFileName;
}

[WebMethod]
public void WriteFile(string strText)
{
using (StreamWriter sw = File.AppendText(sFN))
{
sw.WriteLine(strText);
}
}
}

Although "sFN" is defined even as public within the class and assigned a
value in CreateFile, the variable goes NULL when it is used in WriteFile.
The client application does not use this variable in its code. How do I
properly define "sFN" so that it can be used in multiple webmethods?

TIA,
-Jeff
 
P

Peter Kelcey

Jeff

The issue isn't caused by your code. Your problem is caused by the fact
that web services are stateless are you are trying to use them as if
they are stateful. With the design that you have, you are making two
separate calls to your web service. The web service will not maintain
the state of you class variable between calls. Each time you call the
web service, the class is instantiated again and all variables are
created new.

You can get hack your way around this by storing the value of
strFileName in a session variable. (which can be maintained between
calls if you want). However I would recommend that you take the time
now to re-think you overall design and use some service design best
practices.

With web services, you need to put assigned the old "CRUD" method
(Create, Read, Update and Delete) and you need to begin to design you
methods based on a service approach. CRUD results in "chatty" code
that doesn't work well within a services based world.

Best practices for services design state that your service should
accept all of the parameters that it needs to complete its own work and
shouldn't rely on information sent to other methods. Under this
design principle, your method would like the following

[WebMethod]
public void WriteFile(string, strFileName, string strText)
{
using (StreamWriter sw = File.AppendText(sFN))
{
sw.WriteLine(strText);
}
}

I'd also recommend the following article that reviews some patterns
to follow when designing your services.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/SOADesign.asp

MSDN has lots of other useful articles about designing web services
that you can check out.

Hope that helps,

Peter Kelcey
 
J

Jeffery Tyree

Peter-

Thank you very much for the detailed explanation. It is greatly appreciated.

-Jeff
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top