laughingblade
10/23/2013 - 1:18 PM

Simple Proxy for an external service. Minimise untested code close to an external service call by factoring the callout into a proxy class.

Simple Proxy for an external service. Minimise untested code close to an external service call by factoring the callout into a proxy class. This pattern is also useful when picking up a web service of WCF service reference

using System.Xml.Linq;

namespace LeeSoft.TestUtils.SimpleProxy
{
    public interface IServiceProxy
    {
        XDocument Load();
    }
}
using log4net;
using System.Net;
using System.Xml.Linq;

namespace LeeSoft.TestUtils.SimpleProxy
{
    public class ConcreteServiceProxy: BaseServiceProxy
    {
        public ConcreteServiceProxy(ILog log) : base(log)
        {
            ProxyName = "ConcreteServiceProxy";
        }

        public override XDocument Load()
        {
            var client = new WebClient { Credentials = new NetworkCredential("abc", "xyz") };

            // Add a user agent header in case the requested URI contains a query.
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            var data = client.OpenRead("http://www.somedomain.com/OutgoingData/clientName/DATA.XML");

            var doc = XDocument.Load(data);

            LogReceipt(doc);

            return doc;
        }
    }
}
using log4net;
using System.Globalization;
using System.Xml.Linq;

namespace LeeSoft.TestUtils.SimpleProxy
{
    public abstract class BaseServiceProxy : IServiceProxy
    {
        protected ILog Log;

        protected string ProxyName = "BaseServiceProxy";

        protected BaseServiceProxy(ILog log)
        {
            Log = log;
        }

        public abstract XDocument Load();

        protected void LogReceipt(XDocument data)
        {
            Log.Info(string.Format(CultureInfo.InvariantCulture, "Loaded data from {0}. Content: {1}", ProxyName, data));
        }
    }
}