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

Allow IIS7 to download .config files

1. In the following file

C:\Windows\System32\inetsrv\config\applicationHost.config

Ensure the following

<section name="requestFiltering" overrideModeDefault="Allow" />

2

This is the web.config file

 

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
         <handlers>
           <clear />
            <add 
                name="StaticFile" 
                path="*" verb="*" 
                modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" 
                resourceType="Either" 
                requireAccess="Read" />
        </handlers>
        <staticContent>
            <mimeMap fileExtension=".*" mimeType="application/octet-stream" />
        </staticContent>
        <security>
            <requestFiltering>
                <fileExtensions allowUnlisted="true">
                    <remove fileExtension=".config" />
                    <add fileExtension=".config" allowed="true" />
                </fileExtensions>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

Posted by chris on Thursday, March 11, 2010 5:58 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Visual Studio Icons

For free icons that come with Visual Studio check out

 

C:\Program Files\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033\

 

VS2008ImageLibrary.zip


Posted by chris on Monday, February 22, 2010 6:45 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Stream bytes to files

                using (var stream =
                    Assembly.GetAssembly(typeof(StubPolicy)).GetManifestResourceStream(
                        "Documents.TestHelpers.Files.test.msg"))
                {
                    const int bufferLength = 256;
                    var buffer = new Byte[bufferLength];
                    if (stream != null)
                    {
                        int bytesRead = stream.Read(buffer, 0, bufferLength);

                        using (var fs = new FileStream(filename, FileMode.CreateNew, FileAccess.Write))
                        {
                            // Write out the input stream
                            while (bytesRead > 0)
                            {
                                fs.Write(buffer, 0, bytesRead);
                                bytesRead = stream.Read(buffer, 0, bufferLength);
                            }
                            fs.Close();
                        }
                        stream.Close();
                    }
                }

Posted by chris on Wednesday, February 10, 2010 3:48 PM
Permalink | Comments (0) | Post RSSRSS comment feed

ISpecification

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