Tuesday, March 3, 2015

Is my code running inside virtual machine?

This is a small tip which rarely, we as programmers need to apply. Its about how to determine whether our code is running inside a virtual machine or not.Actually it doesn't matter if we are writing business applications. But in some cases especially when we are dealing with hardware devices we may need to disable some features by checking whether the code is under virtual machine. Also this is not a first thing any programmer is looking for. So I am aggregating links as well.

Native C++

Hope everyone will be aware of this as people who are in unmanaged world are talking directly to the computer.

.Net (C# or VB.Net)

In .Net the easiest way if to query the WMI objects. We can get easily get example code snippets from internet. Some are below.

http://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine

SQL

Query the DMV sys.dm_os_sys_info as follows

SELECT virtual_machine_type,virtual_machine_type_desc 
FROM sys.dm_os_sys_info

The sys.dm_os_sys_info gives much more information about the host system such as last SQL Server restart time, memory information etc...

There are different virtualization softwares available to create virtual machines. The method to determine that detail may vary from type to type. Need to invest some time to determine that.

Tuesday, February 24, 2015

Group by test class name in VS2012 Test Explorer

Background

Writing unit test case is always a good practice in programming. It gives confidence to re-factor code and make sure each and every piece is working properly. If individual pieces are working good mostly the application will work after integration.

Basics of Visual studio unit test framework

Visual Studio has out of the box unit testing framework. We can create test classes and those classes can contain test methods. Normally if we follow proper naming convention to relate production code with test projects, it is easy to see how the tests are performing. One of the naming convention for unit test class and methods names can be as follows
  • Let the test project name be same as production project but suffix the test project with .Tests
  • For each production code method, create a unit test class.
  • Each scenario in the production method can be one test method in test class.
  • Test class name can be <Scenario>_<Production Method Name>{}
  • Method name can be <Test case specification>_<Expected behavior>()
eg: Production code

    public static class ObjectFactory
    {
        public static object CreateObject(string fullyQualifiedClassAndAssemblyName, object[] constructorParameters)
        {
//Production code which uses reflection to create object.
        }
    }

Unit test class

[TestClassExcludeFromCodeCoverage]
public class ObjectFactory_CreateObject
{
        [TestMethodTimeout(1000)]
        public void WhenFullyQualifiedClassAndAssemblyNamePassedAndClassIsInternal_ShouldSucceed()
        {
//Test code
        }
        [TestMethod,ExpectedException(typeof(FileNotFoundException))]
        public void WhenFullyQualifiedClassAndNonExistingAssemblyNamePassed_ThrowFileNotFoundException()
        {
//Test code
        }
}

The main benefit of this naming convention is, it does not need any additional documentation to describe the what the test does. When we avoid one more item from maintenance, we are increasing productivity.

Running test cases from visual studio

We can easily trigger the unit test execution and see the results in "Test Results" window in VS 2010. The results will be shown with test name by default. The same functionality is there in VS2012 as well, but the window name is changed from "Test Results" to "Test explorer".

Problem

When the project grows, there are high chance that programmers forget to write test cases. Or even if there is strict enforcement, they will tend to write one test method like below for each and every production method.

[TestClass]
public class EmailSender_Send
{
        [TestMethod]
        public void WithProperparameter_ShouldSucceed()
        {
//Test code
        }
}
[TestClass]
public class Scheduler_CreateSchedule
{
        [TestMethod(), Timeout(30000)]
        public void WithProperParameters_ShouldSuccessed()
        {
//Test code
        }
}

Normally the test results will be displayed only with the test name and the test name is the test method name. That ends up in the test result window with all tests with same name. Its very difficult to understand from the review perspective.

If we want to see the test class name we can group by the test class name as below. This works well in VS2010.
[Photo taken from http://www.ladislavmrnka.com/wp-content/uploads/2012/09/TestView.png]

The same functionality in VS2012 named Test Explorer doesn't have Group by Class name in its earlier production releases. The group by popup is shown as below when try to group by class name.
This is really useless for somebody who want to see the test results. There is no idea why Microsoft removed a useful feature from earlier version in new release. But fortunately its back in later VS2012 updates. When this post is written, the latest update was Update 4.

Happy coding. Yes unit testing is part of coding:)

Tuesday, February 17, 2015

Standalone tools for production debugging

Below are some tools which are standalone and can help in production debugging. Don't confuse this works if we as developers have access to production servers and able to run standalone tools but don't have rights to install applications.

If we have rights to install applications in production server, we can use better tools than these such as Visual studio
  • .Net tools
    • Perfview - to catch exceptions
      • This is useful if we suspect that there are some exceptions eaten in the application and those are causing some other side effects.
  • Database
This is list is growing list. Hopefully I can add more later.


Tuesday, February 10, 2015

WCF DataServices - Date Time comparison in OData query

The concept of WCF data service which uses OData is really great. But I doubt whether that is ready to be used in an enterprise production applications. The main reason is its immaturity and lack of support on some Linq queries and operators. One of the major item is lack of joins. I believe OData specification itself doesn't have join. Below is another scenario which is not supported by WCF Data Services.

Requirement - Compare date in database against current date

Lets take and scenario where a MessageProcessAttempt table is exposed via WCF Data service. There is a field called DequeuedTime which tells when a message is dequeued. We need to list down all the messages which dequeued in last 1 hour.

In normal sense we can obtain the list by subtracting the de-queued time from current time and checking if the difference < 1 hour. The query can be as follows.

List<MessageProcessingAttempt> msgs = (from msg
                           in qProxy.MessageProcessingAttempts
                           where (DateTime.UtcNow- msg.DequeuedTime.Value).TotalHours<1
                           select msg).ToList();

But it will fail with below error message
"No property 'TotalHours' exists in type 'Edm.DateTime' at position 56."
Position will change based on the code.There will be no compile time errors. It just fails at runtime. Tried to find the details about Edm.DateTime class in msdn but able to find out except one EdmDateTimeConstant class.So what can we do

Solution - Calculate target date and compare

Find the target date and do comparison rather than finding the difference in the OData query.


DateTime timeToFilter = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
List<MessageProcessingAttempt> msgs = (from msg
                           in qProxy.MessageProcessingAttempts
                           where msg.DequeuedTime.Value >= timeToFilter
                           select msg).ToList();

Here the major difference we can notice that the date subtraction is not happening via operator and its not producing the TimeSpan obejct. We can have DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)) in OData as well instead of variable and it will work. This points to the fact that TotalHours property is not there in a special type called Edm.TotalHours which is produced as part of subtraction operator.

This was found by our development team in India and I didn't agree to them in the beginning. I spend around 2-3 hours and could see WCF Data Service is still not suitable for enterprise apps. Thanks to the team for finding the workaround.

Happy coding...

Tuesday, February 3, 2015

Dynamic SQL View using CONTEX_INFO

SQL Server supports creating views and I hope all knows what is a view. According to wiki its just a result set of query on data. Users can access it just like another table but it doesn't contain its own data like table. If we google for different between view and table we can get ton of links.

Below is a normal view definition.

CREATE VIEW CreditCards 
AS 
  (SELECT * 
   FROM   adventureworks2012.sales.creditcard 
   WHERE  cardtype = 'Vista')

In our day to day life most of the views we are creating has a static 'where' clause. Here we are
going to see how that part can be dynamic.

Create view by getting values from CONTEXT_INFO

CONTEXT_INFO gives us option to store values in the context of a session. It can be more compared to a static variable in programming. Here we are going to see how a view can be created which is affected by CONTEXT_INFO value.

Below is a sample view which is consuming the CONTEXT_INFO

CREATE VIEW creditcards 
AS 
  (SELECT * 
   FROM   adventureworks2012.sales.creditcard 
   WHERE  CardType = CONVERT(VARCHAR(25), Context_info())) 

If somebody call this view without setting the CONTEXT_INFO it will return the view which matches the where condition(CardType) with NULL. Else it returns proper data set.

Setting the CONTEXT_INFO

If we have already a view defined we can set the CONTEXT_INFO to our own values and select the view. The view will return proper values.

DECLARE @contextInfo VARBINARY(128) 

SET @contextInfo = CONVERT(VARBINARY(128), 'Vista') 
SET context_info @contextInfo 

SELECT * 
FROM   adventureworks2012.dbo.creditcards

The above query will return all the Sales.CreditCard with CardType='Vista'

One advantage is we can set this CONTEXT_INFO from code. More precisely from central data access before executing any other query. This way we can control centrally, what the tracks are getting from this view if they go via common data access.

http://jasondentler.com/blog/2010/01/exploiting-context_info-for-fun-and-audit/

Tuesday, January 20, 2015

Debugging exception in WCF IsOneWay=True WCF Services

Recently I had to work on an one way WCF service. The scenario is little different than normal service hosting. There are many services hosted in a server machine using IIS WAS hosting.All of those expose same contact interface. The URLs are obviously different but they follow certain convention such as

net.pipe://localhost/{feature name}/service.svc

The caller has some logic to prepare the above url and it simply calls the service. It uses fire and forget method by decorating contract with IsOneway=True. Below is a similar contract.


[OperationContract(IsOneWay = true)]
void InvokeAsync(Dictionary<stringobject> messageInfoDictionary);

After setting up the environment, we started facing one issue. The service implementation is not getting executed. But there is no exception in caller side. In a normal scenario we immediately go to the svclog file, if there is an exception. As there was no exception, the investigation didn't turn into svclogs in the first round.

Analyzed each and every bit of caller code where the url is prepared. No problem at all. Checked the contract methods again and again for any mismatch. Its all perfect. Finally decided to turn on the svclogs in caller side on the assumption that client is not able to establish communication with server.

It shows that there is timeout. But it didn't help to identify the root cause. Then enabled server side svclogs and it helped.

The exception was System.ServiceModel.Dispatcher.NetDispatcherFaultException .It has an inner exception as well which is of type System.Runtime.Serialization.SerializationException. The error message was

"Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value' contains data from a type that maps to the name 
'http://schemas.datacontract.org/2004/07/{Namespace}:Message'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'Message' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer."

Yes its clear the data contract class is in different assembly and that assembly is not available in the bin folder of service. Putting the dll in place fixed the issue.

I am more researching on how these kind of issues can be caught in our code and log properly. This is important as the services which are exposing the same contract are going to be developed by different  and disconnected teams.

Tuesday, January 13, 2015

Can my business object / entity / model class contain Save()?

This is a very old question. Lets try to answer it with the mind of a passionate programmer who wants his code to be the best quality code. Here we will be examining different possibilities and understand why some techniques are not recommended.

What if the Save() is part of my entity class?

Lets think in the way that, the Save() is part of the business object. What are the pros and cons

Pros

  1. Data and the functions manipulating it are in single unit and its encapsulated.

Cons

  1. If we want to change the data persistence mechanism from SQL Server database to XML, we want to modify all the entity classes.
  2. Violation of SRP - The class will change for 2 reasons. If a new property added or persistence mechanism changed.

What if the Save() is moved to Repository class

Here the Save() will be part of another class. Lets call that class as Repository. Pros and cons below

Pros

  1. Underlying storage mechanism can change without a change in the entity class.

Cons

  1. Repository might need separate methods to save different entities such as SaveEmployee() SaveOrder() etc...Otherwise one method which accepts base class of entity classes and use reflection to identity the properties to be saved. Need to keep track of what property maps to what field in database or node in xml.
  2. The consumer of the entity classes needs to remember one more class name to work with entities. API cannot be explored by developers. Need documentation.

What if the Save() is available in entity and repository and they are loosely connected?


In this technique, Save() will be available in entity class as well as repository class. The difference here is, the entity class method body will not contain any logic to persist the data. It just pass the execution to the repository. The repository knows how to persist. Some code snippet below

Core classes

public abstract class EntityBase
    {
        public abstract void Save();
    }
    interface IRepository
    {
        void Save(EntityBase entity);
    }
    static class RepositoryFactory
    {
        public static IRepository Get()
        {
            IRepository repository=default(IRepository);
            //Logic to decide repository based on config or any other criteria.
            return repository;
        }
    }

Below are the application specific classes.

    public class Account:EntityBase
    {
        public string Name { getset; }
        public decimal balance { getset; }
        public override void Save()
        {
            RepositoryFactory.Get().Save(this);
        }   
    }
 
    class SqlServerRepository:IRepository
    {
        void IRepository.Save(EntityBase entity)
        {
            //Use reflection to get the properties to be saved.
            //Or need to have separate methods like SaveAccount(), SaveCustomer() in the repository.
        }
    }
    //The UI parts. It can be the controller in case of MVC.
    class AccountViewmodel
    {
        Account acc = new Account() { Name = "Sales", Balance = 30000 };
        void SaveCommand()
        {
            acc.Save();
        }
    }

I know this is not a production ready code. But this gives idea how the Save() method can be written by honoring the SRP and keeping the easiness of API usage.