Sunday, December 26, 2010

VB.NET Lecture # 1

Technology Trend: A brief review
Some time back companies acquired software to automate and speedup individual activities. For example a company bought an attendance system to improve timings, attendance and related activities. Similarly some companies bought “General Ledger” whereas others bought “Inventory Control Systems”.
Later people started to realize that greater benefits could be achieved if the data stored in one application is shared by others or if the applications integrated with each other. This lead to the introduction of Enterprise Software Solutions which consist of a number of modules supporting various activities of business. These modules are integrated with each other so that a holistic view of information is made available to stakeholders. These modules are often loosely coupled distributed applications that involve integration of components developed in different technologies.
The conclusion of the above discussion is that, these days it is important that the technology used by developers support integration of your product with others developed using heterogeneous platforms.

What is Microsoft .NET?
It is a set of software technologies for connecting information, people, systems, and devices. It enables a high level of software integration through the use of Web services that are small, discrete, building-block applications that connect to each other as well as to other, larger applications over the Internet.
What is a Framework?
It is a set of assumptions, concepts, values, and practices that constitutes a way of viewing reality. An example of framework is “The Primary Framework for literacy and mathematics” developed by the “Department of Children, Schools and Families, UK”. This framework has been designed to support teachers and schools to deliver high quality learning and teaching for all children. It contains detailed guidance and materials including concepts, values and practices to support literacy and mathematics in primary schools and settings.
Similarly in the local educational institutions you will find all teachers following certain guidelines and readymade documents. For example, similar attendance sheet is used by all and same marks distribution is followed. This is also an example of framework.

What are Software Frameworks? They support the development of software by providing collection of items which are reusable as a group. They have carefully designed plug–points into which the user inserts code to customize or extend the framework.
Horizontal Frameworks: Are generic and can be used to develop products for any business domain.
Vertical Frameworks: Are specialized and can be used to develop products for a specific domain.

What is .NET Framework? The .NET framework thus is a set of concepts, values, practices and items that can be used to develop next generation of applications. The .NET framework being a software framework has plug-In points defined that allow users to write code in order to develop customized applications. The .NET framework has two main components that are CLR (Common Language Runtime) and .NET Class Library. The details of these components will be discussed later in the text.

Objectives of the .NET framework:
The .NET framework is designed to achieve the following objectives,
• To provide a consisted programming environment whether a person is developing a window-based, web or other type of applications.
• To ensure that the code written in .NET can integrate with any other code. This has been done by making use of communication means that are industry standards rather than propriety ones
• To facilitate programmers by providing a consistent object oriented programming environment irrespective of whether the code is stored/executed locally, remotely or involves internet.
• To provide an environment that minimizes software deployment and versioning conflicts.
• Enable safe execution of code, including code created by unknown semi-trusted third party
• To improve performance that were there in previous scripted or interpreted environments

Components of .NET framework:
• Class Library: As mentioned that each framework has a collection of reusable items. The collection of reusable items, which is object oriented, is known as Class Library in Microsoft.NET
• Common Language Runtime: Like the runtime of any other language, CLR has the responsibility of executing the code of that language. However in .NET, CLR has additional responsibility of converting the code into native platform code. In other words, the responsibility of CLR is to translate code into platform understandable form, manage code at execution time, provide core services such as memory management, thread management, and remoting, while also enforcing strict type safety and other forms of code accuracy that promote security and robustness

Other important concepts:
Compiler: The responsibility of compiler in the environment of Microsoft.NET is to identify any syntactical errors in the code. If there are not any, then it converts the code into intermediate form
MSIL (Microsoft Intermediate Language): The compiled code in .NET takes the form of MSIL. Every language in .NET is converted into MSIL after compilation which is then converted into native form on execution by the CLR.
Assembly: The .exe or .dll file which is generated after compilation is referred to as Assembly. This assembly has two major ingredients, MSIL code and Metadata.
Metadata: Metadata means data about data. Metadata describes the types, members and references in code. This metadata is used by Runtime to locate and load classes. In addition it is also used for laying out instances in memory, to resolve method invocations, generate native code, enforce security and set run-time context boundaries

Monday, December 13, 2010

Hard Disk Getting Filled In Windows 7

While working in office I noticed the Low Disk Space message on my Windows 7 machine. I calculated the total amount of memory consumed and it summed up to just 21 GB whereas the primary partition that was filled up had 30 GB of space.
Although the problem is not solved yet, but still I accumulated a lot of interesting bits of information.
First one is a tool named “TreeSize”.
TreeSize is a free tool that examines folders or hard drives to indicate the information consumed by items. It shows a lot of info that windows explorer does not show.
For example, through TreeSize I found that there is a file named “hiberfil.sys” which is consuming 1.5 GB of my Hard disk space and an MSOCache Folder which is consuming upto 2 GB of space.


Then I went on to search how to remove and get back the 1.5 GB space. Through this I determined that if hibernation is disabled then this file gets deleted automatically.
I found a very good article to do that and I am including its link below.
http://www.howtogeek.com/howto/15140/what-is-hiberfil.sys-and-how-do-i-delete-it/

Another folder that was eating a lot of space was MSOCache. On research it was discovered that this folder is related to MSOffice and is never recommended to delete it with windows explorer. The right way to clean this is to use Windows Cleanup Wizard

One last bit of information that was related to all this was using the "%temp%" command which should be typed in Run text box. This box is either displayed by clicking the start button or press Windows Button on Keyboard in combination with letter R . Novice users should just keep in mind that it displays a list of temporary files that you can delete without any fear or danger. In case, While deleting these files you encounter a warning that a particular file should not be deleted then you should not delete that file. Deleting these temporary will also make a lot of space available

The sad part of this story is that within 2 minutes of freeing up 1.5 GB my hard disk got filled again

Wednesday, November 24, 2010

Editing Installer (.MSI) through ORCA

Introduction:
This document attempts to provide a starting point to those who want to customize the MSI more than what is allowed through Visual Studio.

How to Obtain ORCA?
It’s installation is available when Windows SDK is installed. The installation is named ORCA.msi. After the successful completion of installation ORCA.exe will be available in Program Files

Editing installer in ORCA: After installation if you right click an installer, “Edit with ORCA” option will be available.

Otherwise you can open ORCA and click File-Open to get the traditional FileOpen Dialog.

Once the file is opened a list of tables will be displayed. These tables contain various aspects of information that direct windows installer about how to execute the MSI file.



In case you want to modify the control types or labels you can select the “Control” element form the “Tables” list The values in the Type column in control table can be modified if required. For example, if it is desired to display something as ReadOnly, we can change the type from Edit to Text.
The Text property holds the font, followed by contents. The contents can be changed to desired values. It must also be noted that in some cases Text property holds a property rather than literal value e.g [TARGETAPPPOOL].

Another Table is “Binary” which holds things like banner image. We can double click any entry to change the file associated with it.


Important Points to Remember:
Please note that all changes that you make in installer will be overridden when you recompile the installer, for example through Visual Studio.
In addition, remember that orca can only modify MSI files not exe. The setup.exe generated while creating MSI through Visual Studio actually calls the corresponding MSI file. Therefore changes in MSI will effect Setup.exe automatically

Friday, November 19, 2010

Embedding SQL Server Installation and Restoring SQL Server Database Backup during Installation

As mentioned before, most recently i was involved in creation of installer for one of our products. One of the activity that was to be performed during installation was the restoration of database backup and invoking installer of SQL Server after checking registry. In this post i am including links of the articles that i found useful regarding restoration of databse and installation of SQL Server

How to restore a SQL Server database in .NET when there are connections open
(This is the simplest and most effective way that I could find regarding restoring backup file)
Read It

Restore Database during Application Deployment
Read It

Walkthrough: Using a Custom Action to Create a Database at Installation
Demonstrates the use of a custom action and the CustomActionData property to create a database and database table during installation.
Read It

Embedding SQL Server Express into Custom Applications
This white paper discusses how to integrate and deploy Microsoft SQL Server Express-based applications by using configuration files and the ClickOnce deployment technology in Microsoft Visual Studio.
(The good idea that I got from this was to create wrappers for installers that would perform tasks that are not doable through the Installer/Custom Action as it executes after the completion of installation process, not before it)
Read It

How to Embed SQL Server Express in an Application
If your application uses SQL Server Express to host its database, you can freely redistribute the SQL Server Express product with your application. This article contains information and links that will enable you to successfully embed SQL Server Express as part of your application installation.
Read It

Sunday, November 14, 2010

Introduction to ORCA: A Tool to Customize Windows Installers

These days I am involved in an activity of launching one of our products in market as ISV (Independent Software Vendor). One of the activities in that is to create an Installer for the product.

The installer that is created for Web Projects through Visual Studio 2010 is quite generalized and it was felt by us that we must tweak it to some extent to fit our actual requirements.

For example, the initial screens of installer ask the user to specify a virtual directory and an application pool. For specifying the virtual directory the installer presents a TextBox and for application pool a combo box is provided. However, in our case we wanted them to be “Non-Editable” fields so that the user is only informed about the virtual directory and application pool.

After research it was found that Windows SDK contains a tool called ORCA which allows us to modify the Installer file as per our requirements
ORCA presents the installer file as a database containing number of tables. For example, there is a table named “Control” which stores information about all the controls used in the installer.

The values in the table can be modified as per the requirement. One problem that I faced is that there is not enough documentation readily available which shows how to use ORCA (Or maybe it is, but I was not able to find it). Therefore I will dedicate a future post to using ORCA.

Wednesday, August 4, 2010

Customizing Silverlight Controls

Customizing Silverlight Controls
The best thing about Silverlight controls is that their appearance and behavior can be changed dramatically without affecting the functionality of the control.
For example a Button may display a simple text or it can display a grid on itself. The shape of a button can be left as default or it can be changed to a circle.
Introduction:
This document provides basic information that is very helpful in learning how the visual appearance of a Silverlight control can be changed. It is determines various ways of changing appearance and provide code samples.
Customizing Controls
Customization can be done by setting simple values in the properties or by storing a complex structures for example

<button name="SimpleBackground" type="submit" content="Hello" background="Yellow"></button>

<button name="ComplexBackground" type="submit" content="Hello">
<button.background>
<lineargradientbrush endpoint="1,1" startpoint="0,0">
<gradientstop color="Green" offset="0.2"></gradientstop>
<gradientstop color="Yellow" offset="1"></gradientstop>
</lineargradientbrush>
</button.background>

</button>
</pre>


In the above XAML, Button named “SimpleBackground” stores a simple color in Background where as “ComplexBackground” associates a complex structure.
Similarly the content of control can be set to a simple string or it can be set to a complex group of other controls. The example below instructs Silverlight to make a button that has a checkbox placed on it.
<button name="ComplexBackground" type="submit" row="0" column="1">
<button.background>
<lineargradientbrush endpoint="1,1" startpoint="0,0">
<gradientstop color="Green" offset="0.2"></gradientstop>
<gradientstop color="Yellow" offset="1"></gradientstop>
</lineargradientbrush>
</button.background>
<button.content>
<checkbox content="Click Me">
</button.content>
</button>

Following is the complete example which displays two buttons one of which is simple one displaying plain text and single color background, whereas the other has multi-color background and consists of a checbox .
<grid name="LayoutRoot" background="White" showgridlines="True">
<grid.columndefinitions>
<columndefinition width="*"></columndefinition>
<columndefinition width="4*"></columndefinition>
</grid.columndefinitions>
<grid.rowdefinitions>
<rowdefinition height="Auto"></rowdefinition>
</grid.rowdefinitions>

<button name="SimpleBackground" type="submit" content="Hello" background="Yellow" row="0" column="0"></button>


<button name="ComplexBackground" type="submit" row="0" column="1">
<button.background>
<lineargradientbrush endpoint="1,1" startpoint="0,0">
<gradientstop color="Green" offset="0.2"></gradientstop>
<gradientstop color="Yellow" offset="1"></gradientstop>
</lineargradientbrush>
</button.background>
<button.content>
<checkbox content="yo"></checkbox>
</button.content>
</button>


</grid>

Other Ways to Change Visual Appearance of Controls
The above code demonstrates how the visual appearance of a control can be changed using properties however in some cases you may want a single style to be applied to a number of controls. This can be done in two ways
• Using Styles
• Using ControlTemplate
Using Styles:
Styles are a collection of property values that can be applied to controls of particular type. The style can be stored in a separate file for global usage. The “TargetType” property of a style specifies the controls to which the style can be applied to. It is also possible to specify a key for the style, in which case the style will only be applied to controls which refer to that key.
Following code demonstrates how a style can be created
<pre>
<usercontrol.resources>
<style targettype="Button">
<setter property="Background">
<setter.value>
<lineargradientbrush startpoint="0,0" endpoint="1,1">
<gradientstop offset="0.2" color="Green"></gradientstop>
<gradientstop offset="1" color="Yellow"></gradientstop>
</lineargradientbrush>

</Setter.Value>

</setter>
<setter property="FontFamily" value="Arial Black"></setter>
<setter property="MaxWidth" value="100"></setter>
<setter property="MaxHeight" value="50"></setter>


</style>

</usercontrol.resources>
<pre>
Once the above style is created, all controls belonging to the type mentioned in the TargetType property will have the same property values as indicated in the style. For example, the following code creates two buttons. Although not mentioned explicitly but these buttons will have the style created above as both of them belong to the type button.


<button type="submit" content="Button1" row="1" column="1">
<button type="submit" content="Button2" row="1" column="2">

Using Control Template

Control Templates are used in case where we want to completely customize the look and feel as well as behavior of controls. E.g. of complete customization includes replacing or removing parts of a control or adding new parts. For simply setting the properties to certain values, Style is simplest and best choice.

ControlTemplate combine FrameworkElement objects to build a single control. A controlTemplate must have a single FrameworkElement at its root.

The Template property of a control is used to specify the ControlTemplate for that control. Template property can be set in the following three ways
• Set the Template property to an Inline template
<pre>
</pre><button type="submit" content="Button1">
<button.template>
<controltemplate targettype="Button">

<!--Define the ControlTemplate here.-->

</controltemplate>
</button.template>
</button>
<pre></pre>
• Set the Template property to reference ControlTemplate defined as a resource
<pre>
<grid>
<grid.resources>
<controltemplate targettype="Button" key="newTemplate">

<!--Define the ControlTemplate here.-->

</controltemplate>
</grid.resources>

<button type="submit" template="{StaticResource newTemplate}" content="Button1">
</grid>
<pre></pre>
• Define Template in a Style and link control to that style
<pre>
<stackpanel>
<stackpanel.resources>
<style targettype="Button" key="newTemplate">
<setter property="Template">
<setter.value>
<controltemplate targettype="Button">

<!--Define the ControlTemplate here.-->

</controltemplate>
</Setter.Value>
</setter>
</style>
</stackpanel.resources>
</pre><button type="submit" content="Button1">
</stackpanel>
<pre></pre>
Following is an example that sets the template for a control by combining a number of framework elements
<pre>
<usercontrol.resources>
<style targettype="Button">
<setter property="Template">
<setter.value>
<controltemplate>
<grid>
<rectangle width="200" height="100" fill="Blue" stroke="Black" strokethickness="7">
<ellipse width="100" height="100" fill="Transparent" stroke="Yellow" strokethickness="5"></ellipse>
<textblock text="Click Me" horizontalalignment="Center" verticalalignment="Center" foreground="White"></textblock>
</grid>
</controltemplate>
</Setter.Value>
</setter>
</style>
</usercontrol.resources>
</pre>
Binding Template to Control Properties using TemplateBinding

One more requirement can arise, that the user of control may want the Template to get some values from the control. For example, we want the color of Rectangle within a template to be that which has been assigned to the background property of Button to which the template is being applied.

The TemplateBinding Markup Extension serves this purpose. It enables the template to change itself based upon the public properties of control. The following code indicates that the value of Fill property will be set by the value of Background property of control
<pre>
<rectangle width="200" height="100" strokethickness="7" stroke="Black" fill="{TemplateBinding Background}">
</pre>
It must also be noted that the Control class defines several properties that can be used by ControlTemplate to have an effect on the control when they are set.

Using ContentPresenter:

One more flexibility is that we can include ContentPresenter in the template rather than controls like TextBlock or Button. This enables the user of control to set a group of controls in the content rather than just text.

Following is the complete example demonstrates the usage of ContentPresenter
<pre>
<usercontrol.resources>
<style targettype="Button">
<setter property="Template">
<setter.value>
<controltemplate>
<grid>
<rectangle width="200" height="100" fill="{TemplateBinding Background}" stroke="Black" strokethickness="7">
<ellipse width="100" height="100" fill="Transparent" stroke="Yellow" strokethickness="5"></ellipse>
<contentpresenter content="{TemplateBinding Content}" horizontalalignment="Center" verticalalignment="Center"></contentpresenter>

</grid>
</controltemplate>
</Setter.Value>
</setter>
</style>
</usercontrol.resources>
<grid name="LayoutRoot" background="White">
</pre><button type="submit" content="Hello" background="Aqua">

</button>

</grid>

</pre>
Customizing Controls by Understanding the Control Contract

Controls that uses ControlTemplate to specify visual structure use Parts Control Model. Many controls that are offered by Microsoft and third-parties follow this model. As per this model, it can be said that a control is made up of “Parts”. The information about these parts of a control is communicated through the control contract. Understanding control contract is very helpful in customizing the appearance of control based on a template

Contract has three elements
• Visual Elements
o These are used by the logic inside a control. In other words the code of control has references to certain FrameworkElements. Therefore the template must have objects for these references. The control uses the TemplatePartAttribute to convey the type of element that is expected, and what the name of the element should be.
• States
o The states of a control are also a part of the control contract. The states of a control are specified by the TemplateVisualStateAttribute
• Public properties
o Public properties are also considered as a part of contract. The properties can also be set without creating any ControlTemplate

Conclusion:

Appearance of Silverlight controls can be changed by
• Directly setting properties
• Creating Styles
• Creating Templates

Understanding control contract is very helpful in creating templates for a control. The class of control communicates the control contract by using TemplatePartAttribute and TemplateVisualStateAttribute

Tuesday, June 29, 2010

Using the Charts/Graphs of Silverlight Toolkit

Recently I got a task of developing a Silverlight user control that displays charts for various data sets. This implied that I study and understand the charts provided in the Silverlight toolkit. Therefore, I started learning the How-Tos of it. Although there is a sample application provided with the toolkit but the code is quite lengthy and some people like me prefer a quick start before diving into the details. Therefore I simplified the example and now it is being shared so that others can take advantage of it.
The basic ingredients include instances of

  • Chart

  • DataPointSeries (When it is desired to draw, Pie, Line, Bar, Column, Bubble and Scatter graph)

  • An instance of IEnumerable interface



Following is the code that displays a pie chart. Comments have been included so that the code is better understood.

Don't forget to import the following

using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Data;


Monday, April 19, 2010

Sample Code: Handling Value Change Events in JSF

There are two type of events that are generated by JSF components
• Value Change Events
• Action Events
One way to handle the events is to implement the appropriate listener. For handling action events javax.faces.event.ActionListener must be implemented and for handling value-changed events javax.faces.event.ValueChangedListener must be implemented. It must also be noted that action events are generated by controls that implement the ActionSource interface where as value-change events are generated by those controls that implement the EditableValueHolder interface.
Following is a class that implements ValueChangedListener. As can be seen that when implementing this listenen the processValueChange method must be implemented

package stu;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;

@ManagedBean(name="questionsController")
@SessionScoped
public class QuestionsController implements ValueChangeListener{
private String data;

public String getData() {
return data;
}

public void setData(String data) {
this.data = data;
}
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
data = event.getNewValue().toString();
}
public QuestionsController() {

}

}
Registering a Listener with EditableValueHolder can be done either by specifying the type i.e. fully qualified name of class that implements ValueChangeListener (using the type attribue), or by registering an instance of ValueChangeListener implementation with the component (using binding attribute). This information is provided within the valueChangeListener tag nested inside the components tag with which the listener is to be registered.

<h:body>
<h:form>
Hello from Facelets
<h:selectOneRadio>
<f:selectItem itemValue="a" itemLabel="a"></f:selectItem>
<f:selectItem itemValue="b" itemLabel="b"></f:selectItem>
<f:valueChangeListener binding="#{questionsController}"></f:valueChangeListener>
</h:selectOneRadio>
<h:commandButton value="error" action="error"></h:commandButton>
</h:form>
</h:body>

As can be seen that error page displays the output, the code for which is given below

<h:body>
Invalid Login
<h:outputLabel value="#{questionsController.data}"></h:outputLabel>
</h:body>

Saturday, April 17, 2010

Introduction to Java Hibernate

Introduction to Java Hibernate

Objectives of this document is to give readers an understanding of the following issues

Object Relational Impedance Mismatch
Benefits of Hibernate as ORM Framework
Architecture of Hibernate Framework
Persistence Life Cycle

Object Relational Impedance Mismatch:
There are a number of differences in the Relational Model (used in database) and Object Oriented Model (used by programming languages). These differences are referred to as Impedance Mismatch. Some areas of Impedance Mismatch are as follows

Identity

In OOP “Identical” and “Equal” are different notions. Two objects are equal if they refer to the same memory location i.e. equality in OOP does not take into consideration the contents of the object but only the reference. However the “equals” method can be overridden to check the contents rather than the reference. In relational database, the equality is based upon the primary key of entity

Inheritance
In RDBMS, inheritance is not supported.
Associations
In RDBMS many-to-many relationships are not directly supported and are modeled via bridge tables. Where as in OOP such relationships can be easily modeled by having collections containing related objects at each end of the relationship. For example a student class may consist of collection having related course and course class may consist of a collection containing students related to that particular course.
Due to above reasons a number of ORM frameworks are available. However among all those, hibernate has become very popular because of the following reasons

Benefits of Hibernate


Simple and Flexible

Single configuration file and one mapping for each application object to be persisted
No need to inherit any classes

Completeness
Complete support for OOP
Has special query language similar to SQL

Performance
Issues statements only when state of object changes
Collections are loaded when they are needed
Properties are populated when needed
Users can disable which associated object will not be loaded
Supports caching

Architecture of Hibernate
Makes use of existing Java APIs including
JDBC for data access
JTA and JNDI enable integrity with JEE
Interfaces provided by Hibernate belong to four categories
Called by applications to perform CRUD and Queries e.g. Session, Transaction and Query
Called by applications to Configure hibernate, e.g. Configuration
Used by applications to react to events occurring inside hibernate. e.g. Interceptor, Lifecycle and Validatable.
Enable extending Hibernate’s powerful mapping functions e.g UserType, CompositeUserType and IdentifierGenerator. (These are implemented by application infrastructure code.)

Following is a description of some important interfaces
Session Interface
It is the Primary interface used by applications
Session is Lightweight and inexpensive to create and destroy
It must be noted that it is not thread safe
It can be considered as cache or collection of loaded objects related to a single unit of work
Also called persistence manager as it performs loading and saving

SessionFactory

Instances of SessionFactory are Heavy weight
And thread safe as they are Intended to be shared among multiple threads
Each object of sessionFactory will represent a single database
Caches generated SQL, mapping metadata for runtime and data (only in-case of second-level cache)

Configuration interface
The Configuration object is used to configure and bootstrap Hibernate
Creates the SessionFactory

Transaction

Optional Interface
Abstracts application code from underlying transaction implementation

Query and Criteria Interface
Query is lightweight and can’t be used out of session
can be used to
Bind parameters
Limit the number of result
Execute Query

Criteria is similar to queries
Create and execute object oriented criteria queries

Callback Interfaces
Allows applications to receive notifications
LifeCycle and Validate needs to be implemented by persisted classes(Not preferred)
Interceptor needs not be implemented by persistent classes.

Type interface
Hibernate supports rich type system
Nevertheless, custom types can be created using
UserType
CompositeUserType

Extension Interfaces
Customized Implementation of certain interfaces possible
Enables plugging in code into hibernate framework
Extension Points and Corresponding Interfaces
Primary key generation (IdentifierGenerator interface)
SQL dialect support (Dialect abstract class)
Caching strategies (Cache and CacheProvider interfaces)
DBC connection management (ConnectionProvider interface)
Transaction management (TransactionFactory, Transaction, and TransactionManagerLookup interfaces)
ORM strategies (ClassPersister interface hierarchy)
Property access strategies (PropertyAccessor interface)
Proxy creation (ProxyFactory interface)

Persistence Life Cycle
Hibernate persistence is Transaction-Scoped
In the context a row will be represented by a single instance
When same row is retrieved twice reference to single instance will be returned
Defines three states for an object
Transient
Persistent
Detached

Transient
Objects created with new operator
Not associated with any database row
Their state garbage collected when dereferenced
Considered non-transactional by hibernate
Can be made persistent
By calling save method
Creation of reference from an already persistent instance

Persistent
Any instance with a database identity
Always associated with persistence manager i.e. Session
Are Transactional
i.e. Their state is synchronized with database at the end of transaction
SQL queries are used for this purpose
Can be retrieved from database by
Executing Query
Identifier Lookup
Navigating object graph starting from persistent instance
Instance is called new if Identity allotted but not stored in database yet

Detached
Objects no longer associated with persistence manager
This happens when the session is closed
Their state is no longer guaranteed to be synchronized with Database
A detached instance can be re-associated with another Persistence manager

Above were some of the basics of Hibernate. This post will be appended with more material related to hibernate basics.

Thursday, April 15, 2010

Writing SQL Query

This material guides how to make the right query inorder to retrieve particular records. It has been observed that often students are not sure that what can be applied to retrieve the required records

This article will use the following schema

order(orderid, orderdate, customerid)
customer(cutomerid, customername)

1- Whenever an objective is given first determine the resources/tables that are required. This can be done either by looking at the columns that are required to be displayed or the columns on the basis of which filteration of rows is done.

for example given the following objective
Find the dates of all orders

The above objective asks for the date of all orders which clearly indicates that orderdate column is required which is present in the order table. Thus the query will be

Select orderDate from orders

However if the objective is to display the orderDates as well as customerNames then the query will be modified. Here the objective indicates that orderDate is required which is in the order table and customerName is required which is in the customer table. Thus the query will need to join the contents of two tables which is always on the basis of common column. The query in this case will be

Select customerName, orderDate from order, customer where order.orderno=customer.custno

2- Secondly determine whether all records need to be displayed or some filteration needs to be applied. For example, if the objective is to display the orderdate and name of customer who have placed order on '10/10/2010' then we need to appy filteration on the basis of orderdate. This is in addition to join-condition which is there due to the reason that orderDate and customerName are in different table. The query in this case will be

Select customerName, orderDate from order, customer where order.orderno=customer.custno and orderDate='10/10/2010'

3- Thirdly, see if there is a need of aggregates or summarized columns. If the query asks for a single aggregate then use appropriate aggregate function, however, if it requires multiple aggregates based upon values of particular column then apply group by. For example if the objective is to determine total number of orders then the query will be

Select count(*) from orders

Do note that the objective was to calculate a single aggregate for the entire table therefore group by has not been applied. In addition, since the resources required for the query were present in one table therefore no join was applied and finally there was no need of filteration as a single total for entire table was required. However if the objective is modified such that only total number of orders placed on '10/10/2010' is required then a where clause will be appended in the above query as filteration is now needed

Select count(*) from orders where orderDate='10/10/2010'

As mentioned that in cases where a number of summaries are needed to be displayed then a group by clause is appended. For example if we need to display summaries on the basis of customer, i.e. total number of orders placed by each customer then group by clause containing name of customer related column will be appended

Select count(*) from orders group by customerId

4- The final step is to see whether all summaries (outputs of aggregates) need to be displayed or only particular ones. For example if the above objective is modified such that only those customerids are required to be displayed that have more than 5 orders, then we need to apply the having clause.

Select count(*) from orders group by customerId having count(*)> 5

To summarize, having is applied when output of group by needs to be filtered

Please note that the list is not exhaustive and some more points may be added in future. However for most of the scenarios the above point will be a very great help