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.

Thursday, 19 July 2012

IP Address's

Loop back address - It is a virtual network interface implemented in software only and not connected to any hardware, but which is fully integrated into the computer system's internal network infrastructure. Any traffic that a computer program sends to the loopback interface is immediately received on the same interface. Localhost is mapped to loopback address, usually 127.0.0.1 for IPv4, although any address in the range 127.0.0.0 to 127.255.255.255 is mapped to it. IPv6 designates only a single address for this function, 0:0:0:0:0:0:0:1 (also written as ::1).

Unspecified or 0:0:0:0 or * address - represents any address, but should not be present on outgoing packets. If you bind a listening socket to 0.0.0.0, you're telling the OS to accept connections on any ip address that the host has network adapters bound to. e.g. if your host had two network adapters with two different ip addresses. You can bind a socket to either one and it will accept connections only on that adapter. Or you can bind a socket to 0.0.0.0 (INADDR_ANY in WinSock) and it will bind to both adapters.

Private address - used within organization, range from 192.168.0.0 to 192.168.255.255 and 172.16.0.0 to 172.16.255.255

Public address - can be static or dynamic(per internet session). Static IP's are used sometime for gaming or hosting website etc.

IPV6 - IPV4 is 4 part address with each part size is of 8 bits, so totally 32 bits. It allows 4,29,49,67,296 or 2^32 addresses. But IPV6 is 8 part address with each part size is of 16 bits, so totally 128 bits.

Sample code to figure out whether IP address is 32 or 128 bits

    string input = "your IP address goes here";

    IPAddress address;
    if (IPAddress.TryParse(input, out address))
    {
        switch (address.AddressFamily)
        {
            case System.Net.Sockets.AddressFamily.InterNetwork:
                // we have IPv4
                break;
            case System.Net.Sockets.AddressFamily.InterNetworkV6:
                // we have IPv6
                break;
            default:
                // umm... yeah... I'm going to need to take your red packet and...
                break;
        }
    }

Wednesday, 4 July 2012

Split unity configuration file

For maintenance reasons, it is better to split a 'BIG' unity configuration into multiple files. One such way to do this is

1. Let us imagine we need to split into two files, so your root config file will look like below

<configSections>
    <section name="unitySection1
          type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
          Microsoft.Practices.Unity.Configuration"/>
    <section name="unitySection2
          type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
          Microsoft.Practices.Unity.Configuration"/>
</configSections>

<unitySection1 configSource="unity1.config" />
<unitySection2 configSource="unity2.config" /> 
 
2. And your individual unity files will look like below(see the highlighted section that 'unity' tag becomes 'unitySection1')
 
   <unitySection1>
       <container /> 
   </unitySection1>
 
   <unitySection2
       <container />
   </unitySection2>
 
3. Load the separate configuration files into Container


    UnityContainer.LoadConfiguration - will adds up the container details, so we just need to call it twice


 private void Initialise()
 {
   string[] unitySections = new string[] {"unitySection1", "unitySection2"};
  
   IUnityContainer container = new UnityContainer(); 
 
   foreach(var section in unitySections)
   {
      var configuration = ConfigurationManager.OpenExeConfiguration(path);
 
      var unitySection = (UnityConfigurationSection)configuration.
                          GetSection(section);
        
      container.LoadConfiguration(unitySection);
    }
 }
 
reference link 

CmdLet.ShouldContinue

Please refer this

Below example code

protected override void ProcessRecord()
{
    if (this.ShouldContinue("Are you sure you want to uninstall""Confirm Uninstall"))
    {
        //your script here
    }
}

Thursday, 21 June 2012

IRequestChannel - Demo 1

Let's assume below ServiceContract

[ServiceContract]
public interface IDemo1
{
    [OperationContract]
    string HelloWorld(string name);
}

so how can we invoke above using IRequestChannel

var httpsBasicBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
var endpoint = "https://host/service.svc";
var channelFactory = new ChannelFactory<IRequestChannel>(httpsBasicBinding, endpoint);
var channel = null;
 
try
{
    channelFactory.Open();
 
    channel = channelFactory.CreateChannel();
 
    channel.Open(); 
    
    string body = "<HelloWorld xmlns="http://tempuri.org/"><name>Suresh</name></HelloWorld>";
    var messageBody = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(body)
    Message message = Message.CreateMessage(MessageVersion.Soap11,  
                       "http://tempuri.org/IDemo1/HelloWorld");
 
    Message response = channel.Request(message);
    var result = response.GetReaderAtBodyContents().ReadOuterXml(); //parse based on the requirments
    
    Console.WriteLine(result);
    
    channel.Close();
}
finally
{
    channel.close(); //abort if faulted 
    channelFactory.Close(); //abort if faulted
}
 
reference : http://www.codeproject.com/Articles/34632/How-to-pass-arbitrary-data-in-a-Message-object-usi 

Wednesday, 13 June 2012

XSD: restriction on type to not be empty or blank

I wanted to create a SimpleType called 'ValidInput', basically i don't want to allow empty spaces. I started with below but for some reasons it worked on XML SPY, but not thru c#.

  <xs:simpleType name="ValidInput">
    <xs:restriction base="xs:string">
      <xs:minLength value="1"/>
      <xs:whiteSpace value="collapse"/>
    </xs:restriction>
  </xs:simpleType>

But below worked, can't figure out why


<xs:simpleType name="ValidInput">
    <xs:restriction base = "xs:string">
       <xs:minLength value="1" />
       <xs:pattern value=".*[^\s].*" />
   </xs:restriction>
</xs:simpleType>

Monday, 21 May 2012

Any CPU vs x64 vs x86

When we compile .net applications/libraries we get IL's, not Machine readable codes. So when we say 'Any CPU'(in a way architecture-neutral PE files) we create neutral IL's, and as part of JIT compilation, output will be either x64 or x86 PE's based on executing machine or calling process.

On a 32-bit machine:
  • Any CPU: runs as a 32-bit process, can load Any CPU and x86 assemblies, will get BadImageFormatException if it tries to load an x64 assembly.
  • x86: same as Any CPU.
  • x64: BadImageFormatException always.
On a 64-bit machine:
  • Any CPU: runs as a 64-bit process, can load Any CPU and x64 assemblies, will get BadImageFormatException if it tries to load an x86 assembly.
  • x86: runs as a 32-bit process, can load Any CPU and x86 assemblies, will get BadImageFormatException if it tries to load an x64 assembly.
  • x64: same as Any CPU.
It is the JIT compiler that generates an assembly code that's compatible with the requested target based on this flag.

Also CorFlags.exe assembly.dll|assembly.exe will tell us whether it is targeted x86 or Any CPU
Just for clarification, CorFlags.exe is part of the .NET Framework SDK. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:
  1. Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)
  2. CD to the directory containing the DLL in question
  3. Run corflags like this: corflags MyAssembly.dll
You will get output something like this:
    Microsoft (R) .NET Framework CorFlags Conversion Tool.  Version  3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.
Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32CorFlags  : 3
ILONLY    : 1
32BIT     : 1
Signed    : 0
The key is the "32BIT" flag as documented above: 1 = x86; 0 = Any CPU.
·        Any CPU: PE = PE32    and  32BIT = 0
·         x86:         PE = PE32    and  32BIT = 1
      ·         x64:         PE = PE32+  and  32BIT = 0



Compilation and Deployment in ASP.NET 2.0

Just for my reference, good article from Rick Strahl

Wednesday, 16 May 2012

500.0 Internal Server Error - aspnet_isapi.dll failed in IIS 7.5

If you experience '500.0 Internal Server Error - aspnet_isapi.dll failed' even after trying all possibilities like 'aspnet_regiis -i' etc..., just uninstall IIS and Re-install again, it just works. It is Microsoft:)

I faced this when i installed Framework 4.0, so uninstalled IIS 7.5/Framework4.0 and re-installed both.

Monday, 23 April 2012

Error message when you visit a Web site that is hosted on IIS 7.5: "HTTP Error 404.17 - Not Found"

This article might help, but we need to look for three things particularly

configure the following settings to match the handler requirements:
  • .NET Framework Version
  • Enable 32-Bit Applications
  • Managed Pipeline Mode

HTTP 500.0 - Internal Server Error in Windows 2008 R2 Server

After deploying a 32-Bit WCF service in IIS 7.5(Windows 2008 R2 server), browsing the service failed with
HTTP 500.0 - Internal Server Error, and from the error message i figured out something wrong with PageHandlerFactory. For 32-Bit web apps, it is mandatory to set 'Enable 32-Bit Applications' to 'True'. We can either set it @ 'Application Pool Defaults' or the specific Application Pool in question.

Sample powershell scripts

ProjectDir - Project Folder
OutDir - either bin\debug or bin\release or whatever set as output directory

1. To Copy files from 'some folder' into output directory  - below copies everything from 'libs' folder which is at same level as that of our Project directory into Project directory's output.

    copy /Y $(ProjectDir)\..\libs\* $(ProjectDir)\$(OutDir)\

to be contd....

Friday, 13 April 2012

BadImageFormatException in Windows 2008 R2 Server

I successfully imported PowerShell Script written using C#, but it throws System.BadImageFormatException when i tried to execute it. After spending few hours, figured out my Powershell Script was compiled for x86, so i should have used “c:\Windows\SysWOW64\WindowsPowerShell\v1.0”.

Tuesday, 10 April 2012

Useful tips

1. How to load all the assemblies?

var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

2. Combine absolute & relative paths

var relativePath = "..\\bling.txt";
var baseDirectory = "C:\\blah\\";
var absolutePath = Path.GetFullPath(baseDirectory + relativePath);

3. Get x86 Program folder

    static string ProgramFilesx86()
    {
       if( 8 == IntPtr.Size
       || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable( 
                "PROCESSOR_ARCHITEW6432"))))
       {
            return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
       }

        return Environment.GetEnvironmentVariable("ProgramFiles");
    }

4. Delete a windows server

   sc delete [servicename]

5. Sometimes Server.Databases[name].Drop() will fail with 'Currently in use' error 
   or FailedOperationException. These scenarios we have to 'Server.KillDatabase()).

6. Script to create User with server admin role

 USE [master];
 GO
 CREATE LOGIN SimpleUser
    WITH PASSWORD    = N'SimpleUser',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
 GO
 EXEC sp_addsrvrolemember
    @loginame = N'SimpleUser',
    @rolename = N'sysadmin';

7. Sn -T [assembly] to get PublicKeyToken.

8. Remove database(s) based on name

DECLARE @Temp TABLE (Id INT IDENTITY(1, 1), name nvarchar(max));
DECLARE @RowCounter INT;
DECLARE @i INT;

INSERT INTO @Temp select name from sys.databases where name like N'GS_81%'

SELECT @RowCounter = MAX(Id) FROM @Temp

SET @i = 1

DECLARE @DBDeleteByName NVARCHAR(max);

WHILE @i <= @RowCounter
BEGIN
    SELECT @DBDeleteByName = 'DROP DATABASE [' + name + ']'  FROM @Temp WHERE Id = @i

    EXEC sp_executesql @DBDeleteByName;

    SET @i = @i + 1;
END

Thursday, 15 March 2012

Smartbear Code Collaborator GUI client not recognizing Subversion repository

Sometimes creating SCM configuration in Code Collaborator GUI client for a SVN server will not work and might get 'svn not found' or 'path not found' error. Please visit this link for fix

Wednesday, 29 February 2012

Console.OutputEncoding

Sometimes we need to output non-english characters in Console, this is possible(really?) using Console.OutputEncoding property. Below is sample code to output latin & chinese characters

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

namespace Test
{
    class Program
    {
        static string latinString = "蘇雷什";
        static string chineseString = "蘇雷什:密碼";

        [DllImport("kernel32.dll")]
        static extern bool SetConsoleOutputCP(uint wCodePageID);

        static void Main(string[] args)
        {
            var latinEncoding = Encoding.GetEncoding("ISO-8859-1");
            var utf8Encoding = Encoding.GetEncoding("UTF-8");

            //-------Start Chinese Characters------------

            SetConsoleOutputCP((uint)utf8Encoding.CodePage);

            Console.OutputEncoding = utf8Encoding;
            Console.WriteLine(chineseString);
          
            //-------End Chinese Characters------------

            //-------Start Latin Characters------------

            SetConsoleOutputCP((uint)latinEncoding.WindowsCodePage);

            Console.OutputEncoding = latinEncoding;
            Console.WriteLine(latinString);

            //-------End Latin Characters------------
        }
    }
}

But wait - it ain't going to display on windows(English) OS.

http://stackoverflow.com/questions/6405428/can-i-get-console-to-show-chinese
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/fe549b29-3e09-4176-b317-1e0094abf71a/
http://www.csharp-examples.net/culture-names/
http://stackoverflow.com/questions/2213541/vietnamese-character-in-net-console-application-utf-8

Wednesday, 15 February 2012

Useful functions - contd.....

public static void PrintHexString(byte data)
{
     Console.WriteLine("Hex of {0} is {1}", data, BitConverter.ToString(BitConverter.GetBytes(data)));
}
-----------------------
private static void DemoNegativeNumberStorageInBinary()
{
            Console.WriteLine("Binary Representation of {0} - {1}", 1000, Convert.ToString(1000, 2));

            /* how negative is done
             * short value = -7;
             * 7 = 0000 0000 0000 0111
             * Not (7) = 1111 1111 1111 1000
             * Add 1 = 1111 1111 1111 1000
             *                           +
             *                           1
             *         1111 1111 1111 1001
             *         (1)111 1111 1111 1001 - is negative because it is 1
             *        
             *         -7 + 7 = 0
             *          1111 1111 1111 1001 (+)
             *          0000 0000 0000 0111
             *          0000 0000 0000 0000
            */
            Console.WriteLine("Binary Representation of {0} - {1}", -1000, Convert.ToString(-1000, 2));
}
-----------------------


Unicode and Encoding

Just for my reference
http://csharpindepth.com/Articles/General/Unicode.aspx
http://stackoverflow.com/questions/496321/utf8-utf16-and-utf32
http://stackoverflow.com/questions/643694/utf-8-vs-unicode

In nutshell
1. .Net, by default use UTF - 16, and Encoding.Unicode means  UTF - 16.
2.  UTF8: Variable-width encoding, backwards compatible with ASCII. ASCII characters (U+0000 to U+007F) take 1 byte, code points U+0080 to U+07FF take 2 bytes, code points U+0800 to U+FFFF take 3 bytes, code points U+10000 to U+10FFFF take 4 bytes. Good for English text, not so good for Asian text.
3. UTF16: Variable-width encoding. Code points U+0000 to U+FFFF take 2 bytes, code points U+10000 to U+10FFFF take 4 bytes. Bad for English text, good for Asian text.
4. UTF32: Fixed-width encoding. All code points take 4 bytes. An enormous memory hog, but fast to operate on. Rarely used.

Monday, 30 January 2012

Abstract Factory vs Factory

There are numerous post out there to explain the differences - i just wanted to add on

Factory - encapsulates the logic of creating a concrete type
Abstract Factory - encapsulates grouping of related factories.

I always start with Factory pattern first to decouple the creation logic from client.
So when will we go for Abstract Factory - as soon as your factory method violates Open/Closed principle. If your Factory method contains lots of 'if/else' or 'switch' statements, then it is time to move onto Abstract Factory. Please refer this article.

Also DBProviderFactory is another example of AF pattern. SqlClientFactory, OracleClientFactory, OleDbFactory are all grouped under DBProviderFactory.

http://en.wikipedia.org/wiki/Abstract_factory_pattern
http://en.wikipedia.org/wiki/Factory_object
http://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.80%29.aspx


Tuesday, 24 January 2012

Modifying Web.Config at run time

Sample code to update an app setting in web.config file at run time. I assume the user have physical path of the web.config, instead of virtual directory.

private static void ChangeAppSettting(string oldValue, string newValue)
{
            string appSettingName = "your app setting name";
            string configFilePath = "Your web.config path";
            Configuration configuration = OpenConfigFile(configFilePath );

            AppSettingsSection appSettings = configuration.AppSettings;

            if (appSettings != null && appSettings.Settings[appSettingName] != null)
            {
                appSettings.Settings[AppSetting].Value = newValue;
                configuration.Save();
            }
        }

        private static Configuration OpenConfigFile(string configPath)
        {
            FileInfo configFile = new FileInfo(configPath);
            VirtualDirectoryMapping virtualDirectoryMapping = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
            var webConfigFileMap = new WebConfigurationFileMap();
            webConfigFileMap.VirtualDirectories.Add("/", virtualDirectoryMapping);
            return WebConfigurationManager.OpenMappedWebConfiguration(webConfigFileMap, "/");
        }