Monday, March 31, 2014

Haskell : Unique right angle triangles without using Set operations (nub).

In GHCi, create a list of triangle values with tuples as below.
*Main> let triangles = [ (a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10] ] 
Now create a list of right angle triangles by
*Main> let rightAngleTriangle = [ (a,b,c)|(a,b,c) <- triangles , a^2 == b ^2 + c ^ 2]
Here variable a is hypotenuse. b and c are representing other 2 sides. Now call the function.
*Main> rightAngleTriangle
[(5,4,3),(5,3,4),(10,8,6),(10,6,8)]
The above result contains duplicate values. For a single hypotenuse value it printed twice. 2 Methods:

Method 1:

*Main> let rightAngleTriangle = [ (a,b,c)|(a,b,c) <- triangles , a > b, b > c,  a^2 == b ^2 + c ^ 2]

In the above example, I just added 2 conditions, a > b and b > c. That restricts the number of permutations.

Method 2:

*Main> let rightAngleTriangle2 = [(a,b,c) | a <- [1..10], b <- [1..a], c <- [1..b], a ^ 2 == b ^ 2 + c ^ 2] 

In the second example, we are taking a,b and c values separately instead of getting from a tuple. This also produces the same result.

Why not nub?

The nub is slower when we apply it in complex programs. The following one is the nub version.

*Main> import Data.List
*Main Data.List> nub rightAngleTriangle
[(5,4,3),(10,8,6)]
It is slow, because it works after the expression is evaluated. To confirm that, the following one produces duplicate values.
*Main Data.List> let rightAngleTriangle3 = nub [ (a,b,c)|(a,b,c) <- triangles , a^2 == b ^2 + c ^ 2]

*Main Data.List> rightAngleTriangle3
[(5,4,3),(5,3,4),(10,8,6),(10,6,8)]

So better to prevent the duplication at origin.

Monday, February 17, 2014

Gradle Dependencies Error

src\main\java\com\package\HelloWorldServlet.java:5: error: package javax.servlet does not exist
import javax.servlet.ServletException;
OR
error: cannot find symbol
public class HelloWorldServlet extends HttpServlet {

When we get any one of the above error there must be a problem of missing depencies in gradle. In this case I missed the below line. providedCompile 'javax.servlet:servlet-api:2.5'

The complete code:

dependencies {
   providedCompile 'javax.servlet:servlet-api:2.5' //I missed this line.
}

Saturday, February 1, 2014

Working with H2, Gradle, H2Sharp, IntelliJ Idea and Flyway - Experience

1. In gradle with flyway, the H2 database doesn't work at version 1. It doesn't throw any error, it says migration is successful. But it doesn't create tables in the database. So we should start from the version 2 sql files.
Example: V1__TestDatabaseSchema.sql file doesn't work.
V2__TestDatabaseSchema.sql file works. Version number matters

2. There must be double hyphen in the filename after the version number (V2, V1 and etc).

3. I faced "Connection refused: connect" in IntelliJ.
So I tried various options like enabling IPV4, windows hot fix, installing ISA Client, restarting machine, switched java language level in IntelliJ, disabled firewall and other options mentioned in the internet. Finally I added http proxy in the IntelliJ Idea. That worked. In my office network I have Automatic configuration script enabled.

I posted my solution to the public forum http://stackoverflow.com/questions/12701347/unable-to-import-maven-project-into-intellij-idea/20758527#20758527.


So I copy pasted the proxy settings as below in IntelliJ Idea.
I was unable to download maven project from IntelliJ. When I typed the library names, it didn't give me any result. The above solution fixed this problem too. 4. When connecting H2 database with other tools in file mode, the same database should not be open in Web UI. The reason is, in file mode, multiple JVM deamons cannot access the database at the same time, it throws error. The file will be locked by one JVM deamon process.
Example: jdbc:h2:file:F:\folderName\fileName;

5. The order for running gradle script to migrate H2 via flyway is
flywayClean, flywayInit, flywayMigrate
So when there is any error in the migrate, after making changes re-run from flywayClean. flywayClean drops all tables.

6. The Sql Server Mode is mandatory when connecting to the H2 Web Console. Otherwise the query for sql server won't compile. It will succeed when running gradle scripts, but won't yeild result.

7. There are two version of H2 Sharp available in the internet.
    a. Git https://code.google.com/p/h2sharp/
    b. Google code https://github.com/Remo/h2sharp/tree/master/Dlls
Code downloaded from google code didn't work, I faced compile errors. Only git version worked for me.

8. Be careful about datetime field when using H2+H2Sharp in a .net project. It didn't work for me.

Example Program for H2 with Gradle, Flyway in IntelliJ Idea

This is an example program to work with H2, Gradle, Flyway and IntelliJ Idea. Download the example program H2Test_SampleProgram.zip.

1. To see the Gradle tasks window from IntelliJ Idea, follow the below steps.


2.Here is the order, to run gradle tasks.


3. To see the output, connect the H2 database and run the following queries. The table Schema_Version will be automatically created and updated by flyway.

The H2 Compatible SQL Query

This article describes the difference between H2 compatible sql query and Sql compatible sql query.

1. All the [dbo] schema prefixes must be removed. In H2, the default schema is "public".

2. The most important thing in H2 is to understand the case sensitivity. It expects exact case in queries, otherwise it will throw error, such as "Table not found" or "Column not found".

3. By default H2 creates all the tables and columns in upper case letters. such as Create Table userinfo(info int); will be created as USERINFO and the column name in it will be INFO. Two ways to avoid this upper upper case problem.
    a. Using square bracket.
    b. Appending the following in the connection string.
DATABASE_TO_UPPER=FALSE;

4. H2 is square bracket sensitive. Note that [App] totally different from app.


5. In the above case it creates multiple tables in the same name but with different cases. Database_To_Upper is an another option to solve case sensitive issue. I recommend to use "Database_To_Upper" always.


6. Apart from tables and columns, the data in H2 is also case sensitive by default. To avoid case sensitivity, there are two options. IgnoreCase=True option in connection string.
Using collation. SET COLLATION ENGLISH STRENGTH PRIMARY;
To know more about collation set_collation

7. There are two benefits of using collation
    1. Case-insensitive columns are compared faster when using collation.
    2. String literals and parameters are however still considered case sensitive even if IgnoreCase option is set.


8. But if you look at the below picture the problem is fixed when we use Collation.


9. Collation must be set before any table created, otherwise you will receive an error.

10. To view current collation SELECT * FROM INFORMATION_SCHEMA.SETTINGS

The best practice is must not use square bracket. Use Database_To_Upper=False; and use collation as Primary. Information_Schema is the only system table mostly we refer for schema related queries. It contains all the tables, columns and constraints related information.


11. Remove "CLUSTERED" and "NONCLUSTERED" keywords from sql server compatible sql queries.

12. ; (semicolon is mandatory at the end of all statements)

13. There is no built-in user defined function in H2. We should use alias to simulate UDF. The alias uses the java code. Here is the example function.
    a. DROP ALIAS Table_Row_Count IF EXISTS;

    b. CREATE ALIAS Table_Row_Count AS
       'long Table_Row_Count(Connection conn, String tableName)
       throws SQLException {
       ResultSet rs = conn.createStatement().
       executeQuery("select count(*) from \"" + tableName + "\"");
       rs.next();
       return rs.getLong(1); }';

    c. We can use the above function by calling
       SELECT Table_Row_Count(table_name) AS RowCount FROM INFORMATION_SCHEMA.TABLES
14. '=' operator is not accepted as column alias as in sql server. We should use only "AS" operator.

15. CHECK CONSTRAINT ddl doesn't require to enforce constraints as in sql server. By default as soon as the contraints are created, they are enforced.

16. WITH CHECK doesn't require as in sql server.

17. SqlBulkCopy option is not available in H2.

H2 - Introduction

1. What is H2?

H2 is a super fast in-memory database. It is mainly used for integration testing.

2. Why do we use H2?

Since it is an in-memory database, it is faster than other database engines. It's foot print is very less (~1 MB). In a build environment we don't need a sql server instance to run integration tests, instead this H2 database simulates the sql server instance. H2 instances will be destroyed once the VM is closed. The following links are comparing H2 with other in-memory databases
H2-vs-SQLite
H2 and SQLite

3. Who manages H2 instance for the application?

In general any build tool. In our case, gradle creates the H2 database and fills data in it. A batch file also can manage H2 instance. Example H2 with Gradle and Flyway Program.

4. How do I configure H2 in my local?

a. Install H2 from download link
b. Default port number for H2 is 8082.
c. Then follow the quick start tutorial Quick Start. When launching the "H2 Console", if it says "Unable to access the network", then replace the IP address with "localhost" such as,

    http://192.168.112.13:8082/
    as
    http://localhost:8082/

    Reason: Because of the network settings in the office. I didn't face this error at my home.
d. Check the CLASSPATH environment variable, if it doesn't include the H2 jar file location, append it in the CLASSPATH variable. My CLASSPATH is variable is .;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip;C:\Program Files (x86)\H2\bin\h2-1.3.174.jar;
e. default username is : sa
f: default password is: <empty> (don't give any password)

5. What connection option should I use?

Although there are many ways to connect the database as mentioned here Database Urls. But for integration tests we must use Server Mode.
Example: jdbc:h2:tcp://localhost/mem:TestDatabaseName;

6. How to enable Sql Server Mode?

Append the following option in the connection string.
MODE=MSSQLServer; Now the url will look like
jdbc:h2:tcp://localhost/mem:TestDatbaseName;MODE=MSSQLServer

7. How long this database will persist?

Unless you mention DB_CLOSE_DELAY=-1; The database will be destroyed from the in-memory as soon as you disconnect it. In order to access other java programs out of gradle, you must mention close delay option also.
Example: jdbc:h2:tcp://localhost/mem:TestDatbaseName;MODE=MSSQLServer;DB_CLOSE_DELAY=-1;
To know more about DB_CLOSE_DELAY Close Delay

8. What is "Driver Not Found" error?

As far as I know, there are two reasons.
a. If you miss the H2 jar file or H2 dll. In our case it is h2-1.3.174.jar or h2-1.3.174.dll. Set the right CLASSPATH as mentioned in Question No 4: d.
b. if you give wrong connection string, such as,
tcp://localhost/mem:TestDatbaseName;MODE=MSSQLServer;DB_CLOSE_DELAY=-1;
The above connection string misses "jdbc:h2:" in the front. So it could not find the driver.

9. What is the driver for H2?

"org.h2.Driver"
in .net you should use it as
org.h2.Driver.load();

10. How JVM deamon behaves for H2?

Since H2 is an in-memory database, the H2 database is per JVM deamon instance. So the database created by one JVM deamon cannot be accessed by the other one. To access a database by all the JVM deamons we must use "server mode" (tcp) option . Within gradle it uses only one JVM deamon. But when we access data generator tool, the data generator will create a new JVM deamon instance. Then data generator tool will search for a database within it's own JVM deamon process, if it doesn't find the database already, it creates a new database on it's own.

11. How do I verify if the same database is used by all the JVM deamons?

If you are using non-tcp connections, this problem may arise.
Create a database without IFEXISTS=TRUE option
jdbc:h2:mem:TestDatbaseName;MODE=MSSQLServer;DB_CLOSE_DELAY=-1;
Add tables in it.
Now in the another process, which access the same database, use IFEXISTS=TRUE option in the connection string. Now you shouldn't throw "database not found" error.
jdbc:h2:mem:TestDatbaseName;MODE=MSSQLServer;DB_CLOSE_DELAY=-1;IFEXISTS=TRUE;
To know more about it Exists

12. Are there any difference between in sql query for H2?

Yes, Here is the list of differences H2 - Tips and Tricks

13. What is H2 Sharp? Any example c#.net program to connect H2?

H2 Sharp is a .net API to access H2 from .net. You need IKVM binaries to use H2 Sharp.
H2 Sharp from github has a sample program.
H2 Sharp download h2sharp
IKVM binaries download IKVM binaries
As far as I know, only the above links are in working condition. The H2 Sharp, I downloaded from the google code version didn't work.

14. Exampe gradle file for H2 with flyway.

Example H2 with Gradle and Flyway Program.

Multiline Prelude Functions

Prelude is commandline utility for Haskell. Prelude supports one line functions. Such as,
let addThree a b c = a+b+c

If it crosses more than a line. Such as

addThree :: Int -> Int -> Int -> Int  
addThree x y z = x + y + z 

As soon as you hit enter after the first line, you will see error as

:11:1: Not in scope: `addThree'

Solution 1

Create a haskell file such as "addThree.hs" and place the function in it. Now load the file using ":l addThree.hs" at prelude.

Solution 2

You can also use multiline function in prelude. Now semicolon must be used after each line, shouldn't press ENTER key. Most importantly 'let' keyword must be prefixed. Here is the modified version of the above example.
let addThree :: Int -> Int -> Int -> Int; addThree x y z = x + y + z 

Haskell Error 3


quicksort.hs:6:42:
    Unexpected parallel statement in a list comprehension
    Use -XParallelListComp

quicksort.hs:6:44: Not in scope: `a'

I placed '|' (pipeline) instead of a ',' (comma) to separate predicate section. Program with Error:
quicksort :: (Ord a) => [a] -> [a] 
quicksort [] = []
quicksort(x:xs)=let smallerSorted = quicksort [a | a <- xs, a <= x]
                    biggerSorted = quicksort [a | a <- xs| a > x] 
--But it supposed to be "a <- xs, a > x"
in smallerSorted ++ [x] ++ biggerSorted


Haskell Error 2

quickSort.hs:4:1:
    parse error (possibly incorrect indentation or mismatched brackets)
quickSort.hs:4:54: parse error on input `='


Two ways to avoid the above error:
    1: Haskell expects right indentation.
    2: Shouldn't use 'Tab Spacing' for indentation. We must use space bar.

The indentation error occurs only for specific keywords. The 'let' keyword expects the next line to be indented. And then the 'in' keyword should start the same column as 'let' starts.

I don't know why we shouldn't use 'Tab' for indentation. I got the above error because I used the 'Tab Spacing'. Used space bar and solved the problem.
Correct Version:
quicksort :: (Ord a) => [a] -> [a] 
quicksort [] = []
quicksort(x:xs)=let smallerSorted = quicksort [a | a <- xs, a <= x]
                    biggerSorted = quicksort [a | a <- xs, a > x]
                in smallerSorted ++ [x] ++ biggerSorted

Haskell Error 1

Invalid type signature: GetMax :: Ord a => [a] -> a
Should be of form <variable> :: <type>

This is because, the function 'GetMax' starts with capital case, it should be 'getMax'. In haskell function names shouldn't start with capital case, only module names can start with capital case.
Example: getMax :: (Ord a) => [a] -> a

Thursday, June 27, 2013

A Date Check - To Narrow Down the Problem

I was facing an issue this week, wrong date of birth was shown for all the patients. When I look at closer, all the patients had same date of birth as "Jan/1/1970". Then I understood that "Jan/1/1970" must be the default date value of .net/sql server. It means somewhere we missed to assign the value for DOB field. Later we figured out, that it was a javascript issue. "Jan/1/1970" is the default date value of javascript. We missed to assign javascript DOB variable. So, as soon as you see "1970" instead of some other value, you can guess that something goes wrong in javascript.

.Net default date value is Jan-01-0001

Sql server default date value is NULL, starts from Jan-01-1753

Oracle default date value is NULL, starts from Jan-01-4712

Javascript default value is Jan-01-1970

Sunday, February 3, 2013

Why @@SERVERNAME Returns NULL?

The @@SERVERNAME can return NULL, when you accidentally delete the server. Most probably by this query

sp_dropserver '<ServerName>'

After the SQL Server restart, the @@SERVERNAME started returning NULL. You can confirm this; if the following query returns no records, the local server was deleted.

Select * From sys.servers Where server_id=0

Solution 1

Run the following query to add the server back.

sp_addserver '<ServerName>',local

Solution 2

I would recommend you to use

Select ServerProperty('ServerName')

This approach returns the machine name, even if the sever name is not present in the sys.servers table.

The SQL Profiler Secures Username and Password

Whenever you run a login related query, the SQL Profiler converts the credentials as ‘----’ (hyphens). This feature improves SQL server security.

For example when you run this query

EXEC sp_addlogin 'Victoria', 'B1r12-36';

The profiler hides the username and password by substituting with hyphens

--*sp_addlogin---------------------------

Similar way, when you run sp_addlinkedsrvlogin, it will display as

--*sp_addlinkedsrvlogin---------------------------

Designing a Wrapper

Here I am sharing my experience with wrappers. This article is intended for beginners. Nowadays it is a fashion to create a wrapper for every third party library. The theme of this article is to think beyond the present situation. An unnecessarily created wrapper or a poorly designed wrapper will lead to messy code.

Wrappers created only for the two reasons.

  1. Wrapper provides abstraction to a library and makes the developer life easy.
  2. Example: When you have a third party library which has wide range of functionality, but your application needs only very few of them. You should create a wrapper
  3. Wrapper enforces best coding practices of the product to use a third party library.
  4. Example: When there are many options in the third party library but few of the options can only be compatible with your application; you should hide/abstract others.

Points to consider when designing a wrapper

  1. Ask yourself, are you extending the functionality by a wrapper? If that is the case go for extension methods (C#). Unless until you have a solid reason, don’t create a wrapper.
  2. Look around! You may get lot of wrappers from online. But, you need to validate them properly whether it fits your needs and has it well designed. I can see lot of wrappers in code project.
  3. Never create a wrapper with reflection or dynamic calls. The degree of dynamism should be very minimal. In my experience introducing generic types are the maximum limit for designing a wrapper with dynamism. Because of dynamism, when there is a bug, the developer can’t even search it them in Google and can’t get help from any online forum. The wrapper should be very simple and neat.
  4. A poorly designed wrapper restricts thinking ability; you should decide what level of abstraction is needed.

    Example: One of the NHibernate wrappers didn’t allow me to write QueryOver for sub queries. I couldn’t alter the wrapper immediately, because it has dynamic and reflection calls. To understand those dynamic calls, it would have been taken 2 more days. I had to find alternative way.

  5. Think about production issues; never leave a wrapper half-way designed. The wrapper should cover all functionalities of the third party library. You should not design it for the present situation; if the third party library is too big, at least your wrapper should have some guidelines in future if some others want to extend the wrapper. When there is a production issue comes in, developers are forced to fix them as soon as possible. When they fix bugs, they generally don’t alter/extend the wrapper’s design. The code will become messy when the developer finds alternative way to fix the bug.

    Example: We faced a production issue, w3wp.exe was crashing. All our sites were down. The reason was, the wrapper for SqlConnection didn’t handle the SqlDataReader’s close operation. As open connections were not closed, the number of connections crossed the maximum limit and crashed the application. Instead of redesigning the wrapper, we first closed all the opened connections properly by typing “sqlConn.Close()” in 72 places of the application. Then we took time to refine the wrapper.

  6. Writing wrappers often lead to performance problems. You should be careful on that.

Sunday, January 20, 2013

Why Scala Becomes So Popular?

This article is intended for developers who have an agenda to learn at least one programming language in a year. I recommend them to go for Scala this year. Also I strongly believe Scala can become the next best programming language. Here are the reasons.
  1. Scala runs on JVM; takes all the advantages of JVM. Scala is platform independent, object oriented and strongly typed.
  2. Scala has well structured type system than Java. Scala uses unified type system as in C#. For an example, all the types are derived from the base type “Any”. “Nothing” is a subtype of everything and not super type of anything.
  3. Scala syntax is similar to Java. Scala is easier to learn than any other functional language.
  4. You don't have to worry about third party tools for Scala. Third party tools and libraries for Java are matured. Almost all the Java development tools can also be used for Scala. For an example, JUnit can be used as unit testing framework for Scala.
  5. Scala is functional. Functional languages are suitable for scalable architectures. In theory functional languages don't allow to alter the variable's state. All the variables are immutable. (In that way, Haskell is a pure functional language, you can't change the state at all.) The advantage of immutability is thread-safe. You can apply parallelism and threading concepts even if the system is so big and rapidly increasing in size. Scala gives good support for concurrency.
  6. Scala has very good open source IDE supports. I prefer to use Eclipse plug-in for Scala. IntelliJ IDEA from JetBrians is also a good one. The community edition of IntelliJ IDEA is free. Visual Studio plug-in for Scala is also available here.

Comparison with other functional languages

  1. Haskell is another powerful functional language, but it needs a deep learning curve. It doesn't have proper open source editor. The third party tools and libraries for Haskell are not matured enough. Building and installing GHC (Glasgow Haskell Compiler) is very harder than Scala installation.
  2. Though Python is matured and functional, Python has limited support for functional paradigm. Python is not considered for enterprise systems. One of our products in Python didn't scale and faced severe performance problems. Python is suitable for string manipulation or string search based applications. Python is best suited for dynamic programming, so comparing Scala with Python is not fair. (My guess is Groovy may overtake Python in near feature. Groovy also runs on JVM.)
  3. Like any other functional languages Scala compiler supports type erasure and type inference. Checked exceptions in Java is annoying. This is eliminated from Scala. Scala has a lot of developer friendly improvements from Java.
  4. Like F#, Scala also supports multi-paradigm (functional and imperative). One of the reason F# seems to be scary to me is its syntax. Scala syntax is similar to Java, But F# syntax is not similar to C#. See Here. Scala is much more minimalistic language than F#. Scala has a very small orthogonal set of constructs that are re-used throughout the language. F# seems to introduce new syntax for every little thing, thus becoming very syntax heavy as compared to Scala. Scala has 40 keywords, whereas F# has 97”.
  5. Also you can find currying, tuples, anonymous functions, pattern matching and lazy evaluation in Scala.

Clojure is also getting popular. Since I don't have knowledge on Clojure or LISP, I can't compare with Clojure.

Any talk on languages is controversial, the above points are my personal views. I welcome your feedback.

Sunday, November 18, 2012

Could not load type - The Structuremap Error

Recently I got an structuremap error when I launch my application. The error message as follows
Error Message: Exception has been thrown by the target of an invocation. - 0%System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> 
System.TypeLoadException: Could not load type 'MetricsEngine.ApplicationServices.Metrics.IMetricService' from assembly 'MetricsEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

at WebApplication6.Bootstrapper.Registries.ClinicalIntegrationRegistry.<.ctor>b__0(IAssemblyScanner scanner)
at StructureMap.Configuration.DSL.Registry.Scan(Action`1 action) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Configuration\DSL\Registry.cs:line 250
at WebApplication6.Bootstrapper.Registries.ClinicalIntegrationRegistry..ctor() in E:\Src\SolutionFolder\WebApplication6.Bootstrapper\Registries\MetricsRegistry.cs:line 33
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at StructureMap.Graph.PluginGraph.ImportRegistry(Type type) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Graph\PluginGraph.cs:line 232
at System.Collections.Generic.List`1.ForEach(Action`1 action)
at StructureMap.Configuration.DSL.Registry.ConfigurePluginGraph(PluginGraph graph) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Configuration\DSL\Registry.cs:line 397
at StructureMap.Graph.AssemblyScanner.ScanForAll(PluginGraph pluginGraph) in c:\BuildAgent\work\767273992e840853\src\StructureMap\Graph\AssemblyScanner.cs:line 249
at StructureMap.Graph.PluginGraph.Seal() in c:\BuildAgent\work\767273992e840853\src\StructureMap\Graph\PluginGraph.cs:line 121
at StructureMap.PluginGraphBuilder.Build() in c:\BuildAgent\work\767273992e840853\src\StructureMap\PluginGraphBuilder.cs:line 72
at StructureMap.ObjectFactory.Initialize(Action`1 action) in c:\BuildAgent\work\767273992e840853\src\StructureMap\ObjectFactory.cs:line 65
at WebApplication6.Bootstrapper.Bootstrapper.RegisterContainer() in E:\Src\SolutionFolder\WebApplication6.Bootstrapper\Bootstrapper.cs:line 27
at WebApplication6.Bootstrapper.Bootstrapper.Bootstrap() in E:\Src\SolutionFolder\WebApplication6.Bootstrapper\Bootstrapper.cs:line 20

Reason:

My project looks very similar to the following picture.
In the above picture, I am referencing two different dlls from two different sources with the same name "MetricsEngine.dll". Now during the bootstrap the structuremap supposed to load it's referenced assembly(0.0.4696.21382) which is from vendor1, but it loads the assembly (1.0.0.0) from vendor2 which is referenced by WebApplication6.EngineServices. Though both the assemblies had different public key token and different version, it always loads the one from vendor2. The reason is structuremap uses reflection to load the assemblies dynamically at runtime; it scans though current project's referenced assemblies and it's references and so forth. In that way assembly MetricsEngine.dll from vendor1 and vendor2 are considered by the structuremap, now it picks the latest version, in our case it picks 1.0.0.0. It doesn't care about assembly's identity (public key token).

Temporary Solution:

I tried, But I couldn't figure out the right solution. For time being after downloading the assembly I renamed the assembly manually and referencing it in my project. I uninstalled that package from NuGet. That is, I am not using NuGet for one of the referencing assembly. Once I figure out the solution I will update this post.

Tuesday, November 13, 2012

The Moore's law and the Core's question

Preface:

This article describes, what can be the next generation computer? Processor making companies like Intel keep reducing the chip size or they increase the efficiency in the same chip size in their every next release. The hardware improvement for every two years is an inevitable requirement. The software operating data size increases day by day, the gaming softwares require very good hardware acceleration. Now the chip companies couldn't reduce the chip size as they could before; they are shipping more than one processor in one suite; they call them as dual core, quad core and so on.

Moore’s Law:

The number of transistors on integrated circuits doubles approximately every two years. Wiki Link. Many have predicted that Moore's Law will soon reach its end.

The semiconductor is the problem:

There is a limit for reducing the size, since we know the processors are made up of silicon and germanium type semiconductors. They are solid, after certain level we can’t reduce their size. What could be the solution for next generation?

Solution:

As of now, there are two ways.
  1. The quantum chips.
  2. The bio chips.
The Bio chips can be made up of either DNA or RNA.

Quantum computer chips:

Rather than encoding ones and zeroes into high and low voltages that switch transistors on and off, the idea is to use the electron's spin. The Princeton and the Wisconsin university are the pioneers of this research. The electron spin has two directions; clockwise and anticlockwise. Scientists are making use of this spin and generating binary digits.

Earlier Version of the Theory:

The earlier version of this theory when I studied in 2004 uses a pair of electrons. In quantum mechanics two entangled particles cannot be viewed individually, even after they leave the interaction zone, where they became entangled. They act as a single quantum object. For example, there are two electrons e1 and e2. They can be used to express 4 different binary numbers.

Example:

To express decimal 14 in quantum computers we need two pair of electrons.That is from the above pictures,

Anticlockwise e1 + Anticlockwise e2 + Anticlockwise e3 + clockwise e4 = 14
Where as in conventional computer we need 4 transistors. That is,

Transistor t1 high voltage + t2 high voltage + t3 high voltage + t4 low voltage = 1110 = (decimal 14)

Transistors are not comparable with electrons in terms of speed and the space requirement.

The Modern Version:

The modern theory deals with electron’s superposition; hence by using single electron we can express 4 different binary numbers as follows.

Example:

In the modern version only two electrons are required to express decimal 14. From the above pictures,
Superposition state anticlockwise e1 + Superposition state clockwise e2 = 14

The conventional computer expresses in the unit of bit, in quantum computer it is qbit (quantum bit). In this case it requires 2 qbits.

Advantages of quantum computers:

  1. Size problem will go away, since electrons are super tiny. Also weightless.
  2. The speed, the current conventional PC’s are about 1-5 GHz speed, quantum computer’s speed will be at about 1-5 THz.
  3. It can be highly parallel computer, because of the electron’s superposition. Understanding electron’s superposition requires some effort, I am not covering here. For now, consider it is an electron's transitioning state

Challenges:

Computer’s speed cannot be improved only by improving processor. Other peripherals’ speed is also important. Scientists are working on them as well. Some researchers suggesting LASER for bus interface.

The DNA computers:

The idea is to use high and low concentrations of these molecules to propagate signals instead of high and low voltages that switch transistors on and off. It is medically proven that DNA can store biological information. Scientists are trying, if DNAs’ can be a better storage for computers? Can they be used for calculations?

The DNA (Deoxyribonucleic acid) contains nucleobases. The primary nucleobases are A, T, C and G. Adenine, thymine, cytosine and guanine are the expansion for them respectively. The DNA is a pair of strands. The strand is made up of strings A with T and C with G. Here is the basic concept for DNA computing.

In a conventional computer, in a bit you can store either 1 or 0. But in a DNA computer you can represent a bit by using these four variables. That is, it can be.

Example:

The same example to represent decimal 14 for DNA computers will be much more clear,
TAGC + TACG => 1110 => 14

Benefits of DNA computers

  1. One Kg of DNA can store the data from all the electronic computers ever built.
  2. DNA computer of half inch will be more powerful than supercomputers.
  3. In one cubic centimeter we can fit 10 trillion DNA molecules. With this size, a computer would be able to hold 10 TB of data, and perform 10 trillion calculations at a time.
  4. By adding more DNA, more calculations could be performed. Scalability! Also they can be highly parallel.
  5. DNA’s extracted from cellular organisms, there will always be a supply of DNA. So these computers will be cheap.

The RNA computers:

The RNA (ribonucleic acid) molecules are very similar to DNA molecules; the only difference is; RNA uses U (uracil) instead of T (thymine). Hence A, G, C and U are called RNA-bases. Everything above mentioned for DNA computers is also applicable for RNA computers.

What can cause an asp.net web service error?

Preface:

Last month I faced a problem in our production server that all the newly hosted websites threw javascript error. When I debugged further with firebug, I noticed that the web service calls were failing.

Reason:

Our website requires ABCpdf 8.1 but our server had version 7.0, that caused the error. Because in the latest release we upgraded ABCpdf to 8.1 in our development environment, but in the production environment.

Technical Details:

The error message was '/Site_URL/SampleWebService.asmx' has not been pre-compiled, and cannot be requested. I couldn't figure out the problem with the help of eventlog or application log. Google search also didn't help me. Finally I figured out that, the problem can occur when CLR tries to load any earlier revison of dll file, but the application was compiled with the latest version of dll. In this case the CLR failed to load ABCpdf 7.0.

Saturday, September 8, 2012

Structuremap scopes and life cycles with example

This article is a detailed version of Basic structuremap scopes. I am trying to keep this article to focus generic DI/IOC container and not just for structuremap. While using any DI/IOC container you must be careful on two things.

  1. Request context
  2. From which context you are requesting object from the structuremap. Basically there are two contexts in a web application you can make request from. The first one is HttpContext and the other is Thread (ThreadContext).

  3. Object's scope
  4. In general the scope defines lifetime of an object. To be accurately with reference to DI/IOC container it is not the lifetime, it is better to say the object's accessiblity. That is, the object created in one scope cannot be referred in another scope. Also the DI/IOC container itself will not dispose the object at the end of the scope. We should explicitly dispose them or GC may take care at later point. For further reading How to dispose objects created by structuremap.


Let's look at the structuremap life cycles. Download the project for this example. I am using windows authentication in this project. Give your machine credentials to login the application. This project UI will not display any result. I am using log4net for results. Results are stored at "_ApplicationLogs\general.txt".

In this example I am using 'RuntimeHelpers.GetHashCode' to get the object hash code for each object. Since we write results in log file for objects comparison, the object hash code for each object helps us to make sure whether they are same object or different object.

  1. Example - transient objects - a.k.a. non-singleton
    • Registry class
    • In registry class, if you don't mention the life cycle, by default the structuremap creates transient object. That is, new object for each structuremap request.
      Code:
      public class ApplicationRegistry : Registry
      {
          public ApplicationRegistry()
          {
              Scan(scanner => 
              { 
                  For<IVehicle>().Use<Car>();                
              });            
          }
      }
      
    • Consumer code
    • In the following code, we are requesting structuremap two times. It returns different object each time. Have a look at the log result
      Code:
      public partial class  _Default : System.Web.UI.Page
      {
          ILog logger = log4net.LogManager.GetLogger("GeneralLog");
          protected void Page_Load(object sender, EventArgs e)
          {
              IVehicle Car = ObjectFactory.GetInstance<IVehicle>();
              logger.Info("First Car :" + Car.GetVehicleID() + " Login user:" + User.Identity.Name);
      
              Car = ObjectFactory.GetInstance<IVehicle>();
              logger.Info("Second Car :" + Car.GetVehicleID() + " Login user:" + User.Identity.Name);
          }
      }
      
    • Log result (log4net log result)
    • 09/08/2012 20:54:08.816 [12] INFO  GeneralLog 
      Message: First Car :3473973 Login user:My-PC\Pandian
      Exception: 
      
      09/08/2012 20:54:08.840 [12] INFO  GeneralLog 
      Message: Second Car :27605492 Login user:My-PC\Pandian
      Exception:
      

  2. Explicit call - transient objects - way 1
  3. The following approach works exactly similar way as explained in example-1.
    • Registry class
    • Code:
      For<IVehicle>().Transient().Use<Car>();
      

  4. Explicit call - transient objects - way 2
  5. This approach too works exactly similar way as explained in example-1 and example-2. The word “request” in the below code doesn't mean HttpRequest. The structuremap returns transient object for each request arrived at it.
    • Registry class
    • Code:
      For<IVehicle>().LifecycleIs(new UniquePerRequestLifecycle()).Use<Car>();
      

  6. Singleton objects
  7. Have a look at the following code and the log, it is very clear that the structuremap creates singleton object across requests. The object hash code 14145203 is same for all the four requests.
    • Registry class
    • Code:
      For<IVehicle>().Singleton().Use<Car>();
      
      For this example I logged in from two different browsers with two different credentials.
    • Log result (log4net log result)
    09/08/2012 22:15:52.277 [5] INFO  GeneralLog 
    Message: First Car :14145203 Login user:My-PC\Pandian
    Exception: 
    
    09/08/2012 22:15:52.313 [5] INFO  GeneralLog 
    Message: Second Car :14145203 Login user:My-PC\Pandian
    Exception: 
    
    09/08/2012 22:16:01.072 [5] INFO  GeneralLog 
    Message: First Car :14145203 Login user:My-PC\TestUser
    Exception: 
    
    09/08/2012 22:16:01.073 [5] INFO  GeneralLog 
    Message: Second Car :14145203 Login user:My-PC\TestUser
    Exception: 
    

  8. Explicit call - Singleton objects
  9. This method also creates singleton object across requests as explained in example 4. The only difference is that you can also pass constructor argument.
    Code:
    For<IVehicle>().Use(new Car());
    

  10. Tricky, it creates singleton object
  11. When we mention the instance in "Use" function it creates singleton object as I said in the 5th example. The "Trainsient()" request is ignored here.
    Code:
    For<IVehicle>().Transient().Use(new Car());
    

  12. Transient objects with constructor arguments.
  13. As opposed to example 5, the following statement in registry creates transient object and it lets you to pass constructor argument. Note, you should modify Car class to accept constructor argument.
    Code:
    For<IVehicle>().Use(context => new Car());
    

  14. Singleton per HttpRequest
  15. The following statement in registry class creates singleton object per request.I am logging in from two different machines. If you look at the log, you can see that it uses only one object per request.
    Code:
    For<IVehicle>().LifecycleIs(new HttpContextLifecycle()).Use<Car>();
    
    In the below log, the first two and the second two results are same. That means it creates new object for every request.
    09/08/2012 22:31:59.870 [19] INFO  GeneralLog 
    Message: First Car :19320046 Login user:My-PC\Pandian
    Exception: 
    
    09/08/2012 22:31:59.888 [19] INFO  GeneralLog 
    Message: Second Car :19320046 Login user:My-PC\Pandian
    Exception: 
    
    09/08/2012 22:32:07.944 [19] INFO  GeneralLog 
    Message: First Car :57289035 Login user:My-PC\TestUser
    Exception: 
    
    09/08/2012 22:32:07.945 [19] INFO  GeneralLog 
    Message: Second Car :57289035 Login user:My-PC\TestUser
    Exception: 
    

  16. Singleton per HttpSession
  17. Very similar to example 8, but it creates singleton object per session.
    Code:
    For<IVehicle>().LifecycleIs(new HttpSessionLifecycle()).Use<Car>();
    

  18. Thread context
  19. The following statement in registry class creates singleton object per thread.
    Code:
    For<IVehicle>().LifecycleIs(new ThreadLocalStorageLifecycle()).Use<Car>();
    
    I have changed a bit in the application's consumer code. There are three threads here. One parent thread and the other two threads are created by me. So there are three threads and three distinct objects.
    Code:
    public partial class  _Default : System.Web.UI.Page
    {
        ILog logger = log4net.LogManager.GetLogger("GeneralLog");
        //CLR runs this method as part of parent thread's execution
        protected void Page_Load(object sender, EventArgs e)
        {
            IVehicle Car = ObjectFactory.GetInstance<IVehicle>();
            logger.Info("First Car :" + Car.GetVehicleID() + "  Main Thread id: " + Thread.CurrentThread.ManagedThreadId);
    
            Car = ObjectFactory.GetInstance<IVehicle>();
            logger.Info("Second Car :" + Car.GetVehicleID() + "  Main Thread id: " + Thread.CurrentThread.ManagedThreadId);
      
            Thread thread1 = new Thread(new ThreadStart(ThreadFunction));
            thread1.Start();
    
            Thread thread2 = new Thread(new ThreadStart(ThreadFunction));
            thread2.Start(); 
        }
        private void ThreadFunction()
        {
            IVehicle Car = ObjectFactory.GetInstance<IVehicle>();
            logger.Info("First Car :" + Car.GetVehicleID() + " Thread id: " + Thread.CurrentThread.ManagedThreadId);
    
            Car = ObjectFactory.GetInstance<IVehicle>();
            logger.Info("Second Car :" + Car.GetVehicleID() + " Thread id: " + Thread.CurrentThread.ManagedThreadId);
        }
    }
    
    In the following log, there are three threads 6, 7 and 11. The three objects created for each thread. This is singleton per thread.
    09/08/2012 22:53:41.562 [6] INFO  GeneralLog 
    Message: First Car :14509978 Main Thread id: 6
    Exception: 
    
    09/08/2012 22:53:41.815 [6] INFO  GeneralLog 
    Message: Second Car :14509978 Main Thread id: 6
    Exception: 
    
    09/08/2012 22:53:41.998 [7] INFO  GeneralLog 
    Message: First Car :15366892 Thread id: 7
    Exception: 
    
    09/08/2012 22:53:41.999 [7] INFO  GeneralLog 
    Message: Second Car :15366892 Thread id: 7
    Exception: 
    
    09/08/2012 22:53:42.000 [11] INFO  GeneralLog 
    Message: First Car :7995840 Thread id: 11
    Exception: 
    
    09/08/2012 22:53:42.047 [11] INFO  GeneralLog 
    Message: Second Car :7995840 Thread id: 11
    Exception: 
    

  20. Hybrid context
  21. I have a special requirement for this example. Considering the above example-10, I need the first object (which is created in the parent thread) should be HttpContext scoped. The other two objects created inside the thread should be ThreadLocal scoped. In hybrid context the structuremap should automatically identify the request scope and it should return the object for the same scope. Generally HttpContext supersedes Thread context. This requirement can be solved as follows.
    Code:
    For<IVehicle>().HybridHttpOrThreadLocalScoped().Use<Car>();
    

    Also it is worth mentioning that, if you look at the HttpContext inside the main thread, it is available; it is not null. But it is not available for child threads; HttpContext is null.

    You can't find any difference in the log result, but the objects created for HttpContext are cached. Objects created for thread local scope are not cached.

Friday, August 24, 2012

Ways to prevent connection/resource leaks - Part 2

You may use these techniques to handle any expensive resource leaks, not just for connection leaks. In Part 1, I am explaining how to fix resource leaks in simpler ways. In this article I am explaining how to fix resource leaks with structuremap and how the structuremap object creation machnism works in multithreaded environment. Structuremap scopes explained here. Also I am explaining evils of singleton object in a multi-threaded environment.

  1. Fix for heterogeneous application - 1

  2. a. If your application is partially/not dependent on ORM.
    b. If your application uses DI/IOC tools like structure map.
    c. If your application is single threaded.

    Solution


    The fact is that singleton objects created by structuremap for HttpContext scope are cached. To create singleton object use the following line of code in your structuremap registry.
    Code:
    For<SqlConnection>().HttpContextScoped().Use(new SqlConnection());
    
    Since it is cached, you can easily dispose it in the global.asax file's Application_EndRequest event by calling the following method.
    Code:
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
    

  3. Fix for heterogeneous application - 2

  4. a. If your application is partially/not dependent on ORM.
    b. If your application uses DI/IOC tools like structure map.
    c. If your application is multi-threaded, but uses limited number of threads.

    Solution


    The following line in structuremap registry creates object for both thread scope and http context scope.
    Code:
    For<SqlConnection>().HybridHttpOrThreadLocalScoped().Use(new SqlConnection());
    

    It requires two operations. One is thread scope cleanup and the other is HttpContext scope cleanup.

    In structuremap, thread scoped singleton objects are not cached. The above line of code creates one singleton object for each thread. The thread scoped singleton objects must be disposed at your own cost. That means you must explicitly dispose at the end of every thread in your application. Such as

    Code:
    ObjectFactory.GetInstance<SqlConnection>().Dispose();
    

    Now, the HttpContext scoped objects can be disposed by calling the following method in Application_EndRequest event.

    Code:
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
    

  5. Fix for heterogeneous application - 3

  6. a. If your application is partially/not dependent on ORM.
    b. If your application uses DI/IOC tools like structure map.
    c. If you are restoring HttpContext.Current within the thread. That is, within a thread you cannot access HttpContext variables, it will be null. But in some cases you may need HttpContext data within a thread and you pass HttpContext.Current as parameter to the thread. This way you restore the HttpContext within a thread. Such as
    Code:
    //Thread method, this method will be executed in parallel by more than 1 threads. ThreadParameters is a class created by me.
    private void BindDataThread(ThreadParameters parameter)
    {
     //I need to access data from HttpContext, restoring it.
     HttpContext.Current = parameter.CurrentHttpContext;
     var connection = ObjectFactory.GetInstance<SqlConnection>();
    }
    

    If you use the above line, it will create a singleton object for HttpContextScope and the same object will be served for various threads from structuremap. Since SqlConnection object is not thread safe it will throw random errors. That means, all threads will be using the same SqlConnection object, one thread will be in retrieving data from the database and the other will be in opening the connection, the third one will be in closing the connection by using the same connection object.

    So what happens to the thread local scope? That I mentioned “HybridHttpOrThreadLocalScoped” in the structuremap registry to create object for thread local scope. Well, in structuremap the HttpContext scope takes precedence by checking HttpContext.Current != null. As soon as you assign "HttpContext.Current = parameter.HttpContext", it will only create object for HttpContext scope within a thread; but it supposed to create object for thread local scope!!

    So what can be the solution?

    Code:
    //For().HybridHttpOrThreadLocalScoped().Use(new SqlConnection());
    For<IVehicle>().LifecycleIs(new ThreadLocalStorageLifecycle()).Use<Car>();
    

    You may try by using the second option (the uncommented) instead of the first option (the commented) as I mentioned above.

    How it will work?

    This creates a singleton object for each thread. That is, the structuremap creates objects per thread basis, no matter for which context the object is requested.

    On the other hand, it can be overhead. Objects created in the page handlers/controllers are run by main thread. We have to dispose them too.

    We can use HttpModules or Application_EndRequest to dispose objects created in main thread.

    Otherwise, if we have an option in DI/IOC container to specify to take ThreadLocalScope lifecyle as precedence, it can be bit more easier.

    Note: If you are using nested DataReader this approach will not work. See the code below

    Code:
    
    int departmentCode;
    //The following statement opens an SqlConnection and going to be active throughout the scope of "using" statement.
    using (SqlDataReader departmentReader = GetDepartmentReader()) 
    {
     while (departmentReader.Read())
     {
      departmentCode = Convert.ToInt32(departmentReader.GetValue(0));
      //The following line will try to use an another reader in the same thread, Since we made the SqlConnection as singlton per thread, this code will again open the same connection and will throw error.
      using (SqlDataReader employeeReader = GetEmployeeReader(departmentCode))
      {
       ...
       ...
      }
     }
    }
    

    All this approaches may raise following questions in your mind.

  7. Why can't you use transient objects?
  8. Transient objects are not cached anywhere in structuremap, you can’t reference back and dispose them.

  9. Why can’t you use nested containers?
  10. For the situations that we discussed so far, I feel the nested containers are overhead. I can simply use “using” statement instead. Both provides the similar solution.


Back to Part-1