Wednesday, 27 February 2013

Roles in SQL Server

Just for my reference

http://www.techrepublic.com/article/understanding-roles-in-sql-server-security/1061781
http://msdn.microsoft.com/en-in/library/ms189121.aspx
http://msdn.microsoft.com/en-us/library/ms188659.aspx

An example on how to create Login/User in SQL Server and adding roles using t-sql below

IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'myuser')
BEGIN
    DROP USER myuser

    DROP LOGIN myuser
END;
GO

CREATE LOGIN myuser WITH PASSWORD = '1234!@#$$#@!'
GO

Use [Database];
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'myuser')
BEGIN
    CREATE USER [myuser] FOR LOGIN [myuser]
    EXEC sp_addsrvrolemember @loginame = N'myuser', @rolename = N'sysadmin'

    EXEC sp_addrolemember N'db_owner', N'myuser'
    EXEC sp_addrolemember 'db_ddladmin', N'
myuser' -- this contains create table permission
    EXEC sp_addsrvrolemember @loginame = N'
myuser', @rolename = N'dbcreator'
END;
GO



In-case of domain account, we need to have below

CREATE LOGIN [domain\user] FROM WINDOWS
GO


To find out assigned permissions for an user, below t-sql can be used. It will display permissions for the logged-in user

"SELECT permission_name FROM fn_my_permissions(NULL, 'SERVER')";
"SELECT permission_name FROM fn_my_permissions(NULL, 'DATABASE')";

Tuesday, 26 February 2013

WCF serviceAuthorizationManager

ServiceAuthorizationManager can be used as custom authentication mechanism for WCF operations. So we can configure this in behavior tag

<behavior name="Behavior">
      <serviceAuthorization serviceAuthorizationManagerType="ClassThatImplementsServiceAuthorizationManager, Assembly" />
</behavior>

This is can code thru code like below

host = new WebServiceHost(typeof(Rest), address.Uri);
host.Authorization.ServiceAuthorizationManager=ClassThatImplementsServiceAuthorizationManager;

WCF Restful service with BASIC Authentication

Just wanted to show code for configuring BASIC authentication on REST service.

Hosting part
---------------
               WebHttpBinding binding = new WebHttpBinding();
                binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                binding.Security.Transport.Realm = "domain"; //Enter domain name

                host = new WebServiceHost(typeof(Service), address.Uri);
                host.AddServiceEndpoint(typeof(IService), binding, address.Uri);
                host.Open();

Client
--------
           WebHttpBinding binding = new WebHttpBinding();

            binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
           
            using (WebChannelFactory factory = new WebChannelFactory(binding, address.Uri))
            {
                factory.Credentials.UserName.UserName = "user";
                factory.Credentials.UserName.Password = "password";

                var channel = factory.CreateChannel();

                channel.CallSomething();
            }

DateTime & TimeZoneInfo

static void Main(string[] args)
        {
            //http://stackoverflow.com/questions/1987824/c-sharp-synchronizing-different-time-zones
            //http://stackoverflow.com/questions/179940/c-sharp-convert-utc-gmt-time-to-local-time
            //http://stackoverflow.com/questions/576740/get-timezone-from-datetime
 
            // local time(in my case it is GMT + 5:30)
            var localTime = DateTime.Now;
            var localTime1 = TimeZoneInfo.ConvertTime(localTime, TimeZoneInfo.Local);
            
            //GMT(in my case it is Local - 5:30)
            var utcTime = localTime.ToUniversalTime();
            var utcTime1 = TimeZoneInfo.ConvertTimeToUtc(localTime, TimeZoneInfo.Local);
            var utcTime2 = TimeZoneInfo.ConvertTimeToUtc(localTime);
            var localTime2 = TimeZoneInfo.ConvertTimeFromUtc(utcTime2, TimeZoneInfo.Local);
 
            // If u receive this from other system, and knows it is UTC
            var receivedUtc = DateTime.SpecifyKind(utcTime, DateTimeKind.Utc);
 
            // .Parse thinks it is UTC(as it ends with Z), though it is local - it adds 5:30
            var localTimeParsedFromZ = DateTime.Parse(localTime.ToString("u"));
            
            //We say it is UTC, so when we use .ToLocalTime, it is really 11 hours added to local time
            var localTimeParsedFromZWithKind = DateTime.SpecifyKind(localTimeParsedFromZ, DateTimeKind.Utc); 
            
 
            Console.WriteLine("local time = " + localTime.ToString());
            Console.WriteLine("local time = local time 1 is " + localTime.Equals(localTime1));
            Console.WriteLine("local time = local time 2 is " + localTime.Equals(localTime2));
            Console.WriteLine("localTime.ToString(u) = " + localTime.ToString("u"));
 
            Console.WriteLine("Time Parsed from 'localTime.ToString(u)' = " + localTimeParsedFromZ.ToString());
 
            Console.WriteLine("local time = " + localTimeParsedFromZWithKind.ToLocalTime().ToString());
            
            Console.WriteLine("utc time = " + utcTime.ToString());
            Console.WriteLine("utc time = utc time 1 is " + utcTime.Equals(utcTime1));
            Console.WriteLine("utc time = utc time 2 is " + utcTime.Equals(utcTime2));
            Console.WriteLine("local time from utc = " + utcTime.ToLocalTime().ToString());
            
            Console.WriteLine("received utc = " + receivedUtc.ToString());
            Console.WriteLine("receivedUtc.ToString(u) = " + receivedUtc.ToString("u"));
 
            foreach (TimeZoneInfo timeZone in TimeZoneInfo.GetSystemTimeZones())
                Console.WriteLine(timeZone.Id);
            var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            var pst = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
            var estLocal = TimeZoneInfo.ConvertTime(localTime, est);
            var pstLocal = TimeZoneInfo.ConvertTime(localTime, pst); 
         }

Tuesday, 12 February 2013

Unit tests - some tips

1. TestContext.WriteLine - If we want to add additional information in to our test result, we use this method within our Test method. To view this additional information, double the test in Test Result window

2. One thread per test - MSTest creates one thread per test. But tests are run sequentially without any order. Try below to verify

        [TestMethod]
        public void TestMethod1()
        {
            System.Threading.Thread.Sleep(1000);
            TestContext.WriteLine("{0}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        }
 
        [TestMethod]
        public void TestMethod2()
        {
            System.Threading.Thread.Sleep(1000);
            TestContext.WriteLine("{0}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        }
 
        [TestMethod]
        public void TestMethod3()
        {
            System.Threading.Thread.Sleep(1000);
            TestContext.WriteLine("{0}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        }
 
3. If we have multiple cores, we can run tests parallel using this

Wednesday, 23 January 2013

Configuring Unity container at runtime

 
1. Some business logic first
 
    public interface ILogger
    {
        void Log(string information);
    }
    
    public class Logger : ILogger
    {
        public void Log(string information)
        {
            Console.WriteLine(information);
        }
    }
 
    public class Employee
    {
        public string FirstName { getset; }
 
        public string LastName { getset; }
 
        public DateTime DOB { getset; }
 
        public Guid ID { getset; }
    }
 
    public interface IEmployeeService
    {
        [BeforeHandler]
        [AfterHandler1]
        [AfterHandler2]        
        bool AddOrUpdate(Employee employee);
 
        [BeforeHandler]
        [AfterHandler1]
        [AfterHandler2]
        Employee Get(Guid id); 
 
        [BeforeHandler]
        [AfterHandler1]
        [AfterHandler2]          
        bool Delete(Guid id);
    }
 
    public class EmployeeService : IEmployeeService
    {
        public EmployeeService(ILogger logger)
        {
            this.Logger = logger;
        }
 
        private ILogger Logger { getset; }
        #region IEmployeeService Members
 
        public bool AddOrUpdate(Employee employee)
        {
            this.Logger.Log("AddOrUpdate called");
 
            return true;
        }
 
        public Employee Get(Guid id)
        {
            this.Logger.Log("Get called");
 
            return new Employee();
        }
 
        public bool Delete(Guid id)
        {
            this.Logger.Log("Delete called");
 
            return true;
        }
 
        #endregion
    }
 
2. Now Add some handlers/Matching rules 

public class AlwaysMatchingRule : IMatchingRule
    {
        public bool Matches(System.Reflection.MethodBase member)
        {
            return true;
        }
    }
 
    public class BeforeHandler : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Console.WriteLine("CallHandler '{0}' will now execute '{1}', Order '{2} "this.GetType().Name, input.MethodBase.Name, this.Order);
 
            return getNext().Invoke(input, getNext);
        }
 
        public int Order { getset; }
    }
 
    public class AfterHandler1 : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var result =  getNext().Invoke(input, getNext);
 
            Console.WriteLine("CallHandler '{0}' executed '{1}', Order '{2}' "this.GetType().Name, input.MethodBase.Name, this.Order);
 
            return result;
        }
 
        public int Order { getset; }
    }
 
    public class AfterHandler2 : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var result = getNext().Invoke(input, getNext);
 
            Console.WriteLine("CallHandler '{0}' executed '{1}', Order '{2}' "this.GetType().Name, input.MethodBase.Name, this.Order);
 
            return result;
        }
 
        public int Order { getset; }
    }
 
    public class BeforeHandlerAttribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        {
            return new BeforeHandler();
        }
    }
 
    public class AfterHandler1Attribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        {
            return new AfterHandler1();
        }
    }
 
    public class AfterHandler2Attribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        {
            return new AfterHandler2();
        }
    } 
 
3. Now configuring container 

        static void Main(string[] args)
        {
            //case 1: simple configuration
            IUnityContainer container1 = new UnityContainer()
                                        .RegisterType<ILogger, Logger>()
                                        .RegisterType<IEmployeeService, EmployeeService>(new InjectionConstructor(typeof(ILogger)));

            //case 2: Here ILogger will be resolved automatically, not need to inject
            IUnityContainer container2 = new UnityContainer()
                                        .RegisterType<ILogger, Logger>()
                                        .RegisterType<IEmployeeService, EmployeeService>();

            //case 3: Different way(obselete) of injection
            IUnityContainer container3 = new UnityContainer()
                                        .RegisterType<ILogger, Logger>()
                                        .RegisterType<IEmployeeService, EmployeeService>()
                                        .Configure<InjectedMembers>()
                                        .ConfigureInjectionFor<EmployeeService>(
                                        new InjectionConstructor(typeof(ILogger))).Container;

            //case 4: Configuring with Policies->Rules->CallHandlers and 
            IUnityContainer container4 = new UnityContainer();

            container4.AddNewExtension<Interception>();
            
            container4
                        .Configure<Interception>()
                            .AddPolicy("Trace")
                                .AddMatchingRule("AlwaysMatchingRule")
                                .AddCallHandler("BeforeHandler")
                                .AddCallHandler("AfterHandler1")
                                .AddCallHandler("AfterHandler2").Interception.Container
                        .RegisterType<IMatchingRule, AlwaysMatchingRule>("AlwaysMatchingRule")
                        .RegisterType<ICallHandler, BeforeHandler>("BeforeHandler", new InjectionProperty("Order", 1))
                        .RegisterType<ICallHandler, AfterHandler1>("AfterHandler1", new InjectionProperty("Order", 2))
                        .RegisterType<ICallHandler, AfterHandler2>("AfterHandler2", new InjectionProperty("Order", 3))
                        .RegisterType<ILogger, Logger>()
                        .RegisterType<IEmployeeService, EmployeeService>()
                        .Configure<Interception>()
                        .SetInterceptorFor<IEmployeeService>(new TransparentProxyInterceptor());

            //case 5: Using handler attributes - simplest of configuration
            IUnityContainer container5 = new UnityContainer();

            container5.AddNewExtension<Interception>();
            container5
                        .Configure<Interception>()
                            .SetDefaultInterceptorFor<IEmployeeService>(new TransparentProxyInterceptor())
                        .Container
                        .RegisterType<ILogger, Logger>()
                        .RegisterType<IEmployeeService, EmployeeService>();

            ExerciseAllServices(container1.Resolve<IEmployeeService>());
            ExerciseAllServices(container2.Resolve<IEmployeeService>());
            ExerciseAllServices(container3.Resolve<IEmployeeService>());
            ExerciseAllServices(container4.Resolve<IEmployeeService>());
            ExerciseAllServices(container5.Resolve<IEmployeeService>());
 
            container1.Dispose();
            container2.Dispose();
            container3.Dispose();
            container4.Dispose();
        }

        private static void ExerciseAllServices(IEmployeeService service)
        {
            service.AddOrUpdate(null);
            service.Get(Guid.Empty);
            service.Delete(Guid.Empty);
            Console.WriteLine("-----------------------------------------------");
        } 
 
 
Some good References
http://blogsprajeesh.blogspot.in/2009/12/unity-application-block-interceptor.html 
http://msdn.microsoft.com/en-us/library/ff660871%28v=pandp.20%29.aspx 
http://msdn.microsoft.com/en-us/library/dd203208.aspx 
http://msdn.microsoft.com/en-us/library/ff647107.aspx