Archive for ◊ July, 2009 ◊

Author:
Friday, July 31st, 2009

my blogs will talk about the database tips.

following is the first one which talks about the differences between IN and EXISTS clause.

When coding a SQL statement with tables in master-detail relationships, it’s common to have to decide whether to write the query using the WHERE EXISTS (. . .) clause or the WHERE value IN (. . .) clause. You may resist using WHERE EXISTS because it has the awkward syntax of returning a value, which you always ignore.

However, there’s a difference when using rule-based optimization. You can determine the performance of a rule-based query by understanding which table is the driving table and how many rows each part returns.

When you write a query using the IN clause, you’re telling the rule-based optimizer that you want the inner query to drive the outer query (think: IN = inside to outside). For example, to query the 14-row EMP table for the direct reports to the employee KING, you could write the following:

select ename from emp e
where mgr in (select empno from emp where ename = ‘KING’);

Here’s the EXPLAIN PLAN for this query:

OBJECT     OPERATION
———- —————————————-
SELECT STATEMENT()
NESTED LOOPS()
EMP                TABLE ACCESS(FULL)
EMP                 TABLE ACCESS(BY INDEX ROWID)
PK_EMP               INDEX(UNIQUE SCAN)

This query is virtually equivalent to this:

select e1.ename from emp e1,(select empno from emp where ename = ‘KING’) e2
where e1.mgr = e2.empno;

You can write the same query using EXISTS by moving the outer query column to a subquery condition, like this:

select ename from emp e
where exists (select 0 from emp where e.mgr = empno and ename = ‘KING’);

When you write EXISTS in a where clause, you’re telling the optimizer that you want the outer query to be run first, using each value to fetch a value from the inner query (think: EXISTS = outside to inside).

The EXPLAIN PLAN result for the query is:

OBJECT     OPERATION
———- —————————————-
SELECT STATEMENT()
FILTER()
EMP                TABLE ACCESS(FULL)
EMP                 TABLE ACCESS(BY INDEX ROWID)
PK_EMP               INDEX(UNIQUE SCAN)

This is virtually similar to the PL/SQL code:

set serveroutput on;
declare
l_count integer;
begin
for e in (select mgr,ename from emp) loop
select count(*) into l_count from emp
where e.mgr = empno and ename = ‘KING’;
if l_count != 0 then
dbms_output.put_line(e.ename);
end if;
end loop;
end;

To determine which clause offers better performance in rule-based optimization, consider how many rows the inner query will return in comparison to the outer query. In many cases, EXISTS is better because it requires you to specify a join condition, which can invoke an INDEX scan. However, IN is often better if the results of the subquery are very small. You usually want to run the query that returns the smaller set of results first.

Some people avoid the EXISTS clause because of the requirement to return a result from the query–even though the result is never used. Depending on personal style, people often use ‘X,’ 1, 0, or null. From looking at the EXPLAIN PLAN output, it appears that the optimizer throws out whatever value you enter and uses 0 all the time.

When coding a SQL statement with tables in master-detail relationships, it’s common to have to decide whether to write the query using the WHERE EXISTS (. . .) clause or the WHERE value IN (. . .) clause. You may resist using WHERE EXISTS because it has the awkward syntax of returning a value, which you always ignore.

However, there’s a difference when using rule-based optimization. You can determine the performance of a rule-based query by understanding which table is the driving table and how many rows each part returns.

When you write a query using the IN clause, you’re telling the rule-based optimizer that you want the inner query to drive the outer query (think: IN = inside to outside). For example, to query the 14-row EMP table for the direct reports to the employee KING, you could write the following:

select ename from emp e
where mgr in (select empno from emp where ename = ‘KING’);

Here’s the EXPLAIN PLAN for this query:

OBJECT     OPERATION
———- —————————————-
SELECT STATEMENT()
NESTED LOOPS()
EMP                TABLE ACCESS(FULL)
EMP                 TABLE ACCESS(BY INDEX ROWID)
PK_EMP               INDEX(UNIQUE SCAN)

This query is virtually equivalent to this:

select e1.ename from emp e1,(select empno from emp where ename = ‘KING’) e2
where e1.mgr = e2.empno;

You can write the same query using EXISTS by moving the outer query column to a subquery condition, like this:

select ename from emp e
where exists (select 0 from emp where e.mgr = empno and ename = ‘KING’);

When you write EXISTS in a where clause, you’re telling the optimizer that you want the outer query to be run first, using each value to fetch a value from the inner query (think: EXISTS = outside to inside).

The EXPLAIN PLAN result for the query is:

OBJECT     OPERATION
———- —————————————-
SELECT STATEMENT()
FILTER()
EMP                TABLE ACCESS(FULL)
EMP                 TABLE ACCESS(BY INDEX ROWID)
PK_EMP               INDEX(UNIQUE SCAN)

This is virtually similar to the PL/SQL code:

set serveroutput on;
declare
l_count integer;
begin
for e in (select mgr,ename from emp) loop
select count(*) into l_count from emp
where e.mgr = empno and ename = ‘KING’;
if l_count != 0 then
dbms_output.put_line(e.ename);
end if;
end loop;
end;

To determine which clause offers better performance in rule-based optimization, consider how many rows the inner query will return in comparison to the outer query. In many cases, EXISTS is better because it requires you to specify a join condition, which can invoke an INDEX scan. However, IN is often better if the results of the subquery are very small. You usually want to run the query that returns the smaller set of results first.

Some people avoid the EXISTS clause because of the requirement to return a result from the query–even though the result is never used. Depending on personal style, people often use ‘X,’ 1, 0, or null. From looking at the EXPLAIN PLAN output, it appears that the optimizer throws out whatever value you enter and uses 0 all the time.

Category: Databases | Tags: ,  | Leave a Comment
Author:
Monday, July 27th, 2009

[Many of you might be aware of this, but to some it might be new and to others it will be refreshing to know. If you don’t fall into any of these categories please ignore.]

 Definition:

An interface defines the contract between class which is providing the functionalities (implementing class) and clients which is consuming the functionalities. It contains only the signatures or declaration of methods, delegates or events.

 An interface can be a member of a namespace or a class and can contain signatures of the following members:

 

Code Examples:

//Defines size, enumerators, and synchronization methods for all nongeneric

//collections.

public interface ICollection : IEnumerable

{       

    int Count { get; }    

    bool IsSynchronized { get; }

    object SyncRoot { get; }

    void CopyTo(Array array, int index);

}

 An interface can inherit from one or more base interfaces.

 The key to understanding interfaces might be to compare them with class. Although class has behavioral characteristics (methods), classes are more accurately classified as things as opposed to behaviors. And interfaces enable us to define behavioral characteristics, or abilities, and apply those behaviors to classes, irrespective of their hierarchy.

 

Code Examples:

//Defines a method to release allocated resources.

public interface IDisposable

{       

    void Dispose();

}

Here Dispose is a behavior which can be associated to classes irrespective of hierarchy by simply implementing this interface.

C# does not support Multiple-Inheritance, so consider defining interfaces to achieve an effect similar to that of multiple inheritances. This also means defining an interface if you need to support its functionality on types that already inherit from some other type. For example, IDisposable is implemented by types used in many different scenarios. Requiring classes to inherit from a base class to be disposable would make the class hierarchy too inflexible. Classes such as MemoryStream, which should inherit their stream-based contracts from their parent classes, would not be able to do so and also be disposable. 

We cannot inherit one value type from another and also all value types are implicitly inherited from ValueType. So define an interface if you need some common functionality to be supported by a set of value types or a set of types that includes some value types. 

Another common use of interface is in Strategy Pattern. The Strategy Pattern is a GOF (Gang of Four) behavioral pattern where the intent is to “…define a family of algorithms, encapsulate each one, and make them interchangeable”. (“Design Patterns” — Gamma, Help, Johnson, Vlissides)

There are three main parts to any strategy:

  1. Strategy: the interface that defines how the algorithm will be called.
  2. Concrete Strategy: the implementation of the strategy.
  3. Context: the object holding the Concrete Strategy.

Strategy lets the algorithm vary independently from clients that use it.

You can find more details on strategy pattern in following links: http://www.dofactory.com/Patterns/PatternStrategy.aspx  or http://en.wikipedia.org/wiki/Strategy_pattern

Note: Do favor defining abstract classes over interfaces in most of scenarios except the ones mentioned above. Reason being, in later versions of your library, you can safely add new members to classes; you cannot add members to interfaces without breaking existing code.

What needs to consider in designing interface?

  1. Do provide at least one type that is an implementation of an interface. This helps ensure that the interface is well designed and can be implemented without too much difficulty.
  2. Do not add members to an interface at the later version. Adding new members will break code that implemented the previous version of the interface. This is one of the main reasons why, in general and where possible, classes are preferable to interfaces.
  3. Avoid implementing interface members explicitly without having a strong reason to do so. One issue with explicit implementation is it members cannot be accessed through a class instance, but only through an instance of the interface.
  4. Consider implementing interface members explicitly if the members are intended to be called only through the interface.
  5. Consider implementing interface members explicitly to hide a member and add an equivalent member with a better name.
Category: .Net | Tags: ,  | Leave a Comment
Author:
Friday, July 24th, 2009

Introduction to SOA

We have been hearing the SOA €€œ the buzz word €€œ all the hype, for a long time now. Let us get into exploring the basics of SOA. This blog will focus on SOA, what it is, the advantages of SOA, the components involved.

 What is SOA

SOA refers to €œService Orientation Architecture€. SOA is a model of building distributed applications whose goal is to achieve loose coupling among interacting software agents.

SOA are very much present and used everywhere in real world. Let’s consider the case of CD playing service offered by CD player. To utilize the service offered by CD player , we need to insert the CD into the player. The advantages of the CD and the CD player being decoupled is the fact that , the same CD can be played in a different music system .At the same time other CDs can be played in the music system . Say , suppose the CD and and CD player were together as a single system, it would have been like that system would only play those set of songs and vice versa that these set of songs cannot be played in another CD player. This is a classical example of SOA in real world. According to OOPS, the data and the functionality related to an Entity are coupled, but in SOA is the data is decoupled from the functionality.

 

SOA   Advantages:

Implementation Advantages  

  • Reduce  Coupling of components  – thereby adding new services , removing  or modifying or replacing services can be done without major changes to the system
  •  Build Components/services which are reusable
  •  Leverage existing services, Eliminate redundancy
  • Integration and  Interoperability  of components
  • Availability of services across domain, across technology, across products in an enterprise, across platform, across the network.
  • Operational Efficiency

  

Business Advantages

  • On demand business:  Service-oriented architecture gives existing systems the flexibility and agility to respond to a business environment which is changing rapidly.   Decoupling of software components helps to achieve this.
  • Reduction in cost -  the reuse of services , maintenance cost of system built on SOA is low , leveraging existing  services
  • Increase on ROI €€œ  in the long term there will be considerable reuse of services at the enterprise level , the integration of products / services , low maintenance  cost , supporting customer/client requirements in shorter duration and make them happy and a lot more factors will help achieve Increase in ROI.

 

Architectural Components of SOA

 The components of a service-oriented architecture include:

  • Service providers. A service provider is a component or set of components that  basically provides a service €€œ a business function taking some predefined inputs and provides a defined output .
  • Service consumers. A service consumer is a set of components interested in using one or more of the services provided by service providers.
  • Service repository. A service repository contains the descriptions of the services. Service providers register their services in this repository and service consumers access the repository to discover the services being provided.

 

There are a lot of challenges that need to be taken care of after  choosing SOA during the software life cycle  such as  availability , security , reliable message transferring between consumer €€œ provider ,      choose Synchronous  /  Asynchronous services , chosing services , statelessness of the services , performance  ,expose only the interfaces to the consumer such that the consumer need not know the inner details of implementation .

Inspite of  all the challenges involved , the industry is adopting SOA for the advantages it offers.

Category: .Net | Tags: ,  | Leave a Comment
Author:
Tuesday, July 14th, 2009

Test automation can enable few testing tasks to be performed far more efficiently than could ever be done by testing manually and hence adding value to overall testing efforts.

Some of the benefits of automation tests/testing are listed below

  1. Regression tests. Most suitable to run regression (for existing features) tests on the latest version of the application. This is perhaps the most obvious task, particularly in an environment where frequent bug fixes are performed hence leading to frequent feature modifications. The effort involved in performing a set of regression tests should be minimal. Given that the tests already exist and have been automated to run on an earlier version of the application, it should be possible to select the tests and initiate their execution with just a few minutes of manual effort.
  2. Difficult manual tests. Perform tests which would be difficult or impossible to do manually. For instance, to perform a full-scale live test of an online system with 1000 users may be impossible, but the input from 1000 users can be simulated using automated tests. By having end users define tests that can be automatically replayed, user scenario tests can be run at any time even by technical people who do not understand the intricacies of the full business application.
  3. Consistency and repeatability of tests. Tests that are repeated automatically will be repeated exactly every time without fail. This gives a level of consistency to the tests which is very difficult to achieve manually. The same tests can be executed on different hardware configurations, using different operating systems, or using different databases. This gives a consistency of cross-platform quality for multi-platform products which is virtually impossible to achieve with manual testing. The good automated testing practice can also insure consistent standards both in testing and in development.
  4. Verifying invisible results. In manual testing, typical expected outcomes are the obvious things that are visible to the tester. However, there are cases where attributes that should be tested are not easy to verify manually. For example a graphical user interface (GUI) object may trigger some event that does not produce any immediate output or that is not visible to the tester. A test execution tool may be able to check that the event has been, triggered, which would not be possible to check without using a tool.
  5. Reuse of tests. Tests that are reusable across many releases or test cycles are best to automate. The effort put into deciding what to test, designing the tests, and building the tests can be distributed over many executions of those tests. Tests which will be reused are worth spending time on to make sure they are reliable. This is also true of manual tests, but an automated test would be reused many more times than the same test repeated manually.
  6. Earlier time to market. Once a set of tests has been automated, it can be repeated far more quickly than it would be manually, so the testing cycle time can be shorter.
  7. Increased confidence. Knowing that an extensive set of automated tests has run successfully, there can be greater confidence that there won’t be any unpleasant surprises when the system is released (providing that the tests being run are good tests!). In short, more thorough testing can be achieved with less effort, giving increases in both quality and productivity.

    We shall discuss about the challenges of automated tests/testing in the following blog!

    Author:
    Tuesday, July 14th, 2009

    Need REST from SOAP

    Yes, we are tried of using SOAP and badly in need of REST;  Till date we would have mostly come across web services being implemented using SOAP (Simple Object Access Protocol) as messaging protocol for exchanging structured information (XML was chosen as the standard message structure) over HTTP (transporting medium). Though it has its own advantages, may get cumbersome due to its verbose XML format by adding soap headers and other meta-datas, thereby making it slower and also failing to utilize the power of HTTP to the fullest.

    Lets REST

    REST (Representational State Transfer Protocol) on the other hand defines identifiable resources (URIs – uniform Resource Identifiers), and methods for accessing and manipulating the state of those resources (HTTP verbs). Resources are like objects, they clearly differentiate each state very similar as in OOPs where each real-world entity is identified as an object having their own state (method) and attributes (properties).Resources can be identified using a single identifier scheme, typically a URL or URI. Once you have a handle/access to the resource, you can invoke methods (any http verb) and interact with it.

    Few HTTP verbs,

    • GET: retrieve resource
    • POST: process resource
    • PUT: update resource representation
    • DELETE: delete resource

    REST requests are modeled after the way a web browser (client) sends requests to a web server, typically a request for the REST services mostly goes in through url with query strings or in POST data block.

    Typical REST request

    A typical REST request for calling a web method GetInfo which takes integer €˜empid’ as the parameter will look similar to

    http://isense.com/employeeprofile.asmx/GetInfo?empid=1

    Each request starts with the hostname

    http://isense.com

    After the hostname is the service name

    /employeeprofile/

    Next is the method name followed by a question mark (?), followed by the actual query parameters, which take the form argument=value, where the arguments and values can be URL encoded if required. Multiple parameters are separated by an ampersand (&).

    GetInfo?empid=1

    Note:

    1. Method name is case sensitive

    2. The order of method parameters is irrelevant and names are case insensitive.

    3. If a web method takes some complex parameters, for e.g.) like array,

    Public void SetNames(String [] empNames)

    Then at the client program while calling the method, we pass the values as

    http://localhost:3578/Service1.asmx/GetEmpInfo?empNames=Sethu&empNames=Ram&empNames=Kumar.

    The REST service is intelligent enough to group up the query string params with name empNames into a string[] of empNames.

    REST Implementation

    In order make the .Net web service application to work as RESTful services,

    1. We need to configure web config file to add the required HTTP verbs.

    <system.web>

    <webServices>

    <protocols>

    <add name=”HttpGet”/>

    <add name=”HttpPost”/>

    </protocols>

    </webServices>

    </system.web>

    2. Then we can go ahead and create normal web methods using c# .Net web service application as we do earlier.

    [WebMethod]

    public EmployeeList GetEmpInfo(int empid)

    Input:

    empid: required integer paramter.

    If  empid = 0, then it will return the details of all the employees of Isense.

    If  empid is any valid id number of the employee it would return his/her corresponding details.

    Output schema:

    EmployeeList: It’s basically a serialized list of employee object. (NAME and ID)

    <Employees>

    <Employee>

    <NAME>Anand</NAME>

    <ID>1</ID>

    </Employee>

    <Employee>

    <NAME>Abhishek</NAME>

    <ID>2</ID>

    </Employee>

    <Employee>

    <NAME>Jyothi</NAME>

    <ID>3</ID>

    </Employee>

    <Employee>

    <NAME>Sethuram</NAME>

    <ID>4</ID>

    </Employee>

    <Employees>

    3. When it comes to accessing these web methods, its not require to create a proxy or stub at the consuming client. We can invoke the web methods using simple HttpWebRequest and HttpWebResponse objects and call the required service url along with parameters as below,

    < http://localhost:3578/Service1.asmx/GetEmpInfo?empid=4>

    string result = string.Empty;

    string url = “http://localhost:3578/Service1.asmx/GetEmpInfo?empid=4“;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    request.Method = “GET”;

    using(HttpWebResponse response = HttpWebResponse)request.GetResponse())

    {

    using (Stream responseStream = response.GetResponseStream())

    {

    using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))

    {

    XmlDocument xmlDocument = new XmlDocument();

    xmlDocument.LoadXml(readStream.ReadToEnd());

    }

    }

    }

    Once we get the response output xml schema, we can load it either in XML DOM or parse it through a reader object.

    REST Advantages

    • Human readable formats and results.
    • They are stateless.
    • Light weight as purely http.
    • No security issues with firewalls
    • Relative ease and quick to develop.

    Companies using REST

    • Yahoo! – All Yahoo API’s Web Services uses REST including Flickr etc
    • Google – Google Adsense Search and Google Maps are two good examples for RESTful services implemented by Google
    • Amazon
    • EBay
    • del.ico.us

    I am sure this list to going to grow exponentially due to its simplicity to develop and ease of use.

    Rest of REST in Rest

    I hope I have thrown a bit of light on the RESTful design concepts. (I am sure REST will have a greater impact on the future of the World Wide Web). Here in this post, I have just briefed on the fundamentals of RESTful service, may be I can elaborate on the rest of RESTful design concepts in the rest of my blog posts to follow.

    Category: .Net | Tags: ,  | One Comment
    Author:
    Tuesday, July 14th, 2009

    Microsoft Code contract (or Microsoft Contracts) is a set of library (and tools) that you can download (for VS2008) from Microsoft Research. In VS2010, its built-in.

    According to Microsoft: €œCode Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.€

    You can learn more about how to use Code contracts, watch tutorial videos and download code contracts at: http://research.microsoft.com/en-us/projects/contracts/

    In this article I’ll show you how Code Contract (apart from all the uses stated on the site) could help us write better code.

    For those new to the subject, let me quickly tell you how code contract works. Basically, you can define a set of pre-conditions and post-conditions for your methods. For eg. €œthe method should not be called with null arguments€ or €œthe method should not return a negative integer€. At runtime, these pre-conditions are checked whenever the method is called and post-conditions are checked when the function returns. There’s one more type of condition called invariants which we’ll skip for now to keep things simple.

    The cool thing is, Code contracts also does a static analysis. i.e. you don’t have to execute your program to check validity of your contracts. Code contracts static analysis works at compile time and gives you most of the possible contract violation errors right at compilation.

    This is will make the developer aware of common pitfalls in the code and help him write better code; as you’ll see in the examples below.

    After you’ve installed code contracts, open VS2008 and create a class library project. Make sure you’ve enabled all Static Contract checking options in your Project Properties window:

    Code Contract

    Now lets try some code:

    public class CodeContractExmples
    {
    public string CapitalizeFirstLetter(string source)
    {
    string result=”";
    result = source.Substring(0, 1).ToUpper();
    result = result + source.Substring(1, source.Length – 1);
    return result;
    }
    }

    At first look, the programs looks fine. But a few second after you compile, you’ll see two code contract warnings:

    1) contracts: requires unproven: startIndex + length <= this.Length
    2) contracts: Possibly calling a method on a null reference ‘source’

    Code contracts is warning you that your method could fail if source is null or an empty string.
    We can easily fix this warning by checking for null or empty string:

    public string CapitalizeFirstLetter(string source)
    {
    string result=”";
    if (!string.IsNullOrEmpty(source))
    {
    result = source.Substring(0, 1).ToUpper();
    result = result + source.Substring(1, source.Length – 1);
    }
    return result;
    }

    This should get rid of the warnings. However, this may not be the best solution. Your method will return an empty string if called with a null. To prevent anyone from calling your method with a null or an empty string, you could specify a contract precondition. Add a reference to Microsoft Contract Library in your project and try the following code:

    public string CapitalizeFirstLetter(string source)
    {
    Contract.Requires(!string.IsNullOrEmpty(source));
    string result = “”;
    result = source.Substring(0, 1).ToUpper();
    result = result + source.Substring(1, source.Length – 1);
    return result;
    }

    Notice the first line in the method defines a pre-condition for your method. Lets try to call this method with a null. Add another method to your class:

    public void TestMyMethod()
    {
    string myName = null;
    this.CapitalizeFirstLetter(myName);
    }

    After you compile this, you’ll notice the warning on the method call tells you that the contract didn’t pass. Bingo.

    Lets try another example:

    public void CopyArray(string[] source, string[] dest)
    {
    Contract.Requires(source != null);
    Contract.Requires(dest != null);
    for (int i = 0; i < source.Length; i++)
    {
    source[i] = dest[i];
    }
    }

    As you can see I’ve already taken care that source and dest are not given as null. After you compile this you’ll still see a contract warning on the line inside the for loop:

    contracts: Array access might be above the upper bound

    The for loop condition makes sure that I don’t exceed the array bounds of  Ã¢‚¬Å“source€ array, but what if the dest array is smaller than the source array. Trouble. Code contract was clever enough to point this scenario. You should add another precondition:

    Contract.Requires(dest.Length >= source.Length);

    Here’s another example:

    public double CalculatePercentage(int scoredMarks, int totalMarks)
    {
    double percentage = scoredMarks / totalMarks * 100;
    return Math.Round(percentage, 2);
    }

    Again everything looks ok at first glance, but Code contract will warn you about a possible divide by zero error. What if totalMarks is given as 0. You can easily prevent this by adding a precondition:

    public double CalculatePercentage(int scoredMarks, int totalMarks)
    {
    Contract.Requires(totalMarks > 0);
    double percentage = scoredMarks / totalMarks * 100;
    return Math.Round(percentage, 2);
    }

    I can go on with such examples. But I guess you got the point. Code contract static analysis detects some (not all) common contract violations and so that the developer can take care them before he faces these issues at runtime. Also writing pre-conditions in your method prevents the callers from passing invalid arguments. Post-conditions and Invariants are similarly helpful to define the expected behaviors. You can learn more about them and code contract from the website mentioned above.

    Author:
    Tuesday, July 14th, 2009

    Versioning of Database with Visual studio Team system Database Edition

    With the Visual studio team system database edition, working with database , making changes to it, tracing, maintaining and comparing the changes has become more efficient and easy as we do it with rest of the projects.

    The diagram below explains in short as to how we can achieve version control using the Database edition.

    As show in the above diagram, the first step is to create the database project.

    Steps to be followed to create a database project:

    1. Open visual studio team system, click on File à New à Project
    2. Select Database Projects option from the new project dialog.
    3. Select SQL server 2005 option and specify the project name and then click the ok button as show below.

    Create database

    Following these steps will create the database project.

    Once the project is created, the next step is to get the schema for the database. We can import the schema from the existing database into the newly created database project. What the system does is it parses database items such as tables, views, sp’s which intern extracts the database objects from the script files that make up the database project. This functionality is similar to the import option where in we import database objects from existing database scripts.

    Steps to be followed to import the schema to the database project:

    1. Right click on the Database Project created in the solution explorer and click on Import Database schema.
    2. In the Import Database schema dialog click on New connection Button, we get the connection properties screen in which we can select the SQL server with which we want to connect and give the credentials and then finally enter the database name from which we want to import data and click on the ok button and the click finish to import the schema as shown below.

    Import schema

    Once these steps are followed, we will have the selected database schema imported into our database project. Visual studio also provides a schema view, in which we get the database representation very similar to the object explorer in the SQL server.

    After importing the schema the next step is to add the project into version control, now we can build the project to ensure that the database schema is imported properly and then check in this project into the TFS/VSS.

    Once the project is checked into the version control, we are no longer connected to the actual database, i.e. we are in the disconnected mode now. Now we can modify and make changes as we want to the database project. Also as it is version controlled, each database professional can synchronizes their development environment to version control. They can check out files as they are changed and develop and test those changes in isolation. Changes made to their copy of the database project are deployed only to their isolated development environment. After a team member generates realistic test data and runs unit tests against a private copy of the database, the team member checks the changes into version control. Other team members can obtain tested changes from version control.

    When all the developers are done with their changes and the database project is ready for deployment, the next step would be to deploy these changes back to the Production database.

    Steps to be followed to deploy a project back to the production server are as follows:

    1. In the solution explorer right click on project and select project properties.
    2. In the properties window, click on Build option. In build option we have target database settings. Click on the Edit button next to target connection, we get the connection properties window and here we need to select the SQL server and the database where we want to deploy the changes to. Then click on the ok button as shown below.
    3. Then again go to solution explorer and right click on the project and click on deploy to deploy the changes back to the production database. Deploying to database

    Following these steps will deploy the chages back to the production database. Visual studio team system database edition has many features, some of which are listed below.

    • Compare schemas or data between databases.
    • Develop and run unit tests against database objects.
    • Generate predictable, representative test data without compromising sensitive production data.
    • Rename database tables, columns, views, or other objects and propagate those changes to the rest of the database project, which includes associated unit tests, views, stored procedures, triggers, and so on.
    • Create, edit, validate, execute, and analyze scripts and queries.

    Category: .Net | Tags: ,  | 2 Comments
    Author:
    Tuesday, July 14th, 2009

    What is Enterprise Application?
    Enterprise Applications are software which provides business logic support functionality for an enterprise, typically in commercial organizations, which aims to improve the enterprise’s productivity and efficiency.

    Characteristics of enterprise software:
    Characteristics of enterprise software are performance, scalability, and robustness. Enterprise software typically has interfaces to other enterprise software.

    Services provided by enterprise software are typically business-oriented tools such as online shopping and online payment processing, interactive product catalogue, automated billing systems, security, content management, CRM, ERP, Business Intelligence, HR Management, Manufacturing, EAI etc.

    What is Scalability?
    There are a number of different aspects of scalability. It always starts with performance, code maintainability, fault tolerance, and the availability of programming staff.

    Why people has negative impression that PHP is only for small scale web-sites?
    PHP is a language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn’t require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.

    PHP is an open source programming language that is widely popular on the web. However because PHP so popular in shared hosting environments, many people have an impression that PHP is only for small scale web-sites. This is patently untrue, and PHP is in use in many large scale web sites such as Yahoo, wikipedia and Lufthansa Online Ticketing for the creation of large web applications such as IMP.

    Enterprises want to have specific assurances about a web technology they use in the following areas:

    • performance and fast development
    • reliability and security
    • extensibility – able to use industry standards to communicate with other software systems.
    • scalability – able to add additional servers as the load increases.
    • load balancing – ability to distribute the load so no single server is overloaded
    • high availability – ability to survive failure of server components transparently.

    Conclusion:
    To achieve high performance and scalability – it not only depend on language, it also depend on the developers.

    I will give my next article about How to make our PHP code excellent.

    Author:
    Tuesday, July 14th, 2009

    What is Hibernate ?

    Hibernate is an (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves Object-Relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

    Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables.
    In the Java world, ORM‘s first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class level attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are “one to one”, “one to many” or “many to many”.

    Productivity

    O/R mapping help developer get rid of writing complex and tedious SQL statement, developer no more need of JDBC APIs for result set or data handling. It makes developer more concentrate on the business logic.

    Maintainability

    O/R mapping help reduce lines of code, it makes system more understandable. It emphasizes business logic rather than persistence work (SQLs). More important, a system with less code is easier to refactor.

    Portability

    O/R mapping abstracts our application away from the underlying SQL database and sql dialect. Switching to other SQL database requires few changes in Hibernate configuration file (Write once / run-anywhere)

    Why Hibernate ?

    The reasons are plenty,weighing in favor of Hibernate clearly.

    -Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.

    -The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries.

    -High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution.

    -Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.

    -EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.

    Hibernate Framework Objects.

    a) Session Factory

    Represented by org.hibernate.SessionFactory class

    A factory for Session and a client of ConnectionProvider

    Typically one for each database

    b) Session

    Represented by org.hibernate.Session

    The life of a Session is bounded by the beginning and end of a logical      transaction.

    A session represents a persistence context Handles life-cycle operations-    create, read and delete operations – of persistent objects

    Wraps a JDBC connection  -   Factory for Transaction

    c) Transaction

    Represented by org.hibernate.Transaction

    A single-threaded, short-lived object used by the application to specify   atomic units of work

    A Session might span several Transactions in some cases.

    State Transitions

    I) Transient instances may be made persistent by calling save(), persist() or    saveOrUpdate()

    II) Persistent instances may be made transient by  calling delete()

    III) Any instance returned by a get() or load() method is persistent

    IV) Detached instances may be made persistent by  calling update(),    saveOrUpdate(), lock() orreplicate()

    V) The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

    Configuration Hibernate/Java

    1.Write domain classes (as POJO classes)

    Example.java

    public class Example implements Serializable {

    private int id;

    private String name;

    public Example () {

    }

    public Example (int id, String name) {

    this.id = id;

    this.name = name;

    }

    public int getId() {

    return id;

    }

    public void setId(int id) {

    this.id = id;

    }

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    }

    2.Write or generate Hibernate mapping files for the domain classes

    Example.hbm.xml

    <?xml version=”1.0″?>

    <!DOCTYPE hibernate-mapping PUBLIC

    “-//Hibernate/Hibernate Mapping DTD 3.0//EN”

    “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

    <hibernate-mapping>

    <class name=”Example” table=”TabExample“>

    <id name=”id”>

    <generator class=”increment”/>

    </id>

    <property name=”name” column=”cname”/>

    </class>

    </hibernate-mapping>

    3.Write Hibernate configuration file (perapplication)

    hibernate.cfg.xml

    <?xml version=’1.0′ encoding=’utf-8′?>

    <!DOCTYPE hibernate-configuration

    PUBLIC “-//Hibernate/Hibernate Configuration DTD//EN”

    “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

    <hibernate-configuration>

    <session-factory>

    <property

    name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

    <property

    name=”connection.url”>jdbc:mysql://localhost:3306/test</property>

    <property name=”connection.username”></property>

    <property name=”connection.password”></property>

    <property name=”show_sql”>true</property>

    <property

    name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

    <property name=”myeclipse.connection.profile”>mysql</property>

    <mapping resource=”Example.hbm.xml” />

    </session-factory>

    </hibernate-configuration>

    4. Main class to run the application

    public class TestExample {
    public static void main(String[] args) {
        Example oneexample = new Example ();
        example.setName("James");
        Example twoexample = new Example ();
        example.setName("James");
        createExample(oneexample);
        createExample (twoexample);
        deleteExample (oneexample);
        twoexample.setName("UpdateJames");
        updateExample (v);
      }
      private static void deleteExample (Example example) {
        Transaction tx = null;
       Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
          tx = session.beginTransaction();
          session.delete(example);
          tx.commit();
        } catch (RuntimeException e) {
          if (tx != null && tx.isActive()) {
            try {
              tx.rollback();
            } catch (HibernateException e1) {
            }
            throw e;
          }
        }
      }
      private static void createExample (Example example) {
        Transaction tx = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
          tx = session.beginTransaction();
          session.save(example);
          tx.commit();
        } catch (RuntimeException e) {
          if (tx != null && tx.isActive()) {
            try {
              tx.rollback();
            } catch (HibernateException e1) {
                      }
           throw e;
          }
        }
      }
    
       private static void updateExample(Example example) {
        Transaction tx = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
          tx = session.beginTransaction();
          session.update(example);
          tx.commit();
        } catch (RuntimeException e) {
          if (tx != null && tx.isActive()) {
            try {
              tx.rollback();
            } catch (HibernateException e1) {
            }
            throw e;
          }
        }
      }
    }
    Category: Java | Tags: ,  | One Comment
    Author:
    Tuesday, July 14th, 2009

    Design Patterns provide a proven solution for a given problem and every programmer should know a few of the patterns. One such pattern in threading is “Worker Thread” pattern, which gets implemented in BackgroundWorker component in .NET.  Threading itself, is one such programming concept that many fear to trespass, so imagine trying to write some thread plumbing code that spawns a worker thread from a thread pool! And not to mention the typical threading issues such as dead lock, thread safely etc. Thankfully, .NET team has implemented the worker thread pattern in the component, System.ComponentModel.BackgroundWorker.

    Features of BackgroundWorker -

    A standard protocol for reporting progress, completion and cancellation

    • Uses thread pool for worker threads
    • An implementation of IComponent allowing it be sited in the Visual Studio Designer
    • Exception handling on the worker thread
    • Ability to update Windows Forms and WPF controls in response to worker
    Usage -

    Drop the BackgroundWorker component from the tool box on to the windows form (or WPF window), write a delegate for the events Dowork, ProgressChanged, RunWorkerCompleted. Call the method RunWorkerAsync. That’s it! You are up and running a threaded application!

    Events –
    DoWork - This event handler is run on a new worker thread when the operation begins.

    ProgressChanged – This event handler is raised when the progress of the task has to be reported back. This is optional, so the programmer has to make call to ReportProgress, from DoWork event, to raise this particular event.

    RunWorkerCompleted Event is raised when the worker thread completes its job, either with success, faliure or cancellation.

    Interesting point is, BackroundWorker is not a sealed class and provides an virtual OnDoWork method, which means, technically this component could be extended to implement a new threading pattern ( Fire and Forget (background thread), Periodic (Timer), IO thread, Producer/Consumer, Worker thread (work queue) ).

    Properties -

     WorkerReportsProgress – Set this property to true, if you want the ProgressChanged event to work, when set false, InvalidaOperationException is raised when ProgressChanged event is called.

    WorkerSupportsCancellation – Set this property to true, if you want the thread to be canclled during an operation. For cancelling the worker thread, main thread has to call the method CancelAsync() on the worker thread. In the worker thread’s DoWork() event, check for CancellationPending DoWorkEventArgs to Cancel and exit out of DoWork method.

    Code Sample -

    Setting up the BackgroundWorker -

     backgroundWorker1.WorkerReportsProgress = true;

    backgroundWorker1.WorkerSupportsCancellation = true;

    backgroundWorker1.DoWork += new DoWorkEventHandler

    (backgroundWorker1_DoWork);

    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler

    (backgroundWorker1_ProgressChanged);

    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

     

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

    {

    for (int i = 0; i < 100; i++)

    {

              i++;

    backgroundWorker1.ReportProgress(i);

    if (backgroundWorker1.CancellationPending)

    {

                       e.Cancel = true;

    return;

                }

          }

    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

    {

    progressBar1.Value = e.ProgressPercentage;

    }

    Final Words - 

    BackgroundWorker is a scalable worker thread pattern as I have seen it performing well, in a windows service that spawns a number of worker threads to download media content from the internet. All in all, BackgroundWorker provides a good threading implementation minus all the thread plumbing code.

    Category: .Net | Tags: ,  | Leave a Comment