Saturday, July 13, 2013

Storing and Retreiving Data from a Web Server using WCF Web Service


In one of my Silverlight projects, there was a need to store some data on the server and get it back as needed. I wrote a simple WCF Web Service to do this. This service will take in a string and write it on the server on a file called "AppSettings.xml".

The web service function "GetStoredDataFromServer()" will get the stored data in string format from the server.

The web service function "SaveDataOnServer(string datatoSave)" will store the data on the server.

When deploying this service on the IIS server, make sure to provide write permission for the IIS_IUSRS account to the file "AppSettings.xml". This is required because the anonymous user must be able to save the information on the file "AppSettings.xml".


 Here is the code.

 This code needs to go on the IService.cs.

    [ServiceContract]

    public interface IStoreService

    {

        [OperationContract]

        string GetStoredDataFromServer();

 

        [OperationContract]

        string SaveDataOnServer(string datatoSave);

    }


This code needs to go on the Service.svc.cs file.

   public class StoreDataService : IStoreService

    {

        public string GetStoredDataFromServer()

        {

            string togoMessage = "";

            string fileName = AppDomain.CurrentDomain.BaseDirectory + "AppSettings.xml" ;

            if (File.Exists(fileName) == false)

            {

                try

                {

                    StreamWriter sw = new StreamWriter(fileName);

                    sw.WriteLine("");

                    sw.Close();

                }

                catch (Exception ex)

                {

                    togoMessage = "Error : " + ex.ToString();

                    return togoMessage;

                }

            }

            else

            {

                StreamReader sr = new StreamReader(fileName);

                togoMessage = sr.ReadToEnd();

                sr.Close();

            }

            return togoMessage;

        }

 

        public string SaveDataOnServer(string datatoSave)

        {

            string togoMessage = "";

            string fileName = AppDomain.CurrentDomain.BaseDirectory + "AppSettings.xml";

            try

            {

                StreamWriter sw = new StreamWriter(fileName);

                sw.WriteLine(datatoSave);

                sw.Close();

            }

            catch (Exception ex)

            {

                togoMessage = "Error : " + ex.ToString();

                return togoMessage;

            }

            return togoMessage;

        }

    }

 Happy Coding !

All Blogs so far ...