Click here to Skip to main content
15,891,136 members
Articles / Programming Languages / C#

WCF Service Behavior Example: IPFilter - Allow/Deny Access by IP Address

Rate me:
Please Sign up or sign in to vote.
4.92/5 (17 votes)
15 Jun 2009CPOL7 min read 112.3K   2.3K   63  
WCF Service Behavior Example: IPFilter - Allow/Deny Access by IP Address
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Net;
using System.ServiceModel.Channels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.NetworkInformation;
using IPFiltering;

namespace IPFilterTests
{
    [TestClass]
    public class IPFilterServiceBehaviorTestHttpDeny  : IPFilterServiceBehaviorTests
    {
        public IPFilterServiceBehaviorTestHttpDeny()
            : base(BindingType.Http, "DenyLoopback", IPFilterType.Deny)
            {
            }
    }
    [TestClass]
    public class IPFilterServiceBehaviorTestHttpAllow : IPFilterServiceBehaviorTests
    {
        public IPFilterServiceBehaviorTestHttpAllow()
            : base(BindingType.Http, "LoopbackOnly", IPFilterType.Allow)
        {
        }
    }
    [TestClass]
    public class IPFilterServiceBehaviorTestTcpDeny : IPFilterServiceBehaviorTests
    {
        public IPFilterServiceBehaviorTestTcpDeny()
            : base(BindingType.Tcp, "DenyLoopback", IPFilterType.Deny)
        {
        }
    }
    [TestClass]
    public class IPFilterServiceBehaviorTestTcpAllow : IPFilterServiceBehaviorTests
    {
        public IPFilterServiceBehaviorTestTcpAllow()
            : base(BindingType.Tcp, "LoopbackOnly", IPFilterType.Allow)
        {
        }
    }

    [TestClass]
    public abstract class IPFilterServiceBehaviorTests
    {
        private BindingType _bindingType;
        private string _filterName;
        private ServiceHost _host;
        private IPFilterType _exceptedResult;
        private EndpointAddress _address;


        public IPFilterServiceBehaviorTests(BindingType bindingType, string filterName,IPFilterType exceptedResult)
        {
            _bindingType = bindingType;
            _exceptedResult= exceptedResult;
            _filterName = filterName;
        }

        [TestInitialize]
        public void Init()
        {
            Binding binding = GetBinding(_bindingType);
            _address = CreateRandomEndpoint(_bindingType);

            ServiceHost _host = new ServiceHost(typeof(TestService), _address.Uri);
            _host.AddServiceEndpoint(typeof(ITestService), binding, _address.Uri);
            _host.Description.Behaviors.Add(new IPFilterServiceBehavior(_filterName));
            _host.Open();

        }

        [TestCleanup()]
        public void Cleanup()
        {            
            _host = null;    
        }

        [TestMethod()]
        public void TestFilter()
        {
            TestServiceClient client = new TestServiceClient(GetBinding(_bindingType),_address);
            client.Open();
            if ( _exceptedResult == IPFilterType.Deny )
            {
                TestUtil.TestException(()=> Assert.IsNotNull(client.Test()),typeof(Exception));
            }
            else
            {
                Assert.IsNotNull(client.Test());
            }
        }

        private static EndpointAddress CreateRandomEndpoint(BindingType bindingType)
        {
            switch (bindingType)
            {
                case BindingType.Tcp:
                    return new EndpointAddress(string.Format(string.Format("net.tcp://localhost:{0}/", GetPortNumber())));
                case BindingType.NamedPipes:
                    return new EndpointAddress("net.pipe://localhost/ServiceTest/Test/" + RandomUtil.CreateRandomString(20, "abcdefghijklmnopqrstuvwxyz".ToCharArray()));
                case BindingType.Http:
                    return new EndpointAddress(string.Format("http://localhost:{0}/", GetPortNumber()));
                default:
                    throw new NotSupportedException();

            }
        }

        private static Binding GetBinding(BindingType bindingType)
        {
            Binding binding = null;
            TimeSpan timeout = TimeSpan.FromSeconds(30);
            int maxMessageSize = int.MaxValue;

            System.Xml.XmlDictionaryReaderQuotas readerQutas = new System.Xml.XmlDictionaryReaderQuotas();
            readerQutas.MaxDepth = 32;
            readerQutas.MaxStringContentLength = 8192;
            readerQutas.MaxArrayLength = 16384;
            readerQutas.MaxBytesPerRead = 4096;
            readerQutas.MaxNameTableCharCount = 16384;

            if (bindingType == BindingType.Tcp)
            {
                NetTcpBinding tcpBinding = new NetTcpBinding();
                tcpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                tcpBinding.MaxBufferSize = maxMessageSize;
                tcpBinding.MaxBufferPoolSize = 524288;
                tcpBinding.MaxReceivedMessageSize = maxMessageSize;
                tcpBinding.TransferMode = TransferMode.Buffered;
                tcpBinding.ReaderQuotas = readerQutas;

                binding = tcpBinding;
            }
            else if (bindingType == BindingType.NamedPipes)
            {
                NetNamedPipeBinding namedPipeBinding = new NetNamedPipeBinding();
                namedPipeBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                namedPipeBinding.MaxBufferSize = maxMessageSize;
                namedPipeBinding.MaxBufferPoolSize = 524288;
                namedPipeBinding.MaxReceivedMessageSize = maxMessageSize;
                namedPipeBinding.TransferMode = TransferMode.Buffered;
                namedPipeBinding.ReaderQuotas = readerQutas;

                binding = namedPipeBinding;
            }
            else
            {
                BasicHttpBinding httpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
                httpBinding.AllowCookies = false;
                httpBinding.BypassProxyOnLocal = false;
                httpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                httpBinding.MaxBufferSize = maxMessageSize;
                httpBinding.MaxBufferPoolSize = 524288;
                httpBinding.MaxReceivedMessageSize = maxMessageSize;
                httpBinding.MessageEncoding = WSMessageEncoding.Text;
                httpBinding.TextEncoding = Encoding.UTF8;
                httpBinding.TransferMode = TransferMode.Buffered;
                httpBinding.UseDefaultWebProxy = true;

                httpBinding.ReaderQuotas = readerQutas;
                binding = httpBinding;
            }


            binding.SendTimeout = timeout;
            binding.ReceiveTimeout = timeout;
            binding.OpenTimeout = timeout;
            binding.CloseTimeout = timeout;
            return binding;
        }

        private static int GetPortNumber()
        {
            Random random = new Random(Environment.TickCount);

            int i = random.Next(1024, ushort.MaxValue);// Fix this later so won't be endless loop
            IPEndPoint[] endPoints = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
            while (endPoints.FirstOrDefault(f => f.Port == i) != null)
            {
                i = random.Next(1024, ushort.MaxValue);
                endPoints = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
            }
            return i;
        }
    }

    public enum BindingType
    {
        Http,
        Tcp,
        NamedPipes
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions