Click here to Skip to main content
11,412,345 members (67,850 online)
Click here to Skip to main content
Add your own
alternative version

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

, 15 Jun 2009 CPOL
WCF Service Behavior Example: IPFilter - Allow/Deny Access by IP Address
IPFilterExample.zip
IPFilterTests
bin
Debug
IPFilter.dll
IPFilterTests.dll
Configuration
Mock
Properties
TestWebsite
App_Data
bin
IPFilter.dll
IPFilter.pdb
TestWebsite.dll
TestWebsite.pdb
Filtered
Properties
TestWebsite.csproj.user
IPFilterExample.suo
IPFilterExample.vsmdi
IPFilterExample1.vsmdi
IPFilterExample2.vsmdi
LocalTestRun.testrunconfig
IPFilter
bin
Debug
IPFilter.dll
Configuration
Properties
IPFilterExamples.zip
IPFilterExample3.vsmdi
LocalTestRun.testrunconfig
IPFilter.dll
IPFilter.csproj.user
IPFilter.dll
IPFilterTests.dll
IPFilter.dll
IPFilter.pdb
TestWebsite.dll
TestWebsite.pdb
TestWebsite.csproj.user
IPFilterExample.vsmdi
IPFilterExample1.vsmdi
IPFilterExample2.vsmdi
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)

Share

About the Author

Ziad Elmalki

United States United States
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.5 | Last Updated 16 Jun 2009
Article Copyright 2009 by Ziad Elmalki
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid