Tuesday, 26 February 2013

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 

Tuesday, 18 December 2012

My java experience

1. In JUnit, we have assertTrue & assertFalse for evaluating conditions

2. How to split array into array of arrays & join them back

    public static ArrayList<byte[]> Split(byte[] bytes, int size)
    {
        if(bytes == null || bytes.length <= 0) return null;

        int offset = 0;
        ArrayList
<byte[]> splittedByteArray = new ArrayList();

        while (offset < bytes.length)
        {
            byte[] outputBytes;

            if(bytes.length - offset < size )
            {
                outputBytes = new byte[bytes.length - offset];
                System.arraycopy(bytes, offset, outputBytes, 0, bytes.length - offset);
                splittedByteArray.add(outputBytes);

                break;
            }

            outputBytes = new byte[size];
            System.arraycopy(bytes, offset, outputBytes, 0, size);
            splittedByteArray.add(outputBytes);
            offset += size ;
        }

        return splittedByteArray;
     }


     public static byte[] Join(ArrayList<byte[]> bytes)
    {
        if(bytes == null || bytes.size() <= 0) return null;

        int finalByteSize = 0;

        for(int index = 0; index < bytes.size(); index++)
        {
            finalByteSize += bytes.get(index).length;
        }

        byte[] outputBytes = new byte[finalByteSize];
        int desPos = 0;

        for(int index = 0; index < bytes.size(); index++)
        {
            byte[] data = bytes.get(index);

            System.arraycopy(bytes.get(index), 0, outputBytes, desPos, data.length);
            desPos += data.length;
        }

        return outputBytes;
    }

3. ConvertToBase64 & ConvertFromBase64

     public static ArrayList<String> ConvertToBase64(ArrayList<byte[]> byteArray)
    {
        if(byteArray == null || byteArray.isEmpty()) return null;

        ArrayList
<String> base64EncodedStrings = new ArrayList<String>();

        for(int index = 0; index < byteArray.size(); index++)
        {
            String base64encoded = new String(com.lowagie.text.pdf.codec.Base64.encodeBytes(byteArray.get(index)));
            base64EncodedStrings.add(base64encoded);
        }

        return base64EncodedStrings;
    }

    public static ArrayList
<byte[]> CovertFromBase64(ArrayList<String> base64encodedArray)
    {
        if(base64encodedArray == null || base64encodedArray.isEmpty()) return null;

        ArrayList
<byte[]> base64decodedArrays = new ArrayList<byte[]>();

        for(int index = 0; index < base64encodedArray.size(); index++)
        {
            byte[] base64decodedArray = com.lowagie.text.pdf.codec.Base64.decode(base64encodedArray.get(index));
            base64decodedArrays.add(base64decodedArray);
        }

        return base64decodedArrays;
    }


4. How to convert InputStream into byte[], we can use IOUtils.toByteArray(stream). This is part of apache sdk.

5.  ASCII encoding

     String data = "This is to test splitting the bytes";
      byte[] bytes = data.getBytes("US-ASCII");


6. Arrays.equals helps compare two arrays are equal or not(similar to SequenceEqual in c#)

Friday, 14 September 2012

How to : View or Configure Exchange ActiveSync Mailbox Policy Properties

1. Open Exchange Management Console installed in your CAS server.
2. Go To Organization Configuration > Client Access.
3. Click tab Exchange ActiveSync Mailbox Policies.

for more info

Monday, 6 August 2012

Powershell : Import-Module : Could not load file or assembly

Sometimes you might face above issue while importing module(written using C# dll) downloaded from internet. One reason could be that, windows considers downloaded dll's as malicious or whatever, so just 'Unblock'(right-click into Properties->General tab) if you trust it.