Friday, September 08, 2006

Increase Performance in ADO.NET

Here is a consolidated list of how you can improve the performance of your .NET apps:
1. Design your data access layer based on how the data is used.
In larger applications, it’s always better to go for a separate Data Access Layer (DAL) to abstract the underlying data store complexity and to provide a logical separation. Having the data access logic in the same presentation layer may increase performance but at the cost of maintainability.
You can use the Microsoft Application Blocks for simplifying your tasks of Data Access and Exception handling. (I personally prefer this)

2. Cache your data to avoid unnecessary round trips and network overhead.
Try to cache data that is used across your application, in the layer that is close to the consumer of data. This will reduce the latency in network to fetch data. Note that if your data in cache needs to be updated too frequently, then better you don’t cache that data.

3. Acquire late, release early.
Open database connections right only when you need them. Close the database connections as soon as you are finished. Acquire locks late, and release them early.

4. Close disposable resources.
Make sure that you call either the Dispose or Close method on resources that are disposable, as soon as you are finished with using the resource.

5. Reduce round trips.
· If you have some 3 or 4 SQL statements, try to use batch sql statements in a stored procedure to decrease round trips.
· Use ExecuteScalar method for getting a single result.
· Use ExecuteNonQuery method when you want to execute any DDL statement.
· Use connection pooling to help avoid extra round trips. By reusing connections from a connection pool, you can avoid the round trips that are associated with connection establishment and authentication.

6.Return only the data you need.
Evaluate the data that your application actually requires and return only that data. This will minimize the bandwidth consumption in the network.

7. Use Windows authentication.

From a security perspective, use Windows authentication instead of SQL authentication. This ensures that credentials are not passed over the network, database connection strings do not contain credentials, and you can apply standard Windows security policies to accounts. Remember to use connection pooling with your connection.

8. Use stored procedures.
Avoid embedded SQL statements and use Store Procedures (SP) instead. This has the following advantages:
· A Logical separation of Data access code from your Business Logic code
· Queries can be optimized for performance from SQL server
· Deployment becomes easier as, for any change in SP you don’t need to redeploy you application.
· SPs allow the batch execution of SQL commands
· You can impose specific restrictions on selected stored procedures for security reasons. This is very difficult to be done from embedded SQL.
· You can avoid the most dangerous SQL Injection by using parameterized SPs.

9. Consider how to handle exceptions.
You can use try/finally blocks to ensure that connections and other resources are closed, regardless of whether exceptions are generated or not. The best way for abstracting all exceptions from user is to log them to a file or Windows Event log.

10. Use appropriate normalization.
You may want a normalized database to minimize data duplication but be aware that you don’t over-normalize. This can affect the performance and scalability of your application
The above list is purely based on my working experience and there are many more points to add to this, which I’ll be adding in the next part of this article.

Get more information

Tags: ado.net, performance ado.net, DAL, application blocks, cache, round trip, network, database, database connections, stored procedures, normalization

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Thursday, September 07, 2006

Finding the size of an HTML Element

There are so many variables that affect the size of an element -- content length, CSS rules, font family, font size, line height, text zooming ... the list goes on. Add to this the fact that browsers interpret CSS dimensions and font sizes inconsistently, and you can never predict the dimensions at which an element will be rendered. The only consistent way to determine an element's size is to measure it once it's been rendered by the browser.

Solution

You can tell straight away that it's going to be useful to know exactly how big an element is. Well, the W3C can't help: there's no standardized way to determine the size of an element. Thankfully, the browser-makers have more or less settled on some DOM properties that let us figure it out.

Although box model differences mean that Internet Explorer includes padding and borders inconsistently as part of an element's CSS dimensions, the offsetWidth and offsetHeight properties will consistently return an element's width -- including padding and borders -- across all browsers.

Let's imagine that an element's dimensions were specified in CSS like this:

Example 13.15. find_size_element.css
#enterprise
{
 width: 350px;
 height: 150px;
 margin: 25px;
 border: 25px solid #000000;
 padding: 25px;
}

We can determine that element's exact pixel width in JavaScript by checking the corresponding offsetWidth and offsetHeight properties:

Example 13.16. find_size_element.js (excerpt)
var starShip = document.getElementById("enterprise");
var pixelWidth = starShip.offsetWidth;
var pixelHeight = starShip.offsetHeight;

In Internet Explorer 6, Opera, Mozilla, and Safari, the variable pixelWidth will now be set to 450, and the variable pixelHeight will be set to 250. In Internet Explorer 5/5.5, pixelWidth will be 350 and pixelHeight 150, because those are the dimensions at which the broken box model approach used in those browsers will render the element. The values are different across browsers, but only because the actual rendered size differs as well. The offset dimensions consistently calculate the exact pixel dimensions of the element.

If we did not specify the dimensions of the element, and instead left its display up to the default block rendering (thus avoiding the box model bugs), the values would be comparable between browsers (allowing for scrollbar width differences, fonts, etc.).

Get more information

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Getting the Scrolling position using Javascript

Page scrolling is one of the least-standardized properties in JavaScript: three variations are now in use by different versions of different browsers. But with a few careful object tests, we can reliably get a consistent value.

Solution

There are three ways of getting this information. We'll use object tests on each approach, to determine the level of support available:

Example 7.8. get-scrolling-position.js (excerpt)
function getScrollingPosition()
{
 var position = [0, 0];
 if (typeof window.pageYOffset != 'undefined')
 {
   position = [
       window.pageXOffset,
       window.pageYOffset
   ];
 }
 else if (typeof document.documentElement.scrollTop
     != 'undefined' && document.documentElement.scrollTop > 0)
 {
   position = [
       document.documentElement.scrollLeft,
       document.documentElement.scrollTop
   ];
 }
 else if (typeof document.body.scrollTop != 'undefined')
 {
   position = [
       document.body.scrollLeft,
       document.body.scrollTop
   ];
 }
 return position;
}

The function can now be called as required. Here's a simple demonstration, using a window.onscroll event handler, that gets the figures and writes them to the title bar:

Example 7.9. get-scrolling-position.js (excerpt)
window.onscroll = function()
{
 var scrollpos = getScrollingPosition();
 document.title = 'left=' + scrollpos[0] + ' top=' +
     scrollpos[1];
};

The Problem with scroll

scroll is not the most reliable of events: it may not fire at all in Konqueror or Safari 1.0, or when the user navigates with a mouse wheel in Firefox. And if it does fire, it may do so continually and rapidly (as it does in Internet Explorer), which can be slow and inefficient if the scripting you set to respond to the event is very complex.

If you have difficulties of this kind, you may find it better to use the setInterval function instead of an onscroll event handler. setInterval will allow you to call the function at a predictable interval, rather than in response to an event.

window.setInterval(function()
{
 var scrollpos = getScrollingPosition();
 document.title = 'left=' + scrollpos[0] + ' top=' +
     scrollpos[1];
}, 250);

Discussion

The only real complication here is that IE 5 actually does recognize the documentElement.scrollTop property, but its value is always zero, so we have to check the value as well as looking for the existence of the property.

Otherwise, it doesn't really matter to us which browser is using which property; all that matters is that our script gets through one of the compatibility tests and returns a useful value. However, the properties used by each browser are shown here for reference:

  • window.pageYOffset is used by Firefox and other Mozilla browsers, Safari, Konqueror, and Opera.
  • document.documentElement.scrollTop is used by IE 6 in standards-compliant mode.
  • document.body.scrollTop is used by IE 5, and IE 6 in "Quirks" mode.

This list doesn't tell the complete story, but it's intended primarily to describe the ordering of the tests. More recent Mozilla browsers (such as Firefox) also support documentElement.scrollTop and body.scrollTop, by the same rendering mode rules as IE 6. Safari and Konqueror support body.scrollTop in either mode. Opera supports all three properties in any mode!

But none of this is important for you to know -- browser vendors add these multiple properties to allow for scripts that are unaware of one property or another, not to provide arbitrary choices for the sake of it. From our perspective, the important point is to settle on a set of compatibility tests that ensures our script will work as widely as possible.

Get more information

Tags: scroll position, javascript, javascript code, mouse position, browsers, page scrolling, scrolltop

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Communicating between Frames - HTML

If you're working in a framed environment, it may be necessary to have scripts communicate between frames, either reading or writing properties, or calling functions in different documents.

If you have a choice about whether or not to use frames, I'd strongly advise against doing so, because they have many serious usability and accessibility problems, quite apart from the fact that they're conceptually broken (they create within the browser states that cannot be addressed). But as with your use of popups, in some cases you may not have a choice about your use of frames. So if you really must use them, here's what you'll need to do.

Solution

Let's begin with a simple frameset document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
<html>
 <head>
   <title>A frameset document</title>
 </head>
 <frameset cols="200, *">
   <frame src="navigation.html" name="navigationFrame">
   <frame src="content.html" name="contentFrame">
   <noframes>
     <p>This frameset document contains:</p>
     <ul>
       <li><a href="navigation.html">Site navigation</a></li>
       <li><a href="contents.html">Main content</a></li>
     </ul>
   </noframes>
 </frameset>
</html>

We can use four references for cross-frame scripting:

  • window or self refers to the current framed page.
  • parent refers to the page that contains the frame that contains the current page.
  • top refers to the page at the very top of the hierarchy of frames, which will be the same as parent if there's only one frameset in the hierarchy.
  • The frames collection is an associative array of all the frames in the current page.

Let's say we have a script in contentFrame that wants to communicate the page in navigationFrame. Both pages are contained in a single frameset -- the only one in the hierarchy -- so we could successfully make any of the following references from within contentFrame:

  • parent.frames[0]
  • top.frames[0]
  • parent.frames['navigationFrame']
  • top.frames['navigationFrame']

The frames collection is an associative array (like the forms collection we saw in Chapter 6, Processing and Validating Forms), so each element can be accessed by either index or name. It's generally best to use the name (unless you have a good reason not to) so that you won't have to edit your code later if the frame order changes. By the same token, parent references in a complex nested frameset can change if the hierarchy changes, so I generally recommend that developers always start referencing from top. Of the above options, the reference I prefer, then, is top.frames['navigationFrame'].

Now that we have a reference to the frame, we can call a function in the other framed page:

Example 7.6. frames-navigation.js (excerpt)
var navframe = top.frames['navigationFrame'];
navframe.callMyFunction();

Alternatively, we can get a reference to the other framed document, and work with the DOM from there:

Example 7.7. frames-navigation.js (excerpt)
var navdoc = navframe.document;
var menu = navdoc.getElementById('menulist');

Discussion

Communication between frames is only allowed for documents in the same domain -- for security reasons, it's not possible to work with a document that was loaded from a different domain than the script. It wouldn't do, for example, for a malicious site owner to load a site that you visit regularly into a frame, and steal the personal data you enter there.

In fact, some browsers let users disallow all scripts from communicating between frames, just to eradicate any possibility of a cross-site scripting vulnerability, and there's no way to work around this preference if your script finds itself running in a browser so configured.

If you do have users who are complaining of problems (and they can't or won't change their settings to allow cross-frame scripting), the safest thing to do is simply to avoid cross-frame scripting altogether.

Get more information

Tags: frames, html frames, communicate frames, popups, frameset, document, window, parent, top, contentframe, navigation, domain, browsers, vulnarability, cross-site scripting, cross-frame scripting

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Problems with PopUp Windows and Solutions to tackle

Using Popup Windows

Should you use popup windows? The most considered answer I have is this: not if you can help it. Popup windows have gained a bad reputation from marketers' aggressive use of them, but even requested popups can be barriers to good usability.

I won't say that popups are never appropriate, but I will say that they're seldom so. Nevertheless, there are situations where popping open a new window is arguably the most appropriate solution: an online survey might be one example, as the format may make the content more approachable; DHTML games are another, as the viewport may need to be of a known size.

I'll qualify my opinion by discussing the problems that popups create, then providing a pragmatic method for using them that mitigates these problems as much as possible.

What's Wrong with Popups?

The main problem with most popup window scripts is that they don't consider the needs of the user?they address only the needs of the designer. The results? We've all seen them:

  • popups that are generated from links, though those links do nothing when scripting is not available
  • popup windows that don't have a status bar, so you can't necessarily tell whether the document has loaded or stalled, is still loading, etc.
  • popups that don't give users the ability to resize the window, and popups that fail to generate scrollbars for content that might scale outside the window
  • windows that are "chromeless," or open to the full size of the user's screen

These issues are not just questions of usability, but of accessibility as well. For example, screen-reader users may not be notified by their devices that a new window has opened. This could obviously cause confusion if they then attempted to go back in the browser history (they can't). The same thing might happen for a sighted user if a window opens at full-size: you and I may be familiar with using the taskbar to monitor open windows, but not all computer users are -- they may not even realize that a new window has popped up.

If you're going to use popups, looking out for issues like these, and being generally sensitive to their impacts, will make your popups friendlier to users, and less of a strain on your conscience.

Also, bear in mind that, from a developer's perspective, popup windows are not guaranteed to work: most browsers now include options to suppress popup windows, and in some cases, suppression occurs even if the popup is generated in response to a user event.

You may be able to allow for this as you would for situations in which scripting was not supported: by ensuring that the underlying trigger for the popup still does something useful if the popup fails. Or you might have your code open a window and then check its own closed property, to see if it's actually displayed (we'll look at this technique in the next solution).

But neither of these approaches is guaranteed to work with every browser and popup blocker out there, so for this as much as the usability reasons, it's simpler and better to avoid using popups whenever you can.

How Do I Minimize the Problems?

What we need to do is establish some golden rules for the ethical use of popups:

  • Make sure any triggering link degrades properly when scripting is not available.
  • Always include the status bar.
  • Always include a mechanism to overflow the content: either allow window resizing, or allow scrollbars to appear, or both.
  • Don't open windows that are larger than 640x480 pixels. By limiting the size of popups, you ensure that they're smaller than users' primary windows on the vast majority of monitors. This increases the likelihood that the user will realize that the popup is a new window.

Solution

Here's a generic popup function that's based on the guidelines above:

Example 7.1. make-popup.js (excerpt)
function makePopup(url, width, height, overflow)
{
 if (width > 640) { width = 640; }
 if (height > 480) { height = 480; }
 if (overflow == '' || !/^(scroll|resize|both)$/.test(overflow))
 {
   overflow = 'both';
 }
 var win = window.open(url, '',
     'width=' + width + ',height=' + height
     + ',scrollbars=' + (/^(scroll|both)$/.test(overflow) ?
     'yes' : 'no')
     + ',resizable=' + (/^(resize|both)$/.test(overflow) ?
     'yes' : 'no')
     + ',status=yes,toolbar=no,menubar=no,location=no'
 );
 return win;
}

As well as limiting the window size, this script refuses to create a popup that doesn't have an overflow, so if you don't specify "scroll", "resize", or "both" for the overflow argument, the default setting of "both" will be used.

The Ternary Operator

This script uses a shortcut expression called a ternary operator to evaluate each of the overflow options. The ternary operator uses ? and : characters to divide the two possible outcomes of an evaluation, and is equivalent to a single pair of if..else conditions. Consider this code:

if (outlook == 'optimistic') { glass = 'half-full'; }
else { glass = 'half-empty'; }

That code is equivalent to the markup below:

glass = (outlook == 'optimistic' ? 'half-full' :
   'half-empty');

The parentheses are not required, but you may find they make the expression easier to read. For more about this and other useful shortcuts, see Chapter 20, Keeping up the Pace.

Once you have the popup function in place, you can call it in a variety of ways. For example, you could use a regular link:

Example 7.2. make-popup.html (excerpt)
<a href="survey.html" id="survey_link">Online survey</a>

If scripting is not available, this will work just like any other link, but if scripting is available, the script can trigger a click event handler that passes its href to the makePopup function, along with the other settings. The return value of the handler depends on whether or not the window is actually opened; browsers that block the popup will follow the link as normal:

Example 7.3. make-popup.js (excerpt)
document.getElementById('survey_link').onclick = function()
{
 var survey = makePopup(this.href, 640, 480, 'scroll');
 return survey.closed;
};

In general, if you have a script that requires that a window be generated, you can call the makePopup function directly with a URL:

var cpanel = makePopup('cpanel.html', 480, 240, 'resize');

If you need to close that window later in your script, you can do so by using the close method on the stored window reference:

cpanel.close();

Get more information

Tags: popup windows, dhtml, new window, chromeless, browser history, popup blocker, status bar, overflow, ternary operator, script, javascript, url, function, link, click event, trigger, scripting

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Javascript Limitations

JavaScript is most commonly used as a client-side language, and in this case the "client" refers to the end-user's web browser, in which JavaScript is interpreted and run. Since JavaScript does not have access to the server environment, there are many tasks that, while trivial when executed in PHP, simply cannot be achieved with JavaScript: reading and writing to a database, for example, or creating text files. But since JavaScript does have access to the client environment, it can make decisions based on data that server-side languages simply don't have, such as the position of the mouse, or the rendered size of an element.

Security Restrictions

As JavaScript operates within the realm of highly sensitive data and programs, its capabilities have been restricted to ensure that it can't be used maliciously. As such, there are many things that JavaScript simply is not allowed to do. For example, it cannot read most system settings from your computer, interact directly with your hardware, or cause programs to run.

Also, some specific interactions that would normally be allowed for a particular element are not permitted within JavaScript, because of that element's properties. For example, changing the value of a form <input>
is usually no problem, but if it's a file input field (e.g., <input type="file">), writing to it is not allowed at all -- a restriction that prevents malicious scripts from making users upload a file they didn't choose.

There are quite a few examples of similar security restrictions, which we'll expand on as they arise in the applications we'll cover in this book. But to summarize, here's a list of JavaScript's major limitations and security restrictions, including those we've already seen. JavaScript cannot:

  • open and read files directly (except under specific circumstances, as detailed in Chapter 18, Building Web Applications with JavaScript).
  • create or edit files on the user's computer (except cookies [11], which are discussed in Chapter 8, Working with Cookies).
  • read HTTP POST data.
  • read system settings, or any other data from the user's computer that is not made available through language or host objects (Host objects are things like window and screen, which are provided by the environment rather than the language itself.)
  • modify the value of a file input field.
  • alter a the display of a document that was loaded from a different domain.
  • close or modify the toolbars and other elements of a window that was not opened by script (i.e., the main browser window).

Ultimately, JavaScript might not be supported at all.

It's also worth bearing in mind that many browsers include options that allow greater precision than simply enabling or disabling JavaScript. For example, Opera [12] includes options to disallow scripts from closing windows, moving windows, writing to the status bar, receiving right-clicks ... the list goes on. There's little you can do to work around this, but mostly, you won't need to?such options have evolved to suppress "annoying" scripts (status bar scrollers, no-right-click scripts, etc.) so if you stay away from those kinds of scripts, the issue will come up only rarely.

Get more information

Tags: javascript, javascript limitations, security restrictions, cookies, HTTP POST, opera

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Exceptions Best Practices

Java provides an efficient way to handle unexpected conditions that can occur in the program. When there is an error or bug in the program then the program terminates as soon as an error is encountered leaving the program in an in consistent state, to avoid this Java makes use of Exception Handling mechanism to a great advantage so that when ever there is an exceptional condition then the program handles it gracefully and continues program execution.

The whole concept of exceptions/errors is handled by the java.lang.Throwable class. It has two subclasses - Error and Exception. We generally need not handle Errors, they are handled by JVM. Example of Error is OutOfMemoryError.

Exceptions are of two types -Checked exceptions and Unchecked exceptions.

Checked exceptions should either be declared in the throws clause or caught  in the catch block. Unchecked exceptions need not be declared in the throws clause but can to be caught in the catch clause.

Optimization techniques in Exceptions

  • In a catch block avoid using the generic class Exception. For each try block use specific catch blocks based on what can go wrong in your code.
  • Do not use Exception handling for anything other than exception handling like to control the flow of your program.
  • Whenever you are using a throws clause always use the specific subclass of Exception like FileNotFoundException rather than using throws Exception.
  • Use exception handling generously-Very little overhead is imposed by using exception handling mechanism unless an exception occurs. But when an exception occurs it imposes an overhead in terms of execution time.
  • Always use the finally block to release the resources like a database connection, closing a file or socket connection etc. This  prevents resource leaks even if an exception occurs.
  • When using method calls always handle the exceptions in the method where they occur, do not allow them to propagate to the calling method unless it is specifically required. It is efficient to handle them locally since allowing them to propagate to the calling method takes more execution time.
  • Do not use Exception handling in loops. It is better to place loops inside try/catch blocks than vice versa. Here is an code snippet that gives bench mark.

Key Points

  1. Be specific while handling the exception in your catch block.
  2. Do not use Exception Handling to control programming flow.

Get more information

Tags: java exceptions, handle exceptions, try block, method calls, finally block

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Loops Best Practices

Loops provide efficient way for repeating a piece of code as many times as required. Java has three types of loop control structures they are : for loop, while loop and do-while loop. The for loop is used when we know in advance how many iterations are required. The while loop is used when we do not know in advance the number of iterations required so each time before entering the loop the condition is checked and if it is true then the loop is executed. The do-while loop is always executed at least once and then the condition is checked at the end of the loop. Loops have a considerable effect on the performance of the program let us look at some points that focus on optimizing while using the loop control structures.

Optimization techinques in loops

  • Always use an int data type as the loop index variable whenever possible because it is efficient when compared to using byte or short data types. because when we use byte or short data type as the loop index variable they involve implicit type cast to int data type.
  • When using arrays it is always efficient to copy arrays using System.arraycopy() than using a loop. The following example shows the difference
  • Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions .
  • Method calls are very costly and you only make it worse by putting them in a loop. So as far as possible avoid method calls in a loop.
  • It is better to avoid accessing array elements in a loop the better option would be to use a temporary variables inside the loop and modify the array values out of the loop. It is fast to use a variable in a loop than accessing an array element.
  • Try to compare the terminating condition with zero if you use non-JIT or HotSpot virtual machine, here is an example to prove the point. JIT or HotSpot virtual machines are optimized for general loops so you do not have to bother about the terminating condition.
  • Avoid using method calls in loops for termination condition this is costly instead use a temporary variable and test the loop termination with the temporary variable.
  • When using short circuit operators to test for loop termination tests always put the expression that will most likely evaluate to false at extreme left.This saves all the following expressions from being tested in case there is an && operator and if there are only || operators then put the expression which is most likely to evaluate to true in the extreme left.
  • Avoid using try-catch inside the loops instead place the loops inside the try-catch for better performance

Key Points

  1. Use integer as loop index variable.
  2. Use System.arraycopy() to copy arrays.
  3. Avoid method calls in loops .
  4. It is efficient to access variables in a loop when compared to accessing array elements.
  5. Compare the termination condition in a loop with zero if you use non-JIT or HotSpot VMs.
  6. Avoid using method calls to check for termination condition in a loop
  7. When using short circuit operators place the expression which is likely to evaluate to false on extreme left if the expresion contains &&.
  8. When using short circuit operators place the expression which is likely to evaluate to true on extreme left if the expresion contains only ||.
  9. Do not use exception handling inside loops.

Get more information

Tags: java loops, method calls, termination condition, JIT, HotSpot VM

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Objects Best Practices

Object contain data and methods to manipulate the data.  Whenever we create an object there is an overhead involved. When an object is created

  • Memory is allocated to all the variables
  • All super class variables are also allocated memory
  • All sub class variables, super class variables are initialized .
  • The constructor is invoked.

So whenever we create an object the above steps are repeated which take considerable resources so it is very important to decide whether creating a new object is required or not. All objects are placed on heap, their address on the heap is stored in the stack. All class  variables are stored in the method area. All primitive data types are stored on the stack.

When we create a String without the new operator and if the content is already existing it uses a single instance of the literal instead of creating a new object every time.

  • Never create objects just for accessing a method.
  • Whenever you are done with an object make that reference null so that it is eligible for garbage collection.
  • Never keep inheriting chains long since it  involves calling all the parent constructors all along the chain until the constructor for java.lang.Object is reached.
  • Use primitive data types rather than using wrapper classes.
  • Whenever possible avoid using class variables, use local  variables since accessing local variables is faster than accessing class variables.
  • Use techniques such as lazy evaluation. Lazy evaluation refers to the technique of avoiding certain computations until they are absolutely necessary. This way we put off certain computations that may never need to be done at all.
  • Another technique is Lazy object creation : i.e. delaying the memory allocation to an object till it is  not being put into use. This way a lot of memory is saved till the object is actually put in to use.

Key Points

  1. Avoid creating objects in a loop.
  2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
  3. Make used objects eligible for garbage collection.
  4. Do not keep inheritance chains long.
  5. Accessing local variables is faster than accessing class variables
  6. Use lazy evaluation, lazy object creation whenever possible.

Get more information

Tags: java objects, best practices, data types, garbage collection, lazy object creation

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java I/O Best Practices

I/O represents Input and Output streams. We use streams to read from or write to devices such as file or network or console. java.io package provides I/O classes to manipulate streams. This package supports two types of streams - binary streams which handle binary data and character streams which handle character data. InputStream and OutputStream are high level interfaces for manipulating binary streams. Reader and Writer are high level interfaces for manipulating character streams.

  1. Reading and writing data using default behavior of some streams that is byte by byte  read/write causes slow performance.
  2. Buffered input streams and buffered output streams increase performance.
  3. Custom buffering increases performance significantly.

Get more information

Tags: java io, best practices, streams, performance, improve java io

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Serialization Best Practices

Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

Deserialization is the process of reading back that serialized java object stream from input stream.

A java object is serializeable and deserializeable if that class follows the following rules

A) The java class must implement java.io.Serializable interface or java.io.Externalizable interface or inherit that implementation from any one of it's super class implementation.

B) All instance variables of that class must implement Serializable interface or Externalizable interface or inherit from one of it's super class.

All primitive data types and some of standard java API classes are serializable. You need not explicitly implement Serializable or Externalizable interfaces for those classes. Serialization process ignores class (static) variables.

Externalizable interface allow to do your own custom implementation of serialization. In this section,  focus is only on Serializable interface.

We will talk initially about Serializable interface. This is a marker interface and does not have any methods. All major java technologies like RMI, EJB are based on serialization process to pass the objects through network. These technologies implicitly do all the serialization work for you. You need to simply implement the java.io.Serialzable interface, but If you want to do your own serialization, that is reading from or writing to streams, ObjectInputStream and ObjectOutputStream  can be used.

Best Practices

  1. Use 'transient' key word for unnecessary variables that need not be read from/written into streams.
  2. When you write RMI, EJB or any other technologies that uses built in Serialization to pass objects through network, use 'transient' key word for unnescessary variables.
  3. Class (static) variables ignores by Serialization process like 'transient' variables.

Get more information

Tags: java, java serialization, best practices, transient, streams, RMI, serializable, externalizable, java API

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

How JVM works with Strings

Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it  does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using 'new' keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information.

The following figure shows the creation of String Objects without using the intern() method.

You can test the above difference programmatically using == operator and String.equals() method.

== operator returns true if the references point to the same object but it does not check the contents of the String object where as String.equals() method returns true if the contents of the String objects are equal.

s1==s2 for the above code returns true because s1 and s2 references point to the same object.

s3.equals(s4) for the above code returns true because both objects content  is same which is "hello".

You can see this mechanism in the above figure. Here, we have three separate objects which contain same content,"hello". Actually we don't need separate objects because they use memory and take time to execute.

Get more information

Tags: java strings, jvm, objects, heap memory, string.intern, literals

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Collections Best Practices

Lists:

  1. Use ArrayList with proper initialization if you don't want thread safe for the collection whenever you  add/remove/access objects at end and middle of collection.
  2. Use Vector with proper initialization if you want thread safe for the collection whenever you  add/remove/access objects at end and middle of collection.
  3. Use LinkedList if you don't want thread safe for the collection whenever you  add/remove/access objects at beginning of collection.
  4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
  5. Use ListIterator than Iterator and Enumeration for List types

Sets:

  1. Use HashSet for maintaining unique objects if you don't want thread safe for the collection for all basic(add/remove/access) operations otherwise use synchronized HashSet for thread safe.
  2. Use TreeSet for ordered and sorted set of unique objects for non-thread safe collection otherwise use synchronized TreeSet for thread safe

Maps:

  1. Use HashMap for non-thread safe map collection otherwise use Hashtable for thread safe collection.
  2. Use TreeMap for non-thread safe ordered map collection otherwise use synchronized TreeMap for thread safe.

Get more information

Tags: java collections, lists, sets, maps, linked list, iterator, treeset, hashset, hashmap

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

J2EE Patterns Best Practices

  1. Use ServiceLocator/EJBHomeFactory Pattern to reduce expensive JNDI lookup process.
  2. Use SessionFacade Pattern to avoid direct client access to Entity beans thus reducing network calls.
  3. Use MessageFacade/ServiceActivator Pattern to avoid large method execution process.
  4. Use ValueObject Pattern to avoid fine grained method calls over network.
  5. Use ValueObjectFactory/ValueObjectAssembler Pattern to avoid multiple network calls for a single client request.
  6. Use ValueListHandler Pattern to avoid using Entity beans and send data iteratively to the client.
  7. Use CompositeEntity Pattern to avoid inter Entity bean overhead.

Get more information

Tags: j2ee patterns, best practices

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

JMS - Best Practices

  1. Start producer connection after you start consumer.
  2. Use concurrent processing of messages.
  3. Close the Connection when finished.
  4. Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE.
  5. Control transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages.
  6. Close session object when finished.
  7. Make Destination with less capacity and send messages accordingly.
  8. Set high Redelivery delay time to reduce network traffic.
  9. Set less Redelivery limit for reducing number of message hits.
  10. Choose non-durable messages wherever appropriate to avoid persistence overhead.
  11. Set optimal message age (TimeToLive value).
  12. Receive messages asynchronously.
  13. Close Producer/Consumer when finished.
  14. Choose message type carefully to avoid unnecessary memory overhead.
  15. Use 'transient' key word for variables of ObjectMessage which need not be transferred.

Get more information

Tags: jms, concurrent processing, transactional messages, message, transient, asynchronous

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

JDBC Best Practices

  1. Use Type two driver for two tiered applications to communicate from java client to database that gives better performance than Type1 driver.
  2. Use Type four driver for applet to database communication that is two tiered applications and three tiered applications when compared to other drivers.
  3. Use Type one driver if you don't have a driver for your database. This is a rare situation because all major databases support drivers or you will get a driver from third party vendors.
  4. Use Type three driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 &2 drivers.
  5. Pass database specific properties like defaultPrefetch if your database supports any of them.
  6. Get database connection from connection pool rather than getting it directly
  7. Use batch transactions.
  8. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
  9. Your database server may not support all isolation levels, be aware of your database server features.
  10. Use PreparedStatement when you execute the same statement more than once.
  11. Use CallableStatement when you want result from multiple and complex statements for a single request.
  12. Use batch update facility available in Statements.
  13. Use batch retrieval facility available in Statements or ResultSet.
  14. Set up proper direction for processing rows.
  15. Use proper getXXX() methods.
  16. Close ResultSet, Statement and Connection whenever you finish your work with them.
  17. Write precise SQL queries.
  18. Cache read-only and read-mostly tables data.
  19. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.

Get more information

Tags: jdbc, best practices, driver, java client, java server, batch transactions, statement

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

JSPs Best Practices

  1. Use jspInit() method to cache static data
  2. Use StringBuffer rather than using + operator when you concatenate multiple strings
  3. Use print() method rather than println() method
  4. Use ServletOutputStream instead of JSPWriter to send binary data
  5. Initialize the 'out' object (implicit object) with proper size in the page directive.
  6. Flush the data partly
  7. Minimize code in the synchronized block
  8. Set the content length
  9. Release resources in jspDestroy() method.
  10. Give 'false' value to the session in the page directive to avoid session object creation.
  11. Use include directive instead of include action when you want to include the child page content in the translation phase.
  12. Avoid giving unnecessary scope in the 'useBean' action.
  13. Do not use custom tags if you do not have reusability.
  14. Use application server caching facility
  15. Use Mixed session mechanisms such as 'session' with hidden fields
  16. Use 'session' and 'application' as cache.
  17. Use caching tags provided by different organizations like openSymphony.com
  18. Remove 'session' objects explicitly in your program whenever you finish the task
  19. Reduce session time out value as much as possible
  20. Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
  21. Disable JSP auto reloading feature.
  22. Use thread pool for your JSP engine and define the size of thread pool as per application requirement.

Get more information

Tags: jsps, best practices, session

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Java Servlets Best Practices

  1. Use init() method to cache static data
  2. Use StringBuffer rather than using + operator when you concatenate multiple strings
  3. Use print() method rather than println() method
  4. Use ServletOutputStream rather than PrintWriter to send binary data
  5. Initialize the PrintWriter with proper size
  6. Flush the data partly
  7. Minimize code in the synchronized block
  8. Set the content length
  9. Release resources in destroy() method.
  10. Implement getLastModified() method to use browser cache and server cache
  11. Use application server caching facility
  12. Use Mixed session mechanisms such as HttpSession with hidden fields
  13. Remove HttpSession objects explicitly in your program whenever you finish the task
  14. Reduce session time out value as much as possible
  15. Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
  16. Disable servlet auto reloading feature.
  17. Use thread pool for your servlet engine and define the size as per application requirement.

Get more information

Tags: java servlets, stringbuffer, thread pool, best practices

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Common Performance Tuning Practices for EJBs

  1. Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server.

  2. Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server.

  3. Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate.

  4. Make coarse grained session and entity beans to reduce network calls.

  5. Control serialization by modifying unnecessary data variables with  'transient' key word to avoid unnecessary data transfer over network.

  6. Cache EJBHome references to avoid JNDI lookup overhead.

  7. Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions.

  8. Set proper transaction age(time-out) to avoid large transaction.

  9. Use clustering for scalability.

  10. Tune thread count for EJB Server to increase EJB Server capacity.

  11. Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean.

  12. Choose best EJB Server by testing with ECperf tool kit.

  13. Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread safe, client state etc..

Stateless session beans

  1. Tune the Stateless session beans pool size to avoid overhead of creation and destruction of beans.

  2. Use setSessionContext() or ejbCreate() method to cache bean specific resources.

  3. Release acquired resources in ejbRemove() method

Stateful session beans

  1. Tune Stateful session beans cache size to avoid overhead of activation and passivation process.

  2. Set optimal Stateful session bean age(time-out) to avoid resource congestion.

  3. Use 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead.

  4. Remove Stateful session beans explicitly from client using remove() method.

Entity beans

  1. Tune the entity beans pool size to avoid overhead of creation and destruction of beans.

  2. Tune the entity beans cache size to avoid overhead of activation, passivation and database calls.

  3. Use setEntityContext() method to cache bean specific resources.

  4. Release acquired resources in unSetEntityContext() method

  5. Use Lazy loading to avoid unnecessary pre-loading of child data.

  6. Choose optimal transaction isolation level to avoid blocking of other transactional clients.

  7. Use proper locking strategy.

  8. Make read-only entity beans for read only operations.

  9. Use dirty flag to avoid unchanged buffer data updation.

  10. Commit the data after the transaction completes to reduce database calls in between transaction.

  11. Do bulk updates to reduce database calls.

  12. Use CMP rather than BMP to utilize built-in performance optimization facilities of CMP.

  13. Use ejbHome() methods for global operations.

  14. Tune connection pool size to reduce overhead of creation and destruction of database connections.

  15. Use JDBC tuning techniques in BMP.

  16. Use direct JDBC rather than using entity beans when dealing with huge data such as searching a large database.

  17. Use business logic that is specific to entity bean data.

Message driven beans

  1. Tune the Message driven beans pool size to promote concurrent processing of messages.

  2. Use setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources.

  3. Release acquired resources in ejbRemove() method.

  4. Use JMS tuning techniques in Message driven beans.

Get more information

Tags: performance tuning, ejbs, ejb client, ejb server, persistance, setsessioncontext, session beans, entity beans, mdb, ejbhome

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Choosing an EJB Server

We have more than thirty vendors who provide EJB containers/servers. So when you have to choose  a server you need to carefully look into the following issues and consider the trade-offs between them. The following features need to be looked into before you decide on EJB server

  1. Clustering

  2. Load balancing

  3. Instance pool and instance caching

  4. Lazy loading

  5. Pass by reference for EJB 1.1

  6. Different locking strategies

  7. Connection pooling

  8. Controlling callback methods such as ejbLoad(),ejbStore() in CMP etc

If an EJB server provides all these features  then how can you make sure about the performance of your server? The answer is to use the benchmarking specifications available such as TPC-W, @Bench etc and test the server. But  the problem with these bench marking policies is that they test only for a specific feature of your server, so in order to test the overall performance of your server you can use ECperf specification released by SUN to test your server.

Ecperf benchmark specification is developed under java community process that is meant mainly for EJB server performance testing. It provides EJB code and driver to test an EJB server vigorously. For ECperf information, have a look at the following links

http://java.sun.com/j2ee/ecperf/

You will also find benchmark results of various servers at the following site.

http://ecperf.theserverside.com/ecperf/

http://www.cmis.csiro.au/adsat/

In order to choose best EJB server, analyze features of different EJB servers, test using ECperf tool kit and see available benchmarks ( see above links for already available benchmarks) and finally decide suitable server for your application.

Tags: ejb server, ejb container, clustering, load balancing, connection pooling, performance

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Wednesday, September 06, 2006

Instance pooling in EJB

The concept of pooling resources is nothing new. It's common to pool database connections so that the business objects in the system can share database access. This trick reduces the number of database connections needed, which reduces resource consumption and increases throughput. The J2EE Connector Architecture (J2eeCA) is frequently the mechanism employed by EJB containers when pooling connections to databases and other resources, and is covered a little later. Most EJB containers also apply resource pooling to server-side components; this technique is called instance pooling. Instance pooling reduces the number of component instances—and therefore resources—needed to service client requests. In general, it is also less expensive to reuse pooled instances than to create and destroy instances.

As you already know, clients of session and entity beans interact with the beans through the remote and local interfaces implemented by EJB objects. Client applications never have direct access to the actual bean. Similarly, JMS clients never interact with JMS-based message-driven beans (JMS-MDBs) directly. They send messages that are routed to the EJB container system. The EJB container then delivers these messages to the proper message-driven instance.

Instance pooling is possible because clients never access beans directly. Therefore, there's no fundamental reason to keep a separate copy of each enterprise bean for each client. The server can keep a much smaller number of enterprise beans around to do the work, reusing each enterprise bean instance to service different requests. Although this sounds like a resource drain, when done correctly, it greatly reduces the resources required to service all the client requests.

In EJB

Generally speaking the following occurs:
- upon startup the container may pre-populate the pool with some number of beans (at least one).
- if the number of concurrent requests exceeds the number of available bean instances in the pool the container may instantiate new instances, or block the requests (usually due to the pool reaching it's maximum number of instances) until a bean becomes available.
- the container may remove instances from the pool (usually due to low demand).
Keep in mind the exact method by which a container chooses to instantiate/destroy instances is left up to the container vendor.

Like all EJBs stateful session beans are pooled resources. During its lifetime a stateful session bean instance can chance identity many times.
After a stateful session bean instance has been passivated or removed, it can obtain a new identity by either creation or activation.

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

AJAX code in Web.Config

This small piece of code adds a handler to the Web.Config file for AJAX in Asp.Net web applications.  This piece of code does all the work.

<httpHandlers>  <!-- Register the ajax handler -->
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
</httpHandlers>

Tags: ajax, web.config, add code

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Things Javascript can do and CSS cannot

Real progressive enhancement

JavaScript is a programming language; you have conditionals (if statements), loops and you can test if the current user agent supports a technology before you apply it. The classic example of that was already in use in good image rollover scripts: if (document.images){ } made sure that only browsers with images enabled got a rollover effect. Other examples are testing for DOM support and if there is a certain element before trying to apply a certain class to it.

Reading and testing environments

As JavaScript has access to the browser window properties you can check the dimensions you have at your disposal before showing and hiding several elements. You can also recognise changes in the user agent (like resizing the window, or even the font size by using a trick) and react to them for example re-position a menu.

This is extremely important with multi level dropdown menus. A pure CSS multi level dropdown menu will blindly open new sub-menus to the left (unless you hardwire the x-th level not to do so), while a JavaScript powered menu can test if the next level menu fits the screen. If there is not enough space to the left, it can show it on the right and if there is not enough space downwards, it can open the next level above the current one. This is how real application menus work like.

Removal and generation of elements

By tapping into the DOM, JavaScript can add and remove elements from the document. CSS can only show and hide elements and hope that the user agent will not make them available. JavaScript can also generate superfluous elements (for example for flexible rounded corner solutions or drop shadows) without you having to add them to the document by hand.

Time based execution

JavaScript can use timing to trigger an effect only after a certain amount of time. As humans are prone to error, this is extremely handy when it comes to making menus and effects more usable and accessible. Instead of hiding a menu when the user leaves the parent element, you can wait a certain amount of time and then hide it. This allows for a lot more erratic mouse movement while still keeping the menu available.

Richer event handling

While the support for pseudo selectors in CSS is still not as good as it could be, the JavaScript equivalent event handling has been supported for several generations so far. You can react to almost anything: keys being pressed, the mouse moved, the mouse keys being pressed or released, and by using a certain trick you can even come up with your own custom events.

JavaScript can also react to events that are not the users doing like the document being read, another document getting loaded, an element becoming available or the window being moved or closed.

Real keyboard support

While CSS can only apply styles to an element that has the focus (which could have happened either by keyboard or mouse) JavaScript can use several keyboard event handlers and even recognize which key is currently pressed.

This enables you to create menus that work like real application menus. While the normal web way of navigating through a list of links via keyboard is to jump from link to link via Tab (or the A key in Opera), real application menus like the Windows start bar or any dropdown in the browser menu can be navigated with the arrow keys.

Newer versions of Opera and modified versions of Firefox also allow for this kind of navigation and Sun has cooperated with Mozilla to come up with a reusable library of DHTML widgets that follow these rules. James Edwards also created a DHTML menu that works the same way.

On demand pulling of content

While CSS can only deal with what is available in the document when it is loaded (the exception being browsers that support the :after pseudo selector that allows to generate text or media albeit not styleable) JavaScript can create new content, but also pull in data from other resources like Databases or files with Ajax.
You can for example offer visitors without JavaScript a very basic menu and allow others to pull in the whole site map and load the different page content without reloading the whole page.

Get more information

Tags: javscript, css, event handling, reloading page

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Different ways to make money with your Blog

A - Amazon Associates
B - BlogAds
C - Commission Junction
D - Denton
E - Events
F- Federated Media
G - Google Adsense
H - The Honor System
I - Industry Brains
J - Jobs
K - Kanoodle
L - Linkshare
M - Minmalls
N - Netscape
O - Opine Research Reports
P - Packaged Content
Q - Quit Your Day Job
R - RSS Advertising
S - Schwag
T - Tagword
U - US Web
V - Think Viral
W - Washington Post Blog Rolls
X - Xray your life story with Dandelife
Y - Yahoo Publisher Network
Z - Zzzz. Earn money while you sleep.

Get more information

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Firefox Tips and Tricks

You can use these hacks to change the appearance of Firefox by hiding menus, hiding the separator bars, removing menus or even move the tabbar to the bottom.

This file does not exist by default, so you will have to create it yourself the first time. If you can't find the location in the chart I give you, make sure you are able to view your hidden folders/files, since I know XP for sure hides them.

To create the userChrome.css file in windows: Open a text editor (notepad or wordpad) and save the file as "userChrome.css" into a directory listed below according to the OS your using. To edit userChrome.css after it's created just right click on the file and select 'Edit', then edit the file using wordpad or notepad.

Locations to create the userChrome.css file:
95/98/ME --- c:\windows\Application Data\Phoenix\Profiles\[profile-name]\[#s].slt\chrome\
NT --- %UserProfile%\Application Data\Phoenix\Profiles\[profile-name]\[#s].slt\chrome\
2000/XP --- C:\Documents and Settings\[USER]\Application Data\Mozilla\Firefox\Profiles\default.tea\chrome\
*NIX --- ~/.phoenix/[profile-name]/[#s].slt/chrome/

Now that thats out of the way it's time to customize Firefox behind the scenes. All you have to do is copy and paste these settings on a new line in the userChrome.css file and save the file. Next time you open up Firefox the settings will be applied until you delete the setting out of the userChrome.css file.

settings will be applied until you delete the setting out of the userChrome.css file.

Know more

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Tuesday, September 05, 2006

What is TestDriven.NET

"The Zero Friction Unit Testing Add-In for Microsoft Visual Studio .NET"

Test Driven Development is the practice of writing unit tests for your code before you actually write that code. By writing a test and then writing the code to make that test pass you have a much better idea of what the goal and purpose of your code is. Test Driven Development encourages complete code coverage, which not only increases the quality of your code, but allows you to refactor the internals of a method or class and quickly and easily test the outside interface of an object.

TestDriven.NET makes it easy to run unit tests with a single click, anywhere in your Visual Studio solutions. It supports all versions of Microsoft Visual Studio .NET meaning you don't have to worry about compatibility issues and fully integrates with all major unit testing frameworks including NUnit, MbUnit, & MS Team System.

Download TestDriven.NET 2.0

It's highlights:

  1. When running under VS2005 you should find 'Test With... Debugger' a lot faster. It now uses a cached test process is a similar way to the default 'Run Test(s)' test runner. It will no longer do a full solution build or touch your project files before starting. This means is will play nicely with version control and doesn't need to create a '*.Surrogate' project when used with MSTest projects.
  2. There is now a 'Repeat Test Run' option on the code context menu. This will rebuild your tests and repeat the test run using the last used test runner. If you prefer to use the keyboard you can associate shortcuts with 'RerunTests', 'RerunWithDefault', 'RerunWithDebugger', 'RerunWithCoverage' or 'RerunWithMSBee'. The 'RerunTests' command will use the last used test runner. The few people who have tried this feature seem to end up using it a lot. :)
  3. You can now 'Test With... .NET 1.1' from VS2005. Your tests will be built using MSBee/.NET 1.1 and executed inside a .NET 1.1 process. Any .NET 1.1 build errors will be merged into the VS2005 'Error List'. This is particularly useful when working on class library code that must run on .NET 1.1 and .NET 2.0.
  4. You will find 'Go To Reflector' menu buttons on the 'Code', 'Disassembly' and 'Call Stack' context menus. This isn't strictly speaking using testing related, but it can be very useful if you hit a problem on some system or 3rd party code. For example when an exception is thrown you can easily navigate down the call stack and see exactly what caused it.
  5. Once in Reflector you can right click on any method and 'Toggle Breakpoint'. This means you can set breakpoints on assemblies you don't have the source for! If you're using this in VS2005 be sure to disable the debugging option 'Enable Just My Code'. You can find this on the VS2005 'Options...' dialog under 'Debugging\Enable Just My Code'.

Click for more information

TestDriven.NET Official Site

Tags: Testdriven.net, test driven programming, unit testing, Microsoft .net, .net framework, nunit

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Set NOCOUNT On in Stored procedures - ADO.NET

"SET NOCOUNT ON" in all stored procedures - it reduces the network traffic for queries. It's probably a good general practice, but the network traffic savings would be pretty minimal in most cases. This would be more important in a case where a very high volume of SQL statements with small result sets were being run, because the rowcount information would comprise a more significant portion of the network traffic. NOCOUNT doesn't make any difference on the database load, since @@ROWCOUNT is still populated regardless of the NOCOUNT setting.

NOCOUNT can make a significant performance difference if you are executing a large number of SQL statements, such as in the example Scott Whigham points out in his comment or the example in this article. That's because each executed SQL statement reports completion, which can cause a lot of network traffic just to report "1 row inserted.1 row inserted. 1 row inserted."

Previously, in Classic ASP and ADO, NOCOUNT was most commonly a factor if you were checking RecordsAffected on Command.Execute(). SqlDataReader does have a RecordsAffected property, but it's rarely used since it's not populated until the datareader has iterated all the rows and the datareader is closed. There are some possible implications if you're using DataAdapters to submit changes to the database, since it uses the rows affected result to determine if the update succeeded. Probably the easiest way to check for that case is to search the codebase for SqlDataAdapter and see if the Update() method is being called.

Get more information

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Detect older versions when deploying .NET Framework 2.0

Here is an overview of the algorithm that .NET Framework 2.0 and 3.0 setup use to determine whether any previous beta products are on the system:

For each (beta product code)
{

Call MsiQueryProductState to check if the install state for the product code equals INSTALLSTATE_DEFAULT

if (install state == INSTALLSTATE_DEFAULT)
{

Call MsiGetProductInfo to retrieve the INSTALLPROPERTY_INSTALLEDPRODUCTNAME property for the product code
Add the value of the INSTALLPROPERTY_INSTALLEDPRODUCTNAME property to the list of beta products that need to be uninstalled

}

}

If (list of beta products is not empty)
{

If (setup is running in full UI mode)
{

Display UI with a list of product names that need to be uninstalled via Add/Remove Programs

}

Exit setup with return code 4113

}

The difference between the .NET Framework 2.0 and 3.0 is the location of the list of beta product codes.  You can find the beta product codes for the .NET Framework 3.0 by using these steps:

  1. Download the .NET Framework 3.0 web download bootstrapper and save it to your hard drive

  2. Extract the contents by running dotnetfx3setup.exe /x:c:\dotnetfx3

  3. Open the file c:\dotnetfx3\setup.sdb in a text editor such as notepad

  4. Look for the list of product codes in the [PrevProductIds] section of setup.sdb

Get more information

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Develop email applications using ASP.NET 2.0

In ASP.NET 1.x sending email was fairly simple.  The only issue was that there were different ways to send email depending on whether the application was web or windows based.  Windows developers used MAPI to send emails using an email client like Outlook.  Web developers used CDOSYS to send rich emails.  Microsoft realized that a change was warranted.  In ASP.NET 2.0 Microsoft released a new set of classes to handle email.  The only issue is that to many developers, sending email became much more complex.

In ASP.NET 2.0 a new group was added that contains configurable sections for the System.Net namespace called the system.net section group.  This group allows email settings to be established by using the mailSettings section group.  Since we are sending emails and not receiving emails, we will use the SMTP protocol.  To define the SMTP settings, we will add the SMTP section group to the mailSettings section group.  The SMTP section group then contains a network section that specifies attributes for the SMTP network settings.  These attributes include host, port, username, and password.

To prevent confusion, in ASP.NET 2.0 the System.Web.Mail namespace has been marked deprecated.  All of the classes are still accessible using IntelliSense and will still function properly.  However, they too are marked obsolete.  Instead, a new namespace found at System.Net.Mail should be used.  This new namespace contains classes to manage your mail client and messages.  The SmtpClient class is used to establish a host, port, and network credentials for your SMTP server.  The MailMessage class is similar to the MailMessage class found in the old System.Web.Mail namespace.  This class allows a full email message to be built.  There is also an Attachment class that allows an attachment to be generated so it can later be added to the MailMessage object.  In addition to these three most commonly used classes, you will find that System.Net.Mail contains an AlternateView and LinkedResource class.

Unfortunately, ASP.NET 2.0 does not provide a clean and easy way to access the system.net section group from the web.config file within code.  The SmtpClient object contains a UseDefaultCredentials boolean property, but that specifies whether the SmtpClient object is to use the credentials of the user currently running the application.

Read more

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Using CruiseControl.NET with other applications

CruiseControl.NET only work successfully when it is used correctly with other applications. The following pages tell you how to do this.
Source Control Systems
.NET Tools
Build tools
Test, Coverage and Metric tools
Java tools
Other tools

Children

Using CruiseControl.NET with Alienbrain (CruiseControl.NET)
Using CruiseControl.NET with Perforce (CruiseControl.NET)
Using CruiseControl.NET with Subversion (CruiseControl.NET)
Using CruiseControl.NET with Visual Source Safe (CruiseControl.NET)
Using CruiseControl.NET with Rational ClearCase (CruiseControl.NET)
Using CruiseControl.NET with SourceGear Vault (CruiseControl.NET)
Using CruiseControl.NET with PVCS (CruiseControl.NET)
Using CruiseControl.NET with StarTeam (CruiseControl.NET)
Using CruiseControl.NET with FxCop (CruiseControl.NET)
Using CruiseControl.NET with FitNesse (CruiseControl.NET)
Using CruiseControl.NET with Vil (CruiseControl.NET)
Using CruiseControl.NET with MKS Source Integrity (CruiseControl.NET)
Using CruiseControl.NET with Other Build Tools (CruiseControl.NET)
Using CruiseControl.NET with Simian (CruiseControl.NET)
Using CruiseControl.NET with NAnt (CruiseControl.NET)
Using CruiseControl.NET with CVS (CruiseControl.NET)
Using CruiseControl.NET with MBUnit (CruiseControl.NET)
Using CruiseControl.NET with Telelogic Synergy (CruiseControl.NET)
Using CruiseControl.NET with Ant (CruiseControl.NET)
Using CruiseControl.NET with MSTest (CruiseControl.NET)
Using CruiseControl.NET with MSBuild (CruiseControl.NET)
Using CruiseControl.NET with NCover (CruiseControl.NET)
Using CruiseControl.NET with NUnit (CruiseControl.NET)
Using CruiseControl.NET with Seapine Surround (CruiseControl.NET)
Using CruiseControl.NET with Visual Studio .NET (CruiseControl.NET)

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com