Archive

Posts Tagged ‘Gotcha’

NHibernate Samples

October 13, 2010 Leave a comment

Here is a link to a console project I have been adding to showing the various mapping and usages of NHibernate to help people look at all the available options.

Download the samples here

Blair

Advertisements

WCF Instance De-Activation

September 29, 2010 Leave a comment

So we are going to take a look at WCF Instance de-activation.

When you have the InstanceContextMode to Per Call the service instance is deactivated at the end of the call.
When you have the InstanceContextMode to Per Session the service instance is deactivated at the end of the session or after timeout.
When you have the InstanceContextMode to Single the service instance is deactivated at the shutdown of the application.

You need to apply the ReleaseInstanceMode as shown below. The options are pretty self explanatory as to when to release the service instance.

You can also do it in code using OperationContext.Current.InstanceContext.ReleaseServiceInstance() as shown in the code.

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFInstanceActivation.Server
{
    [ServiceContract(Namespace = "http://localhost/Samples", SessionMode = SessionMode.Required)]
    interface IPrintService
    {
        [OperationContract]
        void Print(string message);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    class PrintService : IPrintService
    {

        [OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.BeforeCall)]
        public void Print(string message)
        {
            Console.WriteLine(message);
            OperationContext.Current.InstanceContext.ReleaseServiceInstance();

            Console.WriteLine("Continuing with session id: " + OperationContext.Current.SessionId);
        }
    }

    class Program
    {
        static void Main()
        {
            using (ServiceHost host = new ServiceHost(typeof(PrintService), new Uri("http://localhost/PrintService")))
            {

                host.AddServiceEndpoint(typeof(IPrintService), new WSHttpBinding(), "");
                host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
                //host.Description.Behaviors.Add(new ServiceDebugBehavior{ IncludeExceptionDetailInFaults = false});

                host.Open();

                Console.WriteLine("Press any key to quit..");
                Console.ReadKey();
            }
        }
    }
}

Hope this helps..

Blair..

Categories: Development Tags: , , , , , ,

WCF DataContracts Exposing Subclasses via WSDL

September 27, 2010 Leave a comment

To expose your subclasses via WSDL through metadata they next to be marked as a DataContract and added to the parent classes KnownType attribute.

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace WCFDataContracts.Server
{

    [DataContract]
    [KnownType(typeof(GoldCustomer))]
    public class Customer
    {

        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class GoldCustomer : Customer
    {
    }

    [ServiceContract]
    public interface IPrintService
    {

        [OperationContract]
        void Print(Customer c);
    }

    public class PrintService : IPrintService
    {
        public void Print(Customer c)
        {
            Console.Write(c.Name);
        }
    }

    [ServiceContract]
    public interface ICustomerService
    {

        [OperationContract]
        void Print(Customer c);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    class CustomerService : ICustomerService
    {
        public void Print(Customer c)
        {
            Console.WriteLine(c.Name);
        }
    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine("Starting Service Host");

            using(ServiceHost host = new ServiceHost(typeof(PrintService),new Uri("http://localhost/PrintService")))
            {
                ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
                behavior.HttpGetEnabled = true;
                host.Description.Behaviors.Add(behavior);

                host.AddServiceEndpoint(typeof(IPrintService), new WSHttpBinding(), "");

                host.Open();

                Console.WriteLine("Press any key to exit..");
                Console.ReadKey();

            }

        }
    }
}

Hope this helps.
Blair…

Enumerable extensions to remove duplicates with a function return the key value

September 22, 2010 Leave a comment

Wow.. Long title…

If you have an enumerable and you want to remove duplicates out of the list with a function that returns the key of the type use the extension method I have developed below. Really handy 🙂

public static class EnumerableExtensions
    {
        public static IEnumerable<ElementType> EnsureDuplicateAreRemoved<ElementType,TKeyType>
            (this IEnumerable<ElementType> enumerable, Func<ElementType, TKeyType> keyProducer)
        {
            Dictionary<TKeyType, TKeyType> cache = new Dictionary<TKeyType, TKeyType>();

            foreach (var element in enumerable)
            {
                var value = keyProducer(element);
                if(cache.ContainsKey(value))
                    continue;
                cache.Add(value,value);
                yield return element;
            }

        }
    }

Blair…

The Case Against Count Method in LINQ

September 22, 2010 Leave a comment

The Count method in LINQ is really slow as it iterates of all the items and adds a tally unless the IEnumerator is really an ICollection.

If you need to know whether there is at least 1 item use Any method as it traverses through and if there is an item it exists returning true.

So if you have a huge list the performance difference will be large.

public static int Count(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    ICollection<T> is2 = source as ICollection<T>;
    if (is2 != null)
    {
        return is2.Count;
    }
    int num = 0;
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num++;
        }
    }
    return num;
}

public static bool Any(this IEnumerable<T> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    using (IEnumerator<T> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            return true;
        }
    }
    return false;
}

The source code from LINQ pretty much spells it out. 🙂

Blair…

Double Checking Singleton Design Pattern

September 17, 2010 Leave a comment

Hi all,
I have some source code on how to create a singleton that is thread safe in C#.

Singleton Definition
Ensure a class has only one instance and provide a global point of access to it.

UML
UML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LazyEvaluation
{

    public class ConfigurationA
    {
        private string servername;

        public string Servername
        {
            get { return servername; }
            set { servername = value; }
        }

        private string serverport;

        public string Serverport
        {
            get { return serverport; }
            set { serverport = value; }
        }

        private string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        private string password;

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        private static ConfigurationA configuration;
        private static object locker = new object();

        private ConfigurationA(){}

        public static ConfigurationA Instance
        {
            get
            {
                if (configuration != null)
                {
                    return configuration;
                }

                lock (locker)
                {
                    if (configuration == null)
                    {
                        configuration = new ConfigurationA();
                    }
                    return configuration;
                }
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {

            ConfigurationA c1 = ConfigurationA.Instance;
            ConfigurationA c2 = ConfigurationA.Instance;

            Console.WriteLine("Same instance: {0}", ReferenceEquals(c1, c2));

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();
        }
    }
}

Blair…

Cloning Entities in .NET

July 13, 2010 Leave a comment
using System;

namespace CloningExamples
{

    public class Point
    {
        private readonly int _x;
        private readonly int _y;

        public Point(int x, int y)
        {
            this._x = x;
            this._y = y;
        }

        public int X
        {
            get { return _x; }
        }

        public int Y
        {
            get { return _y; }
        }
    }

    public class Point2 : ICloneable
    {
        private readonly int _x;
        private readonly int _y;

        public Point2(int x, int y)
        {
            this._x = x;
            this._y = y;
        }

        public int X
        {
            get { return _x; }
        }

        public int Y
        {
            get { return _y; }
        }

        public object Clone()
        {
            return new Point2(X, Y);
        }
    }

    public static class CloneableExtensions
    {
        public static T CloneObject(this T entity) where T : ICloneable
        {
            return (T) entity.Clone();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point p1 = new Point(1,2);
           // There is no clone method by default -- Point p2 = p1.Clone();
            Point2 p2 = new Point2(10,20);
            Point2 p3 = (Point2) p2.Clone();
            Point2 p4 = p2.CloneObject();

            Console.WriteLine(p4.X + " " + p4.Y);
            Console.ReadKey();
        }
    }
}

Blair

Categories: Development Tags: , , , ,