Get the current version of the Assembly

The following code snippet return the Version number of currently executing assembly –

static string GetCurrentAssemblyVersionNumber() 
        { 
            Assembly currentAssembly = Assembly.GetExecutingAssembly(); 

            return currentAssembly.FullName.Split( new Char [] {','} )[1]; 
        }

Searching files in a Directory using .Net Framework

.Net framework’s Directory class of system.io namespace provides a static method GetFiles to search the files of a particular directory. Here is the static method detail

Get Files api of directory class 

Using the code snippet we can find all the files of the directory specified in path

string[] paths = Directory.GetFiles(path, stringsearchPattern, SearchOption.AllDirectories);

Here depending on the stringsearchPattern , directory mentioned in path and it sub-directories will be searched and depending on the result , one array of string containing the file paths will be returned. About searchPattern, it could contain any string. But the allowed wildcard characters are – *(zero/more character) and ?(exactly zero or more character).

For example –

1. “*.txt” returns files having .txt extension.
2. “*.?xt” returns files having extension .xt , .axt , .bxt and so on.

Be careful about one anomaly in searchPattern, if you write “*.txt” as search pattern , it gonna consider it like “*.txt*” – that is let’s consider following folders-  fileswithtxtextensions.jpg

If we search using “*.txt” – it gonna match with every one of them. We will get same kind of result for “*htm” search pattern– which will match files with extensions- *htm and *html. I don’t know the exact reason behind it and I will update about it if I get to know that.

In addition, searchPattern in GetFiles() does not support multiple filters which we may require if we want our GetFiles() functions to return ,let’s say, all the “*txt” and “.htm” files. Iteratively searching individual files could be one easy way to solve  this problem.

For more information – visit http://msdn2.microsoft.com/en-us/library/ms143316.aspx .

TestContext – more on mstest

If we are in test driven development, we need to spend significant amount of time in writing unit tests. In VSTS unit testing framework, every test run create a unique folder in our machine and generate a test report ( *.trx format) for every test run-

testresult.jpg

Sometimes it’s needed to access the folder that current test run created. UnitTestAdapterContext class provides a set of properties related to current test run that can be accessed from inside unit tests.

To use the properties provided in UnitTestAdapterContext we need add the following properties in our Test Class –

private TestContext testContextInstance;

///
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///
public TestContext TestContext {
 get
 {
 return testContextInstance;
 }
 set
 {
 testContextInstance = value;
 }
}

The property is automatically provided with a concrete instance of the TestContext type [1]. In essence, it implies that we do not need to instantiate or derive TestContext in our test class.

Take a look at the properties and functionalities offered by TestContext –

testconttextcd.jpg

 If I start debugging a unit test adding a break point and watch the TestContext, we can view different information about and functionality for current test run –   

unittestadaptercontext.jpg  

So, Current TestRun Directory can be accessed by just one line of code- 

 string testDirectory = TestContext.TestDir; 

Therefore , we can use class in our TestContext Unit Tests to get different informations about the current test run and we can use different functioanallity of this class – for example – BeginTimer() and EndTimer() would be verify useful to measure our application’s differenent module’s performance to validate certain non-functional requirements.

More details on TestContext is available here.

References
[1] http://msdn.microsoft.com/en-us/library/ms404699

Designing Efficient Immutable .Net Objects

What is an immutable object?

By definition immutable object is the object whose state can not be changed after it is created. That means, after creating the object, its publicly exposed members can not be changed from their initial assigned values. On the contrary, mutable objects are objects whose state can be changed at any point of time.

Every developer has to take a important decision whether to make a class mutable or immutable while designing the domain model.
While taking this decision, careful considerations can make us avoid the potential pitfall of using immutable object. 
 Why & How using immutable .Net object – is our today’s discussion. Let’s begin with How part . 

How to implement .Net Immutable Object?

 The way I would implement an immutable .Net class –           

          Make the fields private readonly.
          Provide a Public property with get accessor.
          If the class is no longer needed to inherited – making it sealed. 

Like in the following example, I am implementing an immutable class  UserContact which will be inherited in User  

classdiagram1.jpg

 Here is the Implementation of the Immutable classes –     

    public class UserContact

    {

        private readonly string _Name;

        public string Name   

        {

            get { return _Name; }

        }

        private readonly string _EmailAddress;

        public string EmailAddress

        {

            get { return _EmailAddress; }

        }

        public UserContact( string name , string emailAddress)

        {

            _EmailAddress = emailAddress;

            _Name = name;

        }

    }

UserContact get inherited by User as follows [Since User class is no longer inherited – we make it sealed] –

    public sealed class User : UserContact

    {

        private readonly string _UserName;

        public string UserName

        {

            get { return _UserName; }

        }

        public User(string name, string email, string userName)

            : base(name, email) { }

    }


So, isn’t it really easy to implement a Truly Immutable class in .Net framework? J Now the question pops into our mind – why we will be using immutable .net objects , what would be benefits of that ? Let’s explore that –  

Why use immutable object?

 Protection:

From the definition we know, Immutable objects can not be changed after its being initialized. So, while using inside application, immutable object can flow in different layers of the application without getting worried about being altered by different layers.  

Performance:

Copying object will be much easier, we just need to copy the reference instead of copying the whole object. It would be much faster to copy reference than the whole object.

User user = new User(“adil”, “adil.bd@hotmail.com”, “adak”);
User userTemp = user; 

In case of mutable object, we would need to create defensive copy of the object and in .Net term, we need to create a Deep Copy of object otherwise, changing a property in the actual mutable object would reflect everywhere where the object is referenced. For example, let’s consider User as mutable; then changing any thing in user object will have same impact on userTemp as well which is not intended.

To avoid this situation, in case of mutable object, we need to make a Deep Copy of the object which is a costly operation. However, for immutable object, copying the reference would be enough since its state can’t be changed. 

Scalability:

Thread synchronization is an issue of concern while designing multithreaded application. Overhead of synchronizing immutable object is far less than mutable object. By default , an individual immutable object does not need to be synchronized as its state will be not be modified by any thread. However, since the immutable object will still be accessed thorough reference , it would require some synchronization. In complex sync scenarios, immutable object would perform far better then mutable version.   

Consistency: 

If we consider inheritance hierarchy, immutability provides a way for the sub-class to maintain consistency in inheritance hierarchy. Consider following mutable objects–

 classdiagram2.jpg

When we instantiate the StudentMutable object, the AccountType is automatically set to Student Account –

public StudentMutable(string name , string email , string userName )
: base(name ,email , userName,“Student Account”){}

 Now, we can write following lines by which the AccountType property could be anything other than “Student Account” which is completely inconsistent –   

StudentMutable mutable = new StudentMutable(“Adil”, “Adil.bd@hotmai.com”, “adil”);   
mutable.AccountType = “whatever account”;   

But if we use Immutable object in inheritance – the object hierarchy will always be consistent.:) 

What to consider while designing Immutable objects?

Intantiation of immutable object might be considered an operation that will be done more frequently. Then the allocation and freeing the resource for the immutable object would be the most recurrent opertaion which might result as performace overhead. Incase of regular objects , it seems that syncronization is far more costly operation from CPU perspective than allocating and freeing resource.  

For objects that require significant time to initialize , we may consider to implement Object Pool or Flyweight pattern to enhance reusability.  

Conclusion

 So , We can achive much faster and efficient code if we use Immutable object. But by saying all this , definitly we need to design accordingly and carefully so that immutable object can perform to its best. In this article , we learn how to implement immutable object in .Net and what’s its benefits and what we need to consider while implementing immutable object. In my next post , I am thinking to write something about reusing the immutable object to enhance efficiency. Thanks for visiting the the blog. Let me know your comments and feedbacks. Bye J