McKelt.com

Remembering Thoughts

Recent comments

Authors

Categories


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Topics

ToDo://

 

  1. Command --- Query separation
  2. DDD lingo

ToMake

 

  1. SilverTweet
  2. SilverStock
  3. BedlamMvc
using System;
using System.Collections.Generic;

namespace Matlock.Core.Specification
{
    public interface ISpecification<T>
    {
        bool IsSatisfiedBy(T candidate);
        ISpecification<T> And(ISpecification<T> other);
        ISpecification<T> Or(ISpecification<T> other);
        ISpecification<T> XOr(ISpecification<T> other);
        ISpecification<T> AndAllOf(IEnumerable<ISpecification<T>> specifications);
        T Target { get; set; }
        void GetResults(ResultsVisitor visitor);
        IEnumerable<Type> WhatWasAssessed();
        Risks.IMatlockCommand GetCommand();
    }
}

Posted by chris on Wednesday, February 03, 2010 4:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Castle Windsor – WCF Endpoint Configuration

          const int maxSize = 52428800;

            var binding = new BasicHttpBinding();
            binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
            binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
            binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
            binding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default;
            binding.MaxReceivedMessageSize = 1000000;
            binding.CloseTimeout = new TimeSpan(0, 1, 0);
            binding.OpenTimeout = new TimeSpan(0,1,0);
            binding.ReceiveTimeout = new TimeSpan(0,10,0);
            binding.SendTimeout = new TimeSpan(0,1,0);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            binding.MaxBufferSize = maxSize;
            binding.MaxBufferPoolSize = maxSize;
            binding.MaxReceivedMessageSize = maxSize;
            binding.MessageEncoding = WSMessageEncoding.Mtom;
            binding.TextEncoding = Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            binding.ReaderQuotas.MaxDepth = 32;
            binding.ReaderQuotas.MaxStringContentLength = maxSize;
            binding.ReaderQuotas.MaxArrayLength = maxSize;
            binding.ReaderQuotas.MaxBytesPerRead = maxSize;
            binding.ReaderQuotas.MaxNameTableCharCount = maxSize;

            container = new IocContainer(LifestyleType.Transient);
            container.AddFacility<WcfFacility>().Register(
                Component
                    .For<ISharePointFacadeService>()
                    .Named("DmsGateway")
                    .ActAs(
                        new DefaultClientModel()
                        {
                            Endpoint = WcfEndpoint
                                        .BoundTo(binding)
                                        .At("http://localhost/SharepointFacade/DMSService.svc/mex")
                        }));

Posted by chris on Monday, February 01, 2010 10:08 AM
Permalink | Comments (0) | Post RSSRSS comment feed

ConvertPropertiesAndValuesToHashtable Extension method

public static class Extensions
    {
        public static Hashtable ConvertPropertiesAndValuesToHashtable(this object obj)
        {
            var ht = new Hashtable();

            // get all public static properties of obj type
            var propertyInfos = obj.GetType().GetProperties().Where(a=>a.MemberType.Equals(MemberTypes.Property)).ToArray();
            // sort properties by name
            Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));

            // write property names
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                ht.Add(propertyInfo.Name, propertyInfo.GetValue(obj, BindingFlags.Public, null, null, CultureInfo.CurrentCulture));
            }

            return ht;
        }
    }
 
 
 
Tests
 
 using System;
    using System.Collections;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Presentation;
    using Presentation.Mappers;
    using Presentation.Model;

    using SoftwareApproach.TestingExtensions;

    using TestHelpers;

    [Concern(typeof(DocumentMetaDataToDmsDocumentMetaDataMapper))]
    [TestClass]
    public class WhenUsingExtensions : ContextSpecification<DocumentMetaDataToDmsDocumentMetaDataMapper>
    {
        private DocumentMetadata metadata;

        private Hashtable ht;


        protected override void Context()
        {
            metadata = RandomHelper.FillPropertiesWithRandomValues<DocumentMetadata>(new DocumentMetadata());
            metadata.RiskId = 12;
        }

        protected override void Because()
        {
            ht = metadata.ConvertPropertiesAndValuesToHashtable();
        }

        [TestMethod]
        public void ShouldContainCorrectCountForNumberOfMembers()
        {
            ht.Count.ShouldEqual(metadata.GetType().GetProperties().Where(a=>a.MemberType.Equals(MemberTypes.Property)).Count());
        }

        [TestMethod]
        public void ShouldMapAllPropertiesToHashtableCorrectly()
        {
            metadata.Account.ShouldEqual(ht["Account"].ToString());
            metadata.AssociatedNames.ShouldEqual(ht["AssociatedNames"].ToString());
            metadata.Broker.ShouldEqual(ht["Broker"].ToString());
            metadata.BrokerContact.ShouldEqual(ht["BrokerContact"].ToString());
            metadata.CreatedDate.ShouldEqual(Convert.ToDateTime(ht["CreatedDate"], CultureInfo.CurrentCulture));
            metadata.ExpiryDate.ShouldEqual(Convert.ToDateTime(ht["ExpiryDate"], CultureInfo.CurrentCulture));
            metadata.InceptionDate.ShouldEqual(Convert.ToDateTime(ht["InceptionDate"], CultureInfo.CurrentCulture));
            metadata.PolicyReference.ShouldEqual(ht["PolicyReference"].ToString());
            metadata.QuoteReference.ShouldEqual(ht["QuoteReference"].ToString());
            metadata.RiskId.ShouldEqual(Convert.ToInt32(ht["RiskId"]));
            metadata.Status.ShouldEqual(ht["Status"].ToString());
            metadata.Underwriter.ShouldEqual(ht["Underwriter"].ToString());
            metadata.UniqueMarketReference.ShouldEqual(ht["UniqueMarketReference"].ToString());
            metadata.YearOfAccount.ShouldEqual(Convert.ToInt32(ht["YearOfAccount"]));
            
        }
    }

Posted by chris on Wednesday, January 27, 2010 2:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Google reader subscriptions

Google reader OPML file Google reader OPML file


Posted by chris on Thursday, January 14, 2010 4:46 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Obliterate Database

declare
   @vcFK varchar(250),
   @vcTable varchar(250),
   @vcSP varchar(250),
   @vcView varchar(250),
   @vcFn varchar(250)

-- ...drop all foreign key constraints      
select @vcFK = min(name) from sysobjects where type='F'
while @vcFK is not null
begin
   print 'Dropping FK constraint ' + @vcFK
   
   -- ...get name of table corresponding to the foreign key
   select
      @vcTable = S2.name
   from
      sysobjects S1
      inner join sysconstraints C on S1.id = C.constid
      inner join sysobjects S2 on C.id = S2.id
   where
      S1.name = @vcFK and S1.type='F'
   
   exec ('alter table ' + @vcTable + ' drop constraint ' + @vcFK)
   select @vcFK = min(name) from sysobjects where type='F' and name > @vcFK
end

-- ...drop all tables
select @vcTable = min(name) from sysobjects where type='U' and name not like 'dt%'
while @vcTable is not null
begin
   print 'Dropping table ' + @vcTable
   exec ('drop table ' + @vcTable)
   select @vcTable = min(name) from sysobjects where type='U' and name not like 'dt%' and name > @vcTable
end

-- ...drop all our stored procedures
select @vcSP = min(name) from sysobjects where type='P' and (name like 'usp%')
while @vcSP is not null
begin
   print 'Dropping procedure ' + @vcSP
   exec ('drop procedure ' + @vcSP)
   select @vcSP = min(name) from sysobjects where type='P' and (name like 'usp%') and name > @vcSP
end

-- ...drop all views
select @vcView = min(name) from sysobjects where type='V' and name like 'v%'
while @vcView is not null
begin
   print 'Dropping view ' + @vcView
   exec ('drop view ' + @vcView)
   select @vcView = min(name) from sysobjects where type='V' and name like 'v%' and name > @vcView
end
   
-- ...drop all functions
select @vcFn = min(name) from sysobjects where type='FN' and name like 'udf%'
while @vcFn is not null
begin
   print 'Dropping function ' + @vcFn
   exec ('drop function ' + @vcFn)
   select @vcFn = min(name) from sysobjects where type='FN' and name like 'udf%' and name > @vcFn
end

Posted by chris on Thursday, December 10, 2009 5:43 PM
Permalink | Comments (0) | Post RSSRSS comment feed

WCF Tracing

In the web.config in between the <configuration></configuration> tags

 

<system.diagnostics>
            <sources>
                  <source name="System.ServiceModel"
                              switchValue="Information, ActivityTracing"
                              propagateActivity="true">
                        <listeners>
                              <add name="traceListener"
                                    type="System.Diagnostics.XmlWriterTraceListener"
                                    initializeData= "WCFTrace.svclog" />
                        </listeners>
                  </source>
            </sources>
            <trace autoflush="true" />
      </system.diagnostics>

Posted by chris on Friday, November 13, 2009 12:03 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Enum extension methods

public static class EnumExtensionMethods
    {

        public static T ParseAsEnumByDescriptionAttribute<T>(this string description)  // where T : enum
        {    
            if (string.IsNullOrEmpty(description))   
            {        
                throw new ArgumentNullException (description,@"Cannot parse an empty description");    
            }    

            Type enumType = typeof(T); 
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException (string.Format("Invalid Enum type{0}",typeof(T)));
            }   

            foreach (T item in Enum.GetValues(typeof(T)))
            {
                DescriptionAttribute[] attributes = (DescriptionAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0 && attributes[0].Description.ToUpper() == description.ToUpper())
                {
                    return item;
                }
            }
            throw new InvalidOperationException(string.Format("Couldn't find enum of type {0} with attribute of '{1}'", typeof(T),description));
        }
        
        public static string GetDescription(this Enum enumerationValue)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[]) enumerationValue.GetType().GetField(enumerationValue.ToString()).GetCustomAttributes(typeof (DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : enumerationValue.ToString();
        }

        public static EnumDto GetDto(this Enum enumerationValue)
        {
            return new EnumDto {Value = enumerationValue, Description = GetDescription(enumerationValue)};
        }

        public static T ToEnum<T>(this string enumerationString)
        {
            return (T) Enum.Parse(typeof (T), enumerationString);
        }

Posted by chris on Friday, October 23, 2009 6:33 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Log4Net config

    <log4net>
        <appender name="WindowsEventAppender" type="log4net.Appender.EventLogAppender">
            <param name="LogName" value="Application" />
            <applicationName value="Rating" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date [%thread] %-5level %logger%newline =&gt; %message%newline" />
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="ERROR" />
            </filter>
        </appender>
        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
            <file value="RatingDocumentExtract.log" />
            <appendToFile value="true" />
            <maximumFileSize value="300KB" />
            <maxSizeRollBackups value="2" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%level %thread %logger - %message%newline" />
            </layout>
        </appender>

        <root>
            <level value="DEBUG" />
            <appender-ref ref="WindowsEventAppender" />
            <appender-ref ref="RollingFile" />
        </root>
    </log4net>

Posted by chris on Thursday, October 15, 2009 5:33 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Context Specification

namespace Example
{
    using System;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Rhino.Mocks;

    public abstract class ContextSpecification<T>
    {
        protected Exception executionException;

        protected T sut { get; set; }

        [TestInitialize]
        public void Start()
        {
            this.Context();
            this.SetupMockResults();
            this.Because();
        }

        [TestCleanup]
        public void CleanUp()
        {
            this.Clean();
        }

        protected virtual void Context()
        {
        }

        protected virtual void SetupMockResults()
        {
        }

        protected virtual void Because()
        {
        }

        protected virtual void Clean()
        {
        }

        protected TInterface GetDependency<TInterface>() where TInterface : class
        {
            return MockRepository.GenerateMock<TInterface>();
        }

        public void Execute(Action action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                executionException = ex;
            }
        }

    }
}

Posted by chris on Monday, October 12, 2009 1:48 PM
Permalink | Comments (0) | Post RSSRSS comment feed

SQL Server error handling

CREATE PROCEDURE <procName>
/*^
* Procedure:     usp_TryCatchSkeleton
^*/
AS

BEGIN

   SET NOCOUNT ON

   BEGIN TRY

      --Do work

   END TRY

   BEGIN CATCH
/* Note that catching and rethrowing an exception is a lossy operation. ERROR_PROCEDURE() etc will be reset. */
      DECLARE @errorMessage   NVARCHAR(4000);
      DECLARE @errorSeverity  INT;
      DECLARE @errorState     INT;

      SELECT  @errorMessage   = ERROR_MESSAGE(),
              @errorSeverity  = ERROR_SEVERITY() ,
              @errorState     = ERROR_STATE();

      --Perform required recovery actions.

      RAISERROR ( @errorMessage, @errorSeverity, @errorState );
      
      RETURN 1;

   END CATCH
   
   RETURN 0;
END

Posted by chris on Friday, September 11, 2009 12:57 PM
Permalink | Comments (0) | Post RSSRSS comment feed