Thứ Năm, 12 tháng 1, 2012

Query in nHibernate

Today was the first day of my NHibernate course, and I think that it might be good to point out a few of the samples that we worked with. Those are pretty basic NHibernate queries, but they are probably going to be useful for beginners.

Let us take my usual Blog model, and see what kind of queries (and results) we can come up with:

image

Let us find a blog by its identifier:

var blog = s.Get(1);

Which results in:

image

We can also try:

var blog = s.Load(1);

Which would result in… absolutely no SQL queries. You can look at a more deep discussion of that here.

Now, let us try to search by a property:

var blogs = s.CreateCriteria()
.Add(Restrictions.Eq("Title", "Ayende @ Rahien"))
.List();

Which results in:

image

If we try to make the same with HQL, it would look:

var blogs = s.CreateQuery("from Blog b where b.Title = :title")
.SetParameter("title","Ayende @ Rahien")
.List();

Which results in slight different SQL than using the criteria:

image

What about trying a more complex conditional? Let us try to see comparing two properties:

var blogs = s.CreateCriteria()
.Add(Restrictions.Eq("Title","Ayende @ Rahien"))
.Add(Restrictions.Eq("Subtitle", "Send me a patch for that"))
.List();

Which results in:

image

Let us do that again, but using two properties using an OR:

var blogs = s.CreateCriteria()
.Add(Restrictions.Disjunction()
.Add(Restrictions.Eq("Title", "Ayende @ Rahien"))
.Add(Restrictions.Eq("Subtitle", "Send me a patch for that")))
.List();

Which would result in:

image

We can also execute the same SQL using the following syntax:

var blogs = s.CreateCriteria()
.Add(
Restrictions.Eq("Title", "Ayende @ Rahien") ||
Restrictions.Eq("Subtitle", "Send me a patch for that")
)
.List();

Doing the same using HQL would be:

var blogs = s.CreateQuery("from Blog b where b.Title = :title and b.Subtitle = :subtitle")
.SetParameter("title","Ayende @ Rahien")
.SetParameter("subtitle", "Send me a patch for that")
.List();

Which results in:

image

And changing that to an OR is pretty self explanatory :-)

var blogs = s.CreateQuery("from Blog b where b.Title = :title or b.Subtitle = :subtitle")
.SetParameter("title","Ayende @ Rahien")
.SetParameter("subtitle", "Send me a patch for that")
.List();

Giving us:

image

Let us try something a bit more complex, finding a blog by a post title:

var blogs = s.CreateCriteria()
.CreateCriteria("Posts")
.Add(Restrictions.Eq("Title","NHibernate Rocks"))
.List();

That gives us:

image

You will note that we force a load of the Posts collection. We can try something else, though:

var blogs = s.CreateCriteria()
.Add(Subqueries.PropertyIn("id",
DetachedCriteria.For()
.Add(Restrictions.Eq("Title","NHibernate Rocks"))
.SetProjection(Projections.Property("Blog.id"))
))
.List();

Which would give us the same result, but without loading the Posts collection:

image

This is a pretty common example of changing the way that we compute complex conditionals when we want to avoid wide result sets.

Let us do the same with HQL:

var blogs = s.CreateQuery("from Blog b join b.Posts p where p.Title = :title")
.SetParameter("title", "NHibernate Rocks")
.List();

Which would result:

image

We have the same issue as with the first Criteria API, and we can resolve it in the same way:

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.Title = :title)")
.SetParameter("title", "NHibernate Rocks")
.List();

And the same result as in the Criteria API show us:

image

And the final test, let us try to find a blog that has a post posted by a specific user:

var blogs = s.CreateCriteria()
.Add(Subqueries.PropertyIn("id",
DetachedCriteria.For()
.SetProjection(Projections.Property("Blog.id"))
.CreateCriteria("User")
.Add(Restrictions.Eq("Username","Ayende"))
))
.List();

And this give us:

image

The same thing with HQL will give us:

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.User.Username = :user)")
.SetParameter("user","Ayende")
.List();

And that results:

image

Thứ Tư, 11 tháng 1, 2012

Hightlight row in GridView

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("style", "background-color: #FFFFFF; color: black;");
e.Row.Attributes.Add("onmouseover", "style.backgroundColor='#FF6600'");
e.Row.Attributes.Add("onmouseout", "style.backgroundColor='#FFFFFF'");
}
}
catch { }
}

Thứ Tư, 30 tháng 11, 2011

Lượm lặt về 3-tier

Cấu trúc mô hình 3-tier
3-tier[1]: Database
3-tier[2]: Server ( chứa mô hình 3 layer: PL - BLL - DAL ).
3-tier[3]: Client
------------------------------------------
The terms tier and layer are frequently used interchangeably, but actually there is a difference between them: Tiers indicate a physical separation of components, which may mean different assemblies such as DLL, EXE etc on the same server or multiple servers; but layers refers to a logical separation of components, such as having distinct namespaces and classes for the Database Access Layer (DAL), Business Logic Layer (BLL) and User Interface Layer (UIL). Therefore, tier is about physical separation and units of deployment, and layers are about logical separation and units of design.

Creating a multi tier project design is more suitable and advisable to mid to large-size projects, whereas a good multi-layered design is suitable for small to mid-size projects.

Thứ Ba, 29 tháng 11, 2011

SQL Server – Renaming database and physical database files

Sometimes we need to change the name of the database, for example, a database might have been restored using a different name. Whatever the reason may be, this can be easily done via Management Studio or T-SQL.



1. Rename a Database using Management Studio:

Step 1: Renaming Database:

Right Click the Database Name in Object Explorer and Select "Rename", now you can specify new name:

image image

However, this does not change the database file names:

SELECT name, physical_name

FROM [SqlAndMe].sys.database_files

Result Set:

name physical_name

———— ——————-

MyDatabase C:\…\MyDatabase.mdf

MyDatabase_log C:\…\MyDatabase_log.LDF



(2 row(s) affected)



Step 2: Renaming Files:

To change filenames, Right Click on Database in Object Explorer and Select "Properties", Then, go to "Files" Tab:

image

Here, you can change the logical filenames for DATA and LOG files.

Chủ Nhật, 20 tháng 11, 2011

Design Pattern IOC and DI

The problem

Any good architecture always stands on the base that components are loosely coupled… let me stress the point truly loosely coupled. Let’s try to understand this with a scenario and how we normally approach this problem using pure object oriented way.

Consider a scenario where we have a customer class which needs to perform insert operation on database. The customer class should be customizable to save in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.

Below is what we will do. Define two classes one for SQL server and other for Oracle. Both these classes inherit from some kind of same interface ‘Idatabase’. The customer class points to this interface. So the customer class is theoretically shielded from the concrete implementation of SQL Server or oracle. But because the object creational activity needs to be done by the customer class it still needs to be aware of the concrete classes.


Figure: - General loosely coupled thinking


This is what will happen in actual implementation as shown in figure ‘Concrete classes’. The customer class will be creating objects of either oracle or SQL server depending on condition. That means the customer class is exposed to the concrete classes which defeats the purpose of interface. Any change in the database classes will lead to compiling of the customer class.


Figure :- Concrete classes

Creational patterns


The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes from the customer class.

Here are the issues with factory which makes us force to think about some other solutions:-

• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.
• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.
• Factories are custom: - They are very much custom to a particular implementation.
• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

I will not be explaining factory pattern in case you are not aware of you can read the same in my previous article SoftArchInter1.aspx

Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).

Dependency Injection


Rather than writing factory pattern, how about injecting the object directly in to the customer class. So let the customer class references the interface and we should be able to inject the concrete type in to the customer class. With this the customer class does not need to use the new keyword and is complete decoupled from the concrete classes.



Figure: - Dependency injection


Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class.



Figure: - Containers


With this your customer class does not need to worry about creating objects and knowing the concrete objects.

Solving problem using UNITY block


Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection.

Download and installing Unity


The first step is to download the unity application block from http://msdn.microsoft.com/en-us/library/cc468366.aspx and install the same. Depending on whether you have 2008 or 2005 the documentation will vary. For this tutorial I will be using VS 2005 because majority professionals are still using 2005.



Figure: - unity block installed


Once you install the block you should be able to see the same in Microsoft patterns and practices.

The first thing you need to do is to get the references of at least two components Unity and Unity configuration.


Figure: - Add referenced to Unity components


Once you have got reference to the components import the “Microsoft.Practices.Unity” namespace in to your code as shown in figure ‘Import unity namespace’.



Figure: - Import unity namespace

Defining the common interface


As said previously we should be able to inject SQL Server database object or oracle database object in the customer class. So as a good practice we will inherit the SQL server implementation and oracle implementation from a common interface ‘Idatabase’.


Figure: - Database interfaces

Providing the injection gateway


In the customer class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly. There are lot of other ways by which we can achieve the same you can read my previous article on the different ways of providing injection gateways for containers IOCDI.aspx .



Figure: - Providing injection gateway

Defining the config file


To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a windows command application we will be defining an app.config file.

You can see below a simple template of App.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.


Figure: - App.config file

The client code


The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.

In step 4 we tell the container to create the customer object. This is the most important step of all. In this the container using the config data and the dependency attribute injects either the SQL server database object or oracle database object in to the customer class. This object creation depends on what is defined in the app.config file.


Finally in step 5 we call the save method


Figure: - Client code

The actual internal working


So what happens internally in the container is that the unity container creates the object of either oracle or SQL server data objects and injects in to the customer class through the dependency defined attribute.


Enter the real world of loosely coupling


So if you define the ‘clsSqlServer’ class it will create the object of ‘clsSqlServer’ and inject it in to the customer class. If you define the ‘ClsOracle’ class it will inject the ‘clsOracle’ object. You can see in figure ‘The real fun’ how easy it to change implementation by just modifying the config file type sections


Figure: - The real fun

Thứ Sáu, 18 tháng 11, 2011

Vài thuật ngữ được định nghĩa dễ hiểu.

Trước tiên, thuật ngữ này được định nghĩa bởi bloger Đặng Văn Đính, sau đó được st bởi Trần Mạnh Tuấn, mình cảm thấy chính xác và dễ hiểu nên gom về đây (tư tưởng con kiến :)) ). Nếu quan tâm đến tác giả của những định nghĩa này, có thể theo link



Có lẽ bạn đã nghe nói nhiều về Hibernate, NHibernate framework? Thế Hibernate, NHibernate framework là gì? Hy vọng mình và bạn sẽ có trả lời câu hỏi đó khi đọc xong những dòng bên dưới.

Trước khi tìm hiểu Hibernate, NHibernate là gì, chúng ta cần chuẩn bị một số kiến thức để làm nền tảng.
Đầu tiên, chúng ta cần tìm hiểu "framework" là gì? Framework ngày nay được "lạm dụng" rất nhiều. Nhiều người hay gán một vài thứ là "framework" nhưng gán gọi như vậy có đúng không lại là một chuyện khác. Theo cộng đồng wikipedia, từ framework dùng trong phát triển phần mềm là một khái niệm dùng để chỉ những "cấu trúc hỗ trợ được định nghĩa" mà trong đó những dự án phần mềm khác có thể được sắp xếp vào đó và phát triển. Thông thường, một framework bao gồm những program hỗ trợ, code libs và một ngôn ngữ scripting nằm giữa các chương trình phần mềm khác để giúp phát triển và gắn những thành phần khác nhau trong dự án phần mềm lại với nhau.
Tiếp theo, chúng ta cần tìm hiểu về "persistence layer". Từ này tạm thời mình chưa thể dịch sang tiếng Việt được mà chỉ giải thích để bạn hiểu nó là cái gì thôi. Như bạn đã biết, kiến trúc ứng dụng dụng phần mềm có nhiều loại. Có loại chỉ chạy trên một máy là đủ. Có chương trình muốn chạy được phải kết nối sang một máy khác (client-server). Một máy đóng vai trò như là người yêu cầu (client) và máy khác đóng vai trò kẻ phục vụ (server).
Người ta sử dụng thuật ngữ "tier" để chỉ mỗi loại máy có vai trò khác nhau đó. Tier client để chỉ các máy đóng vai trò client và tier server để chỉ các máy đóng vai trò server. Và loại ứng dụng client-server là ứng dụng 2-tier (vì chỉ có 2 tier thôi). Tương tự như vậy theo sự phát triển như vũ bão của công nghệ phần cứng và phần mềm cộng với nhu cầu của các người dùng, doanh nghiệp và xã hội ngày càng lớn, chúng ta thấy có các ứng dụng 3-tier và n-tier để khắc phục nhược điểm của ứng dụng 2-tier và nhằm tăng sức mạnh xử lý cho ứng dụng.
"Layer" là một khái niệm khác với "tier". Và chúng ta đừng lầm lẫn giữa "tier" và "layer". Tier thường gắn với phần cứng máy tính (về mặt physically) còn "layer" thì dính với vấn đề cách thức tổ chức bên trong của ứng dụng.
Việc phân chia tier là "trong suốt" (transparent) đối với ứng dụng xét về mặt luận lý (logically). Điều này có nghĩa là khi chúng ta phát triển một ứng dụng, chúng ta không bận tâm đến các thành phần (component) sẽ triển khai (deploy) ra sao mà chỉ chú ý là chúng ta sẽ tổ chức ứng dụng thành những layer như thế nào. Ví dụ, một ứng dụng có thể chia làm 3 phần như sau: phần giao diện người dùng (UI layer), phần xử lý nghiệp vụ (business layer) và phần chứa dữ liệu (data layer). Cụ thể ra, business layer sẽ có thể chia nhỏ thành 2 layer con là business logic layer (chỉ quan tâm đến ý nghĩa của các nghiệp vụ, các tính toán mang nhằm thoả mãn yêu cầu của người dùng) và persitence layer. Persistence layer chịu trách nhiệm giao tiếp với data layer (thường là một hệ quản trị cơ sở dữ liệu quan hệ - Relational DBMS). Persistence layer sẽ đảm nhiệm các nhiệm vụ mở kết nối, truy xuất và lưu trữ dữ liệu vào các Relational DBMS.

Việc phân chia như vậy có lợi ích là công việc sẽ được tách bạch ra. Người nào lo thiết kế và xử lý UI thì chỉ việc chú tâm vào công việc đó. Người lo business layer thì chỉ cần tập trung vào thiết kế và phát triển làm sao thoả mãn các requirement của khách hàng mà không phải chú tâm đến các khía cạnh hiện thực bên dưới thông thường liên quan đến technical issues. Còn người lo persistence layer thì chỉ việc chú trọng đến các khía cạnh hiện thực và giải quyết các technical issues mà thôi. Cũng như sẽ có những DBA (DB Administrators) lo việc cài đặt và tạo các objects trong các relational database.

Như vậy, bạn đã hiểu ứng dụng được chia một cách logically thành các "layer" và bạn cũng hiểu được là persistence layer là một layer có nhiệm vụ kết nối Relational DBMSs và truy xuất, thao tác trên dữ liệu đã được lưu trữ cũng như lưu trữ dữ liệu mới vào chúng. Hibernate framework là một framework cho persistence layer. Và bạn có thể thấy rằng nhờ có Hibernate framework mà giờ đây khi bạn phát triển một ứng dụng bạn chỉ còn chú tâm vào những layer khác mà không phải bận tâm nhiều về persistence layer nữa. Tương tự như vậy nếu bạn có một UI framework, bạn sẽ không phải bận tâm nhiều về UI layer nữa. Và xét đến cùng, việc bạn quan tâm duy nhất là business logic layer của bạn có đáp ứng yêu cầu của khách hàng không hay thôi.

Và đây là thông tin về Hibernate framework từ website chính thức của Hibernate:
Hibernate là một dịch vụ lưu trữ và truy vấn dữ liệu quan hệ mạnh mẽ và nhanh. Hibernate giúp bạn phát triển các class dùng để lưu trữ dữ liệu theo cách thức rất là hướng đối tượng: association, inheritance, polymorphism, composition và collections. Hibernate cho phép bạn thực hiện các câu truy vấn dữ liệu bằng cách sử dụng ngôn ngữ SQL mở rộng của Hibernate (HQL) hoặc là ngôn ngữ SQL nguyên thuỷ cũng như là sử dụng các API.

Không giống như các persistence layer khác, Hibernate không ẩn đi sức mạnh của ngôn ngữ SQL khỏi bạn mà Hibernate còn đảm bảo cho bạn việc bạn đầu tư vào công nghệ và tri thức cơ sở dữ liệu quan hệ là luôn luôn chính xác. Và điều quan trọng hơn nữa là Hibernate được license theo LGPL (Lesser GNU Public License). Theo đó, bạn có thể thoải mái sử dụng Hibernate trong các dự án open source hoặc các dự án thương mại (commercial).

Hibernate là một dự án open source chuyên nghiệp và là một thành phần cốt tuỷ của bộ sản phẩm JBoss Enterprise Middleware System (JEMS). JBoss, như chúng ta đã biết là một đơn vị của Red Hat, chuyên cung cấp các dịch vụ 24x7 về hỗ trợ chuyên nghiệp, tư vấn và huyấn luyện sẵn sàng hỗ trợ bạn trong việc dùng Hibernate.

NHibernate là một công cụ mapping object/relational cho môi trường .NET. Thuật ngữ mapping object/relational (ORM) liên quan tới kỹ thuật mapping một mô phỏng dữ liệu của một object model tới một relational data model với một mô hình dựa trên SQL.

Các thành phần của Hibernate project:

* Hibernate Core: Cung cấp các chức năng cơ bản của một persistence layer cho các ứng dụng Java với các APIs và hỗ trợ XML mapping metadata.
* Hibernate Annotations: Các map class với JDK 5.0 annotations, bao gồm Hibernate Validator.
* Hibernate EntityManager: Sử dụng EJB 3.0 EntityManager API trong JSE hoặc với bất kỳ JEE server nào.
* Hibernate Tools: Các tool tích hợp với Eclipse và Ant dùng cho việc sinh ra các persistence object từ một schema có sẵn trong database (reverse-engineering) và từ các file hbm sinh ra các class java để hiện thực các persistence object, rồi Hibernate tự tạo các object trong database (forward-engineering).
* NHibernate: Hibernate cho .Net framework.
* JBoss Seam: Một Java EE 5.0 framework cho phát triển các ứng dụng JSF, Ajax và EJB 3.0 với sự hỗ trợ của Hibernate. Seam hiện rất mới và tỏ ra rất mạnh để phát triển các ứng dụng Web 2.0. Nó tích hợp đầy đủ tất cả các công nghệ "hot" nhất hiện nay.

Thứ Hai, 14 tháng 11, 2011

Lorem Ipsum

Bạn đã bao giờ vô tình đọc được "Lorem Ipsum". Nếu chưa thì hãy đọc tiếp.

Trích: "Chúng ta vẫn biết rằng, làm việc với một đoạn văn bản dễ đọc và rõ nghĩa dễ gây rối trí và cản trở việc tập trung vào yếu tố trình bày văn bản. Lorem Ipsum có ưu điểm hơn so với đoạn văn bản chỉ gồm nội dung kiểu "Nội dung, nội dung, nội dung" là nó khiến văn bản giống thật hơn, bình thường hơn. Nhiều phần mềm thiết kế giao diện web và dàn trang ngày nay đã sử dụng Lorem Ipsum làm đoạn văn bản giả, và nếu bạn thử tìm các đoạn "Lorem ipsum" trên mạng thì sẽ khám phá ra nhiều trang web hiện vẫn đang trong quá trình xây dựng. Có nhiều phiên bản khác nhau đã xuất hiện, đôi khi do vô tình, nhiều khi do cố ý (xen thêm vào những câu hài hước hay thông tục)."

Trên đây là đoạn giới thiệu về Lorem Ipsum. Nếu có hứng thú, các bạn có thểm tìm hiểu thêm và sử dụng theo link