[Dev Tip] Tạo máy ảo từ máy ảo khác trên VMWare

Đôi khi có những trường hợp bạn muốn setup hệ thống để test một function hay solution gì đó. Và bạn quyết định dùng các máy ảo để triển khai và dùng VMWare. Vấn đề là chuẩn bị các máy ảo.

1) Cài mới tất cả các máy? Đôi khi nếu yêu cầu là các hệ điều hành giống nhau thì việc này là công việc trâu bò và tốt nhiều thời gian để ngồi cài từng máy một.

2) Vậy sao không cài một máy cơ sở rồi copy nó ra thành nhiều máy khác – dạng như copy/paste một file ra nhiều phiên bản. Cũng hay, nhưng có vẻ cơ bắp quá, và đôi khi bạn gặp hạn chế về dung lượng ổ cứng.

3) Có một cách hay hơn cách 2 – cũng clone nhưng ít tốn dung lượng bộ nhớ – linked clone.

Step 1) Cài một máy cơ sở – chứa tất cả các thành phần cần thiết của tất cả các máy.

Step 2) Tạo một snapshot cho nó

snapshotXong, tới đây mình đã hoàn tất các bước chuẩn bị.

Step 3) Tạo một máy mới dựa trên máy cơ sở đã tạo

Step 3.1) Chọn snapshot trên máy cơ sở > Clone

Step 3.2) Clone dạng linked

linked[Note] các thao tác không được nhắc đến là những thao tác cơ bản như chọn nơi lưu trữ, tên máy ảo mới,.. bạn tự làm. 🙂

Đến đây mình đã tạo được một máy ảo mới dạng linked tới máy ảo cơ sở. Mọi thay đổi trên máy ảo mới không có tác động gì đến máy ảo cơ sở. Xóa máy ảo cơ sở thì xem như những máy ảo kế thừa cũng không chạy được.

[Dev Tip] Compare two objects

Sometime, you need to compare objects. Beside of override the Equal(), GetHashCode() methods, which are for some domain rules.

If you must compare all properties of the object, then I suggest another way to get it done: using JSON.

You can serialize those objects and compare JSON results.


public static void AreEqualByJson(object expected, object actual, string message = "")
{
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
};

var expectedJson = JsonConvert.SerializeObject(expected, settings);
var actualJson = JsonConvert.SerializeObject(actual, settings);
Assert.AreEqual(expectedJson, actualJson, message);
}

[Dev Tip] The GetHashCode() and Equals() in the implemented IEqualityComparer interface

When you compare two objects using an EqualityComparer then the IEqualityComparer.Equals and IEqualityComparer.GetHashCode methods are used instead of the methods on the Key objects.

# Recall

Every object in .NET has an Equals method and a GetHashCode method.

The Equals method is used to compare one object with another object – to see if the two objects are equivalent.

The GetHashCode method generates a 32-bit integer representation of the object. Since there is no limit to how much information an object can contain, certain hash codes are shared by multiple objects – so the hash code is not necessarily unique.

A dictionary is a really cool data structure that trades a higher memory footprint in return for (more or less) constant costs for Add/Remove/Get operations. It is a poor choice for iterating over though. Internally, a dictionary contains an array of buckets, where values can be stored. When you add a Key and Value to a dictionary, the GetHashCode method is called on the Key. The hashcode returned is used to determine the index of the bucket in which the Key/Value pair should be stored.

When you want to access the Value, you pass in the Key again. The GetHashCode method is called on the Key, and the bucket containing the Value is located.

# Example

BoxEqualityComparer boxEqC = new BoxEqualityComparer(); 

Dictionary<Box, String> boxes = new Dictionary<Box, string>(boxEqC); 

Box redBox = new Box(100, 100, 25);
Box blueBox = new Box(1000, 1000, 25);

boxes.Add(redBox, "red"); 
boxes.Add(blueBox, "blue"); 

[Dev Tip] Burrow.Net – web pages

I have to note some pages which has talked about the Burrow.net and RabbitMQ. I will play with them later.

http://thoai-nguyen.blogspot.com/2012/05/messaging-rabbitmq-and-burrownet.html

http://thoai-nguyen.blogspot.com/2012/06/custom-burrownet-tunnelfactory-rabbitmq.html

http://thoai-nguyen.blogspot.com/2012/06/things-you-can-change-in-burrownet.html

http://thoai-nguyen.blogspot.com/2012/06/programmatically-rabbitmq-exchange.html

http://thoai-nguyen.blogspot.com/2014/06/using-rabbitmq-header-exchange-with.html

http://thoai-nguyen.blogspot.com/2013/07/monitor-rabbitmq-queues-count-message.html

http://thoai-nguyen.blogspot.com/2012/10/rpc-with-burrownet-and-rabbitmq.html

And: https://github.com/vanthoainguyen/Burrow.NET

[Dev Tip] Another way to apply Unit of Work

NOTE: I get it from another blog. I think his idea is suit for some cases.

I bet you must have heard about Unit Of Work. If you have not, you can find the discription here : http://martinfowler.com/eaaCatalog/unitOfWork.html.    You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you’ve read so you can avoid inconsistent reads.     Nowadays, DDD is one of the most famous design methodologies in the developer community. Even though 95% of all software applications fall into the “not so good for using DDD” categories, some practices and ideas of DDD can be used in many .NET projects, especially Repository and Domain Service. I have seen many implementations of Repository pattern and UnitOfWork, but i am not so happy with any because of the following reason. We tend to use some kinds of ORM like NHibernate or EF as the technology behind Repository implementation. These frameworks mostly have the Unit Of Work built in, so I think the Domain Service layer should not call IUnitOfWork.CommitChange() when it needs to persist something to the repository. In some complex services, we call a service method which may execute different service methods; and because a service method (that requires changing the database) should call IUnitOfWork.CommitChanges. Therefore, as a result, IUnitOfWork.CommitChanges will be called many times in 1 business transaction.     Another example could be the controller which can use several domain services to execute an action method. Let’s say a website user wants to register at your website. When he submits the registration form, the RegisterController will call the UserService to create a user to the repository and another service create a WelcomeEmail in the Email repository. That means there are 2 records are got involed in this transaction (assume that you use SQL as the data source). And a proper UnitOfWork implementation should be called only 1 time to finish the saving task. However, it’s easy to see the implementation like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
[HttpPost]
public ActionResult Register(RegisterUserViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return View(viewModel)
    }
    
    UserService.Create(user);
    EmailService.Create(welcomeEmail);
    
    return RedirectToAction("Index", "Home");
}

In the user service implementation :

1
2
3
4
5
public void Create(User contact)
{   
    _userRepository.Add(contact);
    _unitOfWork.CommitChange();
}

And in the email service implementation :

1
2
3
4
5
public void Create(Email email)
{   
    _emailRepository.Add(email);
    _unitOfWork.CommitChange();
}

It’s not difficult to see that the UnitOfWork will call method CommitChange() two times. If you use EF behind the Repository implementation, I’m sure the code above will make your breakpoint stop at method ObjectContext.SaveChanges() 2 times. For me it’s not “Unit Of Work” if we do like that. It would be nice if we could have a way to call the CommitChange() only when we actually need, it could be the end of every http request. Therefore, the domain services should never call CommitChange() on your UnitOfWork.     Base on this idea which is a bit similar to “Open Session In View” pattern, I created a basic implementation of UnitOfWork below:

1
2
3
4
5
public interface IUnitOfWork
{
    void CommitChange();
    bool IsDirty { get; set; }
}

The domain service will use a UnitOfWorkScope to ensure the change will be committed in the end or immediately based on the UnitOfWorkScopeOption:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public enum UnitOfWorkScopeOption
{
    Shared,
    CommitImmediately
}
public class UnitOfWorkScope : Disposable
{
    private readonly UnitOfWorkScopeOption _option;
    private readonly IUnitOfWork _unitOfWork;
    public UnitOfWorkScope() : this(UnitOfWorkScopeOption.Shared)
    {
    }
    public UnitOfWorkScope(UnitOfWorkScopeOption option)
    {
        _option = option;
        _unitOfWork = ObjectFactory.GetInstance<IUnitOfWork>(); // I'm using StructureMap
    }
    protected override void DisposeCore()
    {
        switch(_option)
        {
            case UnitOfWorkScopeOption.CommitImmediately:
                {
                    _unitOfWork.CommitChange();
                    _unitOfWork.IsDirty = false;
                    break;
                }
            default:
                _unitOfWork.IsDirty = true;
                break;
        }
    }
}

I will change the service methods like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void Create(User contact)
{   
    using (new UnitOfWorkScope())
    {
        _userRepository.Add(contact);   
    }
}
public void Create(Email email)
{   
    using (new UnitOfWorkScope())
    {
        _emailRepository.Add(email);
    }
}

The default constructor of UnitOfWorkScope would set the scope option to Shared. That means it would do nothing but mark the UnitOfWork.IsDirty to true. In the end, we can base on that value to determine whether we should call commit change. I put this logic in the base controller, so after the ActionExecuted, the UnitOfWork will be invoked to do the saving job.

1
2
3
4
5
6
7
8
9
10
11
12
13
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    base.OnActionExecuted(filterContext);
    if (filterContext.Exception == null || filterContext.ExceptionHandled)
    {
        var unitOfWork = ObjectFactory.GetInstance<IUnitOfWork>();
        if (unitOfWork != null && unitOfWork.IsDirty)
        {
            unitOfWork.CommitChange();
        }
    }   
}

I made a test project and looks like it run at least 2 times faster than the the original way when I use UnitOfWorkScope. There is a very cool implementation of UnitOfWork at NCommon. You should check it out. Finally, here is the test project. Cheers

REF: http://thoai-nguyen.blogspot.com/2011/06/basic-unit-of-work-implementation.html

[Dev Tip] Auto compile typescript using grunt

1) Install grunt-cli

npm install grunt-cli -g

2) Move to your project folder (you can install grunt, typescript,.. in any folder which you want)
– install grund

npm install grunt --save-dev

– install typescript

npm install typescript --save-dev

– install grunt-typescript

npm install grunt-typescript --save-dev

– install grunt-contrib-watch

npm install grunt-contrib-watch --save-dev

– setup grunt by create Gruntfile.js.
For example:

module.exports = function (grunt) {

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
typescript: {
base: {
src: '*.ts',
dest: 'myjs.js',
options: {
module: 'amd',
target: 'es5'
}
}
},
watch: {
files: '*.ts',
tasks: ['typescript']
},
});

grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-contrib-watch');

grunt.registerTask('default', ['watch']);
};

– run grunt

grunt

– change your ts file and save it, you will automatically get js result.

You will get something like that

gruntNote: there is a nice command:

npm install