Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Sunday, June 12, 2011

Tips for optimizing your web images

By Ryan Boudreaux

April 14, 2011, 11:02 AM PDT

Takeaway: Ryan Boudreaux explains the importance of optimizing your images for the web in order to balance quality and load times. Here are his rules of thumb for optimizing images and using appropriate file types.

There are several image editing and manipulation tools, programs, and applications available for web and graphic designers, and you probably already have your favorite "prepare for publication" imaging tool in place. This will not be a discussion on the various editing tools themselves, but will concentrate on the best practices and techniques for optimizing your images and graphics on the web.

For a quick example before I get into the whys and hows for optimizing images on the web, take a look at the two images below, and without taking a peek at their properties, notice similarities and differences when comparing them to one another (click on images for full-size).

Figure A

http://i.techrepublic.com.com/blogs/04142011figure_a.jpg

Figure B

http://i.techrepublic.com.com/blogs/04142011figure_b.jpg

Figure A is saved as a .jpg image with a baseline standard format at maximum quality, and is 514KB in file size at 800px wide. At a dial-up 56.6Kbps Internet access speed it would take approximately 90 seconds for this image to be rendered fully on the browser screen. My apologies for those of you who are using dial-up for your Internet access.

Figure B is the same image saved as a .jpg, however, with the format set to progressive with 5 scans, and the quality set to low, and it comes in at just 59KB in file size at 800px wide. At dial-up 56.6Kbps speed this image, would take just about 8 seconds to render fully.

What differences do you notice with the two images? Colors, load times, quality, these are all factors to consider when optimizing your web images. I kept the image pixel sizes consistent for this comparison; however, to fully optimize this image, I could have reduced the pixel width and that would have reduced its web page load impact in addition to the other optimizing factors.

Why optimize web images?

What are the motivating factors that direct our attention to obtain the most favorable web images? Several reasons for optimizing your web images include:

Bandwidth and throughput: We all know that bandwidth has been a buzzword for many years now, and getting your web documents to render as fast as possible in users' browsers means keeping your graphic and image file size to a minimum. The challenge becomes maintaining a high quality graphic while keeping a lean file size; the balance of these two elements is key to optimizing your web images.

Data storage and space: While data storage space and servers become less expensive every year, it is still prudent to limit your image size. As sites grow they typically show a steady growth in the number of images. For example, a particular image directory for a sub-section of a Federal agency Intranet site that I maintain includes 18 sub-directories with 360 images, combining for a total 24MB of storage space, and for an average of 69KB per image, that is actually considered to be slightly on the heavy side for a typical optimized web image.

Reduced costs: Optimized images add up to less server and storage space requirements, less bandwidth and throughput requirements, and therefore reduced hosting costs, especially when using a third-party ISP or Internet network solution provider.

User experience: The visitor enjoys a better experience when page load times are minimal; nothing irritates the guest more than having to wait for image-heavy web documents to load in the browser. Optimized images help keep the load times to within seconds.

Tips for optimizing your web images

Image file formats: The rules about file formats vary between organizations, each web development house typically has a specific guideline. Here are three file types that are suited for the web.

·         GIF: The .gif file format is really a bitmap consisting of a grid made of pixel squares, including transparency pixels with up to 256 colors, and data about every pixel is saved. It is a great file type for saving graphics, charts, bullet points, icons, buttons, and textual details.

·         JPEG: Although, the general rule that many follow is to reserve the .jpg file type for images, and .gif file type for graphics, charts, etc., I would apply the .jpg file type as a rule of thumb if your web site leans toward high end photography galleries, or other high quality graphic designs. This file type is good for saving images with millions of colors, including graphics with a variety of shades and gradients. Just note that typically the .jpg file type images are much larger and take longer to load. However, most image editing tools allow you to select the file compression for .jpg. For example, you can choose Maximum, Very High, High, Medium, and Low, so you do have some control over the ultimate file size. To test the image, be sure to save it under several compression settings and then test them for quality rendering and load times. Balancing quality, compression, and load times can be a judgment call depending on the particular image and the web document it is called within.

·         PNG: The .png image file type was developed in answer to the .gif patented file type, and while it can display a larger range of colors than the .gif, it does typically result in a larger file size. Many use the .png file format very effectively for buttons and icons, which are usually small pixel dimensions anyway, so they are not so large when utilized in that fashion. A typical 16×16 pixel .png icon will weigh in between 1KB and 4KB, or a 48×48 button at between 3KB and 7KB, so when utilized in this fashion they are optimal. For any .png image over a dimension of 200 pixels you start to see much higher file sizes.

Saving images for the web: Here are several rules of thumb for saving your optimized images for the web.

·         Make sure you have saved a copy of the image as a lossless version, meaning that you can come back and edit it again later if needed. For example, .raw, .tiff, .png, .psd file formats to name a few. Especially if several layers have been added to the image or graphic file, you never know when the customer will want to change a word here or a graphic element there, even after it has been up on your site for some time.

·         If it is a photograph, then select .jpg file format to save the final image. Remember to test several quality and compression settings until you get the perfect balance between quality and load times. If your image editing tool allows the "progressive" setting use that as it will allow the image to "blur" or display gradually as it is rendered on the web instead of line by line. The load time is not improved with the progressive setting, however it does give the image a softer look and feel when rendering on screen.

·         If your .jpg image is to be used as a background on the web document then use the Medium or Low compression setting. Otherwise for displayed images keep the compression at High.

·         If you have the option to adjust the image "quality" then use the settings to make the appropriate change; again, remember to strike a balance between acceptable quality and suitable file size.

File sizes: Depending on the use of the image follow these guidelines for optimal file size:

·         For background images try to keep the file size around or below10KB.

·         For banners or header images a file size up to 60KB is acceptable.

·         For high end photographs try to keep them to within 100KB at an absolute maximum.

 

Quick tips: Four things to nail down early in the web design process

By Ryan Boudreaux

 

Takeaway: Ryan Boudreaux identifies four areas where it's best to clearly define basics and work out details before getting too far into coding and design elements.

This group of four quick tips are all things you want to consider early in any new web design project. Sometimes the excitement of beginning a new project can tempt you, and an eager customer, to skip too far ahead before all of the basic details are fully worked out. Unfortunately, this can result in re-work, wasted time, or elements that don't mesh in the final product. Here are my top four areas to nail down when you start a new web design engagement.

#1 Content before code

Before starting any coding, design, and image work or getting a domain name for the new web site, it is a good idea to have the content up front. Building the site elements, layout, coding, imaging, and design before the content is like putting the cart before the horse — it goes nowhere fast. Once the content is clearly defined, then you can make the decisions on what elements will work and the ones that can be omitted, and this will save you and the customer a lot of headache, effort, and wasted time, which will also have a negative impact on the customer's budget.

#2 Branding and logo

 

In the same approach with developing the content, it is always a smart plan to have the corporate branding and logo well defined and memorable before launching thewebsite. If necessary, get the aid of a professional design firm to develop a logo and branding, and ensure they deliver a graphic that stands out from the rest and is easily recognizable.

#3 Test the usability

You don't have to necessarily hire a usability test firm to carry out your usability study, though many large organizations do, and there is nothing wrong with that approach. It always makes sense to find a group of folks who can pick apart your site before it goes live. Your test group should be instructed to find any bugs, glitches, or design flaws before you hit the streets with your new website URL.

#4 Web standards and semantics

Make sure your semantic code is set to a standard that accurately describes the content, and uses the right element for the job, for example, with effective and descriptive Class and ID naming conventions. Web standards and semantic practices will ensure that your pages are found and ranked among the popular search engines and improve the relative value of the website.

For example, many foodie bloggers were elated with the recent Google Recipe Search tool, until the discovery that the new microformat powered algorithms were excluding many of their sites, and many were not being ranked at all because their blog code did not have named element ids or classes such as "ingredient", "procedure", "amount", "preparation", "duration", "cooktime", "instruction", "yield" or "recipe" listed in the semantic code. Managing your microformats can be a daunting task, especially when having to convert them into existing code.

 

Saturday, May 28, 2011

Five tips for optimizing your Internet connection

By Brien Posey

Takeaway: If your Internet connection is sluggish, try these tricks to perk it up.

Few things in life are as frustrating as a slow Internet connection. Unfortunately, there isn't much that you can do about many of the things that cause the Internet to slow down. Things like switch congestion or segment congestion (outside your network) are beyond your control. Even so, you can take a few steps to make sure that your Internet connection is functioning optimally.

1: Avoid DNS bottlenecks
 If you have an Active Directory environment in place, you no doubt have an on-premise DNS server. Recently, I have seen several instances of organizations virtualizing their DNS servers and placing them on host machines that have little capacity remaining. The basic thought behind this is that DNS does not require many system resources, so DNS server placement can be treated almost as an afterthought.


 However, your DNS server's performance has a major impact on the amount of time it takes for users to access Web pages. So it's important to make sure that your DNS server has sufficient resources to prevent it from becoming a bottleneck.

2: Use DNS forwarders
 Another thing you can do to optimize your Internet connectivity is to make use of DNS forwarders. The idea behind a forwarder is that if your DNS server is unable to resolve a query, it sends the 

 It's common to point the forwarder to the DNS servers that are owned by a company's ISP. The problem is that these DNS servers can be located anywhere. For example, my ISP resides in South Carolina, but it uses a DNS server in France. If you really want to optimize your Internet connectivity, your DNS forwarder should point to a DNS server that is in close physical proximity to your geographic location.

 If you aren't sure where your ISP's DNS servers are, I recommend using one of the visual trace route applications to determine where the DNS servers reside. The Visual Trace Route Tool is one free option.

 If you do determine that you're forwarding DNS requests to servers that are far away, the forwarder should be redirected to a DNS server that is in closer geographic proximity. If you don't know of another DNS server you can use, try checking out OpenDNS.

3: Use a proxy cache
 You can also optimize your Internet connectivity by using a proxy cache, which offers two main benefits. First, it provides your network users with a degree of shielding because it is the cache, not the user, that ultimately contacts Web sites. More important, a proxy cache can dramatically speed up Internet access.


 When a user enters a Web URL, the request is sent to the proxy server, which then issues the request on behalf of the user (similar to the way a NAT device works). When the proxy server receives the requested content, it forwards it to the user, but it also stores a copy for itself. If a another user requests the same content, the proxy server can deliver it without having to send the user's request to a Web site. Cached content is delivered almost instantly, so the result is lightning-fast Internet access for your users (at least for any content that has been cached) and decreased Internet bandwidth usage.

 The good news is that you may already have everything that you need to set up a proxy server. Microsoft's Forefront TMG can easily be configured to act as a proxy cache.

4: Secure your wireless access points
 You may be able to optimize your Internet connection by securing your wireless access points. I realize that this sounds ridiculous to anyone who is managing an enterprise class network, because all your access points should already be secure. But a tremendous number of small and midsize businesses are operating unsecured wireless access points.

 From an Internet optimization standpoint, the problem with unsecured wireless access points is that they allow an Internet connection to be used by anyone. A neighbor could potentially be consuming the majority of the available bandwidth.

5: Block streaming media sites
 You can further optimize your Internet connectivity by taking measures to prevent bandwidth from being wasted. One such measure is to block access to any streaming media sites for which there is not a legitimate business need. For example, you might block access to YouTube in an effort to prevent users from wasting Internet bandwidth by downloading viral videos.

Five tips for faster Web browsing

Takeaway: If you're wasting too much time waiting (and waiting and waiting) for Web pages to load, give these tips a try. You should see an immediate, noticeable boost in speed, making your browsing experience faster and more efficient.

Everyone wants faster Web browsing. After all, who has time to wait for Web pages to load these days? This is especially true if you're a tab-junkie like me. When you live with an open browser containing 10 to 15 tabs running at any given time, you know how crucial it is to have as fast a browsing experience as possible. But how do you manage this? Are there tricks to getting more speed when your pipe is maxed out already? You bet your sweet bits and bytes there are.

 Not every solution will work for every user, and not every solution should even be attempted by every user. However, if you like to eke out as much blood as you can from every turnip, let's see how you can squeeze a bit more speed from your browsing experience.

Note: This article is also available as a PDF download.

1: Use a fast browser
 Not all browsers are created equal. Some are simply faster than others. The top speed you will find, in the current crop of browsers, belongs to Google Chrome. If you've grown accustomed to Internet Explorer or Firefox, you'll notice a dramatic increase in rendering time using Google Chrome. Of all the ways you can speed up your browsing experience, this is by far the best. Google Chrome also helps speed things up by allowing you to enter search strings in the URL address bar. With this feature, you don't have to add yet another toolbar, thereby slowing down the browser even further.


2: Disable Flash
 Flash pretty much saturates Web sites now. It's almost impossible to get away from this technology. Problem is, Flash can be slow, so it directly affects the speed of your browsing experience. You can have Flash turned off by default and then re-enable it to view what you need to view. The biggest problem with this is that some browsers require an add-on to block Flash. For Chrome, you need the extension Flashblock. There's also a Flashblock extension for Firefox. Internet Explorer has a built-in tool you can access by clicking Tools | Manage Add-ons. In the Manage Add-ons dialog box, double-click Shockwave Flash Object. Then, click the Remove All Sites button. This will disable Flash for all sites.


3: Save your temporary Web files on a RAM disk
 I wrote an article awhile back on using a RAM disk to help speed up disk-intensive applications. Since the RAM disk will be much faster than your standard hard drive, using it to save all your browsers temporary files will create a faster environment for your browser. However, this solution is not for the newbie, and you will need to use a third-party to better achieve this task.

4: Get rid of all those toolbars
 You've seen them in the wild: browsers so filled with toolbars they take up the majority of real estate in the browser window. Most users don't realize those toolbars tend to slow down the browser in many ways. Some toolbars simply take up precious computer memory, while others eat away at bandwidth by sending and receiving data in the background. The math here is quite simple: The more toolbars you have, the slower your browser will run. Some of those toolbars might seem essential. But if speed is really your top priority, you will want to jettison that extra baggage for the speed you will gain.


5: Use tabs, not windows
 Too many tabs can cause problems, but they're still your best bet for browsing efficiency. How do tabs speed up your experience? A couple of ways. The first is all about organization. With multiple tabs in a single window, it becomes quite a bit faster to locate the page you need to work on. You don't have to maximize a window, discover that it's not the right one, minimize it, maximize a new window… until you find the correct one. A single window open with multiple tabs is far easier to search. This is not the only way tabs can help you. Browsers like Chrome treat each tab as an individual process (instead of a child process of a parent). So when a Web site causes a tab to crash, you can close that one tab and not lose all the other tabs. This behavior is not a standard at the moment, so you'll need to switch over to the Chrome browser to take advantage of it.

Monday, May 16, 2011

10 Tips for Writing High-Performance Web Applications

Rob Howard

Before becoming a workaholic, I used to do a lot of rock climbing. Prior to any big climb, I'd review the route in the guidebook and read the recommendations made by people who had visited the site before. But, no matter how good the guidebook, you need actual rock climbing experience before attempting a particularly challenging climb. Similarly, you can only learn how to write high-performance Web applications when you're faced with either fixing performance problems or running a high-throughput site.
My personal experience comes from having been an infrastructure Program Manager on the ASP.NET team at Microsoft, running and managing www.asp.net, and helping architect Community Server, which is the next version of several well-known ASP.NET applications (ASP.NET Forums, .Text, and nGallery combined into one platform). I'm sure that some of the tips that have helped me will help you as well.
You should think about the separation of your application into logical tiers. You might have heard of the term 3-tier (or n-tier) physical architecture. These are usually prescribed architecture patterns that physically divide functionality across processes and/or hardware. As the system needs to scale, more hardware can easily be added. There is, however, a performance hit associated with process and machine hopping, thus it should be avoided. So, whenever possible, run the ASP.NET pages and their associated components together in the same application.
Because of the separation of code and the boundaries between tiers, using Web services or remoting will decrease performance by 20 percent or more.
The data tier is a bit of a different beast since it is usually better to have dedicated hardware for your database. However, the cost of process hopping to the database is still high, thus performance on the data tier is the first place to look when optimizing your code.
Before diving in to fix performance problems in your applications, make sure you profile your applications to see exactly where the problems lie. Key performance counters (such as the one that indicates the percentage of time spent performing garbage collections) are also very useful for finding out where applications are spending the majority of their time. Yet the places where time is spent are often quite unintuitive.
There are two types of performance improvements described in this article: large optimizations, such as using the ASP.NET Cache, and tiny optimizations that repeat themselves. These tiny optimizations are sometimes the most interesting. You make a small change to code that gets called thousands and thousands of times. With a big optimization, you might see overall performance take a large jump. With a small one, you might shave a few milliseconds on a given request, but when compounded across the total requests per day, it can result in an enormous improvement.


Performance on the Data Tier
When it comes to performance-tuning an application, there is a single litmus test you can use to prioritize work: does the code access the database? If so, how often? Note that the same test could be applied for code that uses Web services or remoting, too, but I'm not covering those in this article.
If you have a database request required in a particular code path and you see other areas such as string manipulations that you want to optimize first, stop and perform your litmus test. Unless you have an egregious performance problem, your time would be better utilized trying to optimize the time spent in and connected to the database, the amount of data returned, and how often you make round-trips to and from the database.
With that general information established, let's look at ten tips that can help your application perform better. I'll begin with the changes that can make the biggest difference.


Tip 1—Return Multiple Resultsets
Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database. You'll be making your system more scalable, too, as you'll cut down on the work the database server is doing managing requests.
While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It's arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it's a good thing.
Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult. Figure 1 shows a sample conversation populating several ArrayLists with typed classes. Returning only the data you need from the database will additionally decrease memory allocations on your server.

// read the first resultset reader = command.ExecuteReader(); // read the data from that resultset while (reader.Read()) { suppliers.Add(PopulateSupplierFromIDataReader( reader )); } // read the next resultset reader.NextResult(); // read the data from that second resultset while (reader.Read()) { products.Add(PopulateProductFromIDataReader( reader )); }

Tip 2—Paged Data Access
The ASP.NET DataGrid exposes a wonderful capability: data paging support. When paging is enabled in the DataGrid, a fixed number of records is shown at a time. Additionally, paging UI is also shown at the bottom of the DataGrid for navigating through the records. The paging UI allows you to navigate backwards and forwards through displayed data, displaying a fixed number of records at a time.
There's one slight wrinkle. Paging with the DataGrid requires all of the data to be bound to the grid. For example, your data layer will need to return all of the data and then the DataGrid will filter all the displayed records based on the current page. If 100,000 records are returned when you're paging through the DataGrid, 99,975 records would be discarded on each request (assuming a page size of 25). As the number of records grows, the performance of the application will suffer as more and more data must be sent on each request.
One good approach to writing better paging code is to use stored procedures. Figure 2 shows a sample stored procedure that pages through the Orders table in the Northwind database. In a nutshell, all you're doing here is passing in the page index and the page size. The appropriate resultset is calculated and then returned.

CREATE PROCEDURE northwind_OrdersPaged ( @PageIndex int, @PageSize int ) AS BEGIN DECLARE @PageLowerBound int DECLARE @PageUpperBound int DECLARE @RowsToReturn int -- First set the rowcount SET @RowsToReturn = @PageSize * (@PageIndex + 1) SET ROWCOUNT @RowsToReturn -- Set the page bounds SET @PageLowerBound = @PageSize * @PageIndex SET @PageUpperBound = @PageLowerBound + @PageSize + 1 -- Create a temp table to store the select results CREATE TABLE #PageIndex ( IndexId int IDENTITY (1, 1) NOT NULL, OrderID int ) -- Insert into the temp table INSERT INTO #PageIndex (OrderID) SELECT OrderID FROM Orders ORDER BY OrderID DESC -- Return total count SELECT COUNT(OrderID) FROM Orders -- Return paged results SELECT O.* FROM Orders O, #PageIndex PageIndex WHERE O.OrderID = PageIndex.OrderID AND PageIndex.IndexID > @PageLowerBound AND PageIndex.IndexID < @PageUpperBound ORDER BY PageIndex.IndexID END

In Community Server, we wrote a paging server control to do all the data paging. You'll see that I am using the ideas discussed in Tip 1, returning two resultsets from one stored procedure: the total number of records and the requested data.
The total number of records returned can vary depending on the query being executed. For example, a WHERE clause can be used to constrain the data returned. The total number of records to be returned must be known in order to calculate the total pages to be displayed in the paging UI. For example, if there are 1,000,000 total records and a WHERE clause is used that filters this to 1,000 records, the paging logic needs to be aware of the total number of records to properly render the paging UI.


Tip 3—Connection Pooling
Setting up the TCP connection between your Web application and SQL Server™ can be an expensive operation. Developers at Microsoft have been able to take advantage of connection pooling for some time now, allowing them to reuse connections to the database. Rather than setting up a new TCP connection on each request, a new connection is set up only when one is not available in the connection pool. When the connection is closed, it is returned to the pool where it remains connected to the database, as opposed to completely tearing down that TCP connection.
Of course you need to watch out for leaking connections. Always close your connections when you're finished with them. I repeat: no matter what anyone says about garbage collection within the Microsoft® .NET Framework, always call Close or Dispose explicitly on your connection when you are finished with it. Do not trust the common language runtime (CLR) to clean up and close your connection for you at a predetermined time. The CLR will eventually destroy the class and force the connection closed, but you have no guarantee when the garbage collection on the object will actually happen.
To use connection pooling optimally, there are a couple of rules to live by. First, open the connection, do the work, and then close the connection. It's okay to open and close the connection multiple times on each request if you have to (optimally you apply Tip 1) rather than keeping the connection open and passing it around through different methods. Second, use the same connection string (and the same thread identity if you're using integrated authentication). If you don't use the same connection string, for example customizing the connection string based on the logged-in user, you won't get the same optimization value provided by connection pooling. And if you use integrated authentication while impersonating a large set of users, your pooling will also be much less effective. The .NET CLR data performance counters can be very useful when attempting to track down any performance issues that are related to connection pooling.
Whenever your application is connecting to a resource, such as a database, running in another process, you should optimize by focusing on the time spent connecting to the resource, the time spent sending or retrieving data, and the number of round-trips. Optimizing any kind of process hop in your application is the first place to start to achieve better performance.
The application tier contains the logic that connects to your data layer and transforms data into meaningful class instances and business processes. For example, in Community Server, this is where you populate a Forums or Threads collection, and apply business rules such as permissions; most importantly it is where the Caching logic is performed.


Tip 4—ASP.NET Cache API
One of the very first things you should do before writing a line of application code is architect the application tier to maximize and exploit the ASP.NET Cache feature.
If your components are running within an ASP.NET application, you simply need to include a reference to System.Web.dll in your application project. When you need access to the Cache, use the HttpRuntime.Cache property (the same object is also accessible through Page.Cache and HttpContext.Cache).

There are several rules for caching data. First, if data can be used more than once it's a good candidate for caching. Second, if data is general rather than specific to a given request or user, it's a great candidate for the cache. If the data is user- or request-specific, but is long lived, it can still be cached, but may not be used as frequently. Third, an often overlooked rule is that sometimes you can cache too much. Generally on an x86 machine, you want to run a process with no higher than 800MB of private bytes in order to reduce the chance of an out-of-memory error. Therefore, caching should be bounded. In other words, you may be able to reuse a result of a computation, but if that computation takes 10 parameters, you might attempt to cache on 10 permutations, which will likely get you into trouble. One of the most common support calls for ASP.NET is out-of-memory errors caused by overcaching, especially of large datasets.Common Performance Myths

One of the most common myths is that C# code is faster than Visual Basic code. There is a grain of truth in this, as it is possible to take several performance-hindering actions in Visual Basic that are not possible to accomplish in C#, such as not explicitly declaring types. But if good programming practices are followed, there is no reason why Visual Basic and C# code cannot execute with nearly identical performance. To put it more succinctly, similar code produces similar results.
Another myth is that codebehind is faster than inline, which is absolutely false. It doesn't matter where your code for your ASP.NET application lives, whether in a codebehind file or inline with the ASP.NET page. Sometimes I prefer to use inline code as changes don't incur the same update costs as codebehind. For example, with codebehind you have to update the entire codebehind DLL, which can be a scary proposition.
Myth number three is that components are faster than pages. This was true in Classic ASP when compiled COM servers were much faster than VBScript. With ASP.NET, however, both pages and components are classes. Whether your code is inline in a page, within a codebehind, or in a separate component makes little performance difference. Organizationally, it is better to group functionality logically this way, but again it makes no difference with regard to performance.
The final myth I want to dispel is that every functionality that you want to occur between two apps should be implemented as a Web service. Web services should be used to connect disparate systems or to provide remote access to system functionality or behaviors. They should not be used internally to connect two similar systems. While easy to use, there are much better alternatives. The worst thing you can do is use Web services for communicating between ASP and ASP.NET applications running on the same server, which I've witnessed all too frequently.


Figure 3 ASP.NET Cache 
There are a several great features of the Cache that you need to know. The first is that the Cache implements a least-recently-used algorithm, allowing ASP.NET to force a Cache purge—automatically removing unused items from the Cache—if memory is running low. Secondly, the Cache supports expiration dependencies that can force invalidation. These include time, key, and file. Time is often used, but with ASP.NET 2.0 a new and more powerful invalidation type is being introduced: database cache invalidation. This refers to the automatic removal of entries in the cache when data in the database changes. For more information on database cache invalidation, see Dino Esposito's Cutting Edge column in the July 2004 issue of MSDN®Magazine. For a look at the architecture of the cache, see Figure 3.


Tip 5—Per-Request Caching
Earlier in the article, I mentioned that small improvements to frequently traversed code paths can lead to big, overall performance gains. One of my absolute favorites of these is something I've termed per-request caching.
Whereas the Cache API is designed to cache data for a long period or until some condition is met, per-request caching simply means caching the data for the duration of the request. A particular code path is accessed frequently on each request but the data only needs to be fetched, applied, modified, or updated once. This sounds fairly theoretical, so let's consider a concrete example.
In the Forums application of Community Server, each server control used on a page requires personalization data to determine which skin to use, the style sheet to use, as well as other personalization data. Some of this data can be cached for a long period of time, but some data, such as the skin to use for the controls, is fetched once on each request and reused multiple times during the execution of the request.
To accomplish per-request caching, use the ASP.NET HttpContext. An instance of HttpContext is created with every request and is accessible anywhere during that request from the HttpContext.Current property. The HttpContext class has a special Items collection property; objects and data added to this Items collection are cached only for the duration of the request. Just as you can use the Cache to store frequently accessed data, you can use HttpContext.Items to store data that you'll use only on a per-request basis. The logic behind this is simple: data is added to the HttpContext.Items collection when it doesn't exist, and on subsequent lookups the data found in HttpContext.Items is simply returned.


Tip 6—Background Processing
The path through your code should be as fast as possible, right? There may be times when you find yourself performing expensive tasks on each request or once every n requests. Sending out e-mails or parsing and validation of incoming data are just a few examples.
When tearing apart ASP.NET Forums 1.0 and rebuilding what became Community Server, we found that the code path for adding a new post was pretty slow. Each time a post was added, the application first needed to ensure that there were no duplicate posts, then it had to parse the post using a "badword" filter, parse the post for emoticons, tokenize and index the post, add the post to the moderation queue when required, validate attachments, and finally, once posted, send e-mail notifications out to any subscribers. Clearly, that's a lot of work.
It turns out that most of the time was spent in the indexing logic and sending e-mails. Indexing a post was a time-consuming operation, and it turned out that the built-in System.Web.Mail functionality would connect to an SMTP server and send the e-mails serially. As the number of subscribers to a particular post or topic area increased, it would take longer and longer to perform the AddPost function.
Indexing e-mail didn't need to happen on each request. Ideally, we wanted to batch this work together and index 25 posts at a time or send all the e-mails every five minutes. We decided to use the same code I had used to prototype database cache invalidation for what eventually got baked into Visual Studio® 2005.
The Timer class, found in the System.Threading namespace, is a wonderfully useful, but less well-known class in the .NET Framework, at least for Web developers. Once created, the Timer will invoke the specified callback on a thread from the ThreadPool at a configurable interval. This means you can set up code to execute without an incoming request to your ASP.NET application, an ideal situation for background processing. You can do work such as indexing or sending e-mail in this background process too.
There are a couple of problems with this technique, though. If your application domain unloads, the timer instance will stop firing its events. In addition, since the CLR has a hard gate on the number of threads per process, you can get into a situation on a heavily loaded server where timers may not have threads to complete on and can be somewhat delayed. ASP.NET tries to minimize the chances of this happening by reserving a certain number of free threads in the process and only using a portion of the total threads for request processing. However, if you have lots of asynchronous work, this can be an issue.
There is not enough room to go into the code here, but you can download a digestible sample at www.rob-howard.net. Just grab the slides and demos from the Blackbelt TechEd 2004 presentation.


Tip 7—Page Output Caching and Proxy Servers
ASP.NET is your presentation layer (or should be); it consists of pages, user controls, server controls (HttpHandlers and HttpModules), and the content that they generate. If you have an ASP.NET page that generates output, whether HTML, XML, images, or any other data, and you run this code on each request and it generates the same output, you have a great candidate for page output caching.
By simply adding this line to the top of your page
<%@ Page OutputCache VaryByParams="none" Duration="60" %>
you can effectively generate the output for this page once and reuse it multiple times for up to 60 seconds, at which point the page will re-execute and the output will once be again added to the ASP.NET Cache. This behavior can also be accomplished using some lower-level programmatic APIs, too. There are several configurable settings for output caching, such as the VaryByParams attribute just described. VaryByParams just happens to be required, but allows you to specify the HTTP GET or HTTP POST parameters to vary the cache entries. For example, default.aspx?Report=1 or default.aspx?Report=2 could be output-cached by simply setting VaryByParam="Report". Additional parameters can be named by specifying a semicolon-separated list.
Many people don't realize that when the Output Cache is used, the ASP.NET page also generates a set of HTTP headers that downstream caching servers, such as those used by the Microsoft Internet Security and Acceleration Server or by Akamai. When HTTP Cache headers are set, the documents can be cached on these network resources, and client requests can be satisfied without having to go back to the origin server.
Using page output caching, then, does not make your application more efficient, but it can potentially reduce the load on your server as downstream caching technology caches documents. Of course, this can only be anonymous content; once it's downstream, you won't see the requests anymore and can't perform authentication to prevent access to it.


Tip 8—Run IIS 6.0 (If Only for Kernel Caching)
If you're not running IIS 6.0 (Windows Server™ 2003), you're missing out on some great performance enhancements in the Microsoft Web server. In Tip 7, I talked about output caching. In IIS 5.0, a request comes through IIS and then to ASP.NET. When caching is involved, an HttpModule in ASP.NET receives the request, and returns the contents from the Cache.
If you're using IIS 6.0, there is a nice little feature called kernel caching that doesn't require any code changes to ASP.NET. When a request is output-cached by ASP.NET, the IIS kernel cache receives a copy of the cached data. When a request comes from the network driver, a kernel-level driver (no context switch to user mode) receives the request, and if cached, flushes the cached data to the response, and completes execution. This means that when you use kernel-mode caching with IIS and ASP.NET output caching, you'll see unbelievable performance results. At one point during the Visual Studio 2005 development of ASP.NET, I was the program manager responsible for ASP.NET performance. The developers did the magic, but I saw all the reports on a daily basis. The kernel mode caching results were always the most interesting. The common characteristic was network saturation by requests/responses and IIS running at about five percent CPU utilization. It was amazing! There are certainly other reasons for using IIS 6.0, but kernel mode caching is an obvious one.


Tip 9—Use Gzip Compression
While not necessarily a server performance tip (since you might see CPU utilization go up), using gzip compression can decrease the number of bytes sent by your server. This gives the perception of faster pages and also cuts down on bandwidth usage. Depending on the data sent, how well it can be compressed, and whether the client browsers support it (IIS will only send gzip compressed content to clients that support gzip compression, such as Internet Explorer 6.0 and Firefox), your server can serve more requests per second. In fact, just about any time you can decrease the amount of data returned, you will increase requests per second.
The good news is that gzip compression is built into IIS 6.0 and is much better than the gzip compression used in IIS 5.0. Unfortunately, when attempting to turn on gzip compression in IIS 6.0, you may not be able to locate the setting on the properties dialog in IIS. The IIS team built awesome gzip capabilities into the server, but neglected to include an administrative UI for enabling it. To enable gzip compression, you have to spelunk into the innards of the XML configuration settings of IIS 6.0 (which isn't for the faint of heart). By the way, the credit goes to Scott Forsyth of OrcsWeb who helped me figure this out for the www.asp.net severs hosted by OrcsWeb.
Rather than include the procedure in this article, just read the article by Brad Wilson at IIS6 Compression. There's also a Knowledge Base article on enabling compression for ASPX, available at Enable ASPX Compression in IIS. It should be noted, however, that dynamic compression and kernel caching are mutually exclusive on IIS 6.0 due to some implementation details.


Tip 10—Server Control View State
View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page's tree of controls. View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data.
There are a number of drawbacks to the use of view state, however. First of all, it increases the total payload of the page both when served and when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server. Lastly, view state increases the memory allocations on the server.
Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed. The default behavior of the ViewState property is enabled, but if you don't need it, you can turn it off at the control or page level. Within a control, you simply set the EnableViewState property to false, or you can set it globally within the page using this setting:
<%@ Page EnableViewState="false" %>
If you are not doing postbacks in a page or are always regenerating the controls on a page on each request, you should disable view state at the page level.


Conclusion
I've offered you some tips that I've found useful for writing high-performance ASP.NET applications. As I mentioned at the beginning of this article, this is more a preliminary guide than the last word on ASP.NET performance. (More information on improving the performance of ASP.NET apps can be found at Improving ASP.NET Performance.) Only through your own experience can you find the best way to solve your unique performance problems. However, during your journey, these tips should provide you with good guidance. In software development, there are very few absolutes; every application is unique.

Wednesday, April 13, 2011

Five tips for a lighter, leaner Linux desktop

Takeaway: With a little tweaking, you can achieve a noticeable increase in speed for your Linux desktop. Jack Wallen looks at a few simple steps for tuning up performance.

The Linux desktop is flexible, powerful, and reliable, and it's certainly ready for your business and/or home needs. One of the many reasons why the Linux desktop can handle numerous needs is its ability to be highly tuned to meet the requirements of the user. In addition to customizing the desktop, you'll sometimes want to tweak it so that it's as light and lean as possible. For example, you may have a slower piece of hardware you want to eke more life out of. Or you might have an application that requires a larger amount of CPU cycles than a standard desktop allows. Regardless of the "why," we're going to focus on the "how." Here are five ways you can have yourself a lighter, leaner Linux desktop.

1: Use a lighter desktop

There are plenty of options available. From Enlightenment to Fluxbox to Xfce, Linux has plenty of options (all with varied feature sets) that allow you to have the lightest possible desktop. One of the lightest of all (outside of console only) is Fluxbox. Although this desktop may require you to do some manual configurations, the result is an incredibly fast desktop — likely the fastest desktop you have ever experienced. You can install many of these lightweight desktops right from your Package Management system. For Enlightenment, however, I would go with a distribution that offers E17 as an option or as the default (such as Bodhi Linux.)

2: Don't use indexing

As with the Windows desktop, indexing can cause a significant slowdown on your Linux desktop. Both KDE and GNOME use indexing (with the help of Strigi and Beagle, respectively) to enable more powerful desktop searching that is accessed not only by end users, but by applications as well. The act of indexing is when either the Beagle or the Strigi indexing daemon indexes every file within the configured directories. Both tools allow for the configuration of specific times to handle indexing, which is one way to get rid of the issue at hand. But if you don't do much searching or you don't use applications that depend upon desktop searching (such as a groupware suite like Evolution), you can disable the indexing services altogether.

3: Turn off visual effects

Yes, visual effects are cool. That Compiz cube can't be beat for desktop awesomeness. But Compiz (and other compositors) can really put a hit on your system. Just because your GPU can handle the task doesn't mean your CPU or RAM can handle the added load. For slower systems (or when you really need as much CPU as you can get), disable visual effects completely in GNOME or KDE. The latest KDE (4.6 as of this writing) has a nice feature that will automatically disable visual effects if they take too long to load or cause a noticeable hit on the system. For GNOME, just click System | Preferences | Appearance and then disable Visual Effects from within the Visual Effects tab. For KDE, click K Menu | System Settings | Desktop Effects and uncheck  Enable Desktop Effects in the General tab.

4: Remove KDE Plasmoids and GNOME widgets

With either KDE or GNOME, the more widgets you use, the slower your desktop can get. By default, KDE 4 will ship with a single Plasmoid, which won't create a noticeable hit. But if you long for a bit more speed, you can remove that Plasmoid. Same thing with GNOME. I have seen the GNOME Do widget in a GNOME panel cause slowdowns on a system. Of course, with GNOME 3, this all changes, as you can't add widgets to the Panel. You can think of these Plasmoids and widgets similarly to Windows startup applications. They require resources to run and the more you have, the more resources they will use. This is especially true if you have visual effects turned on, since the Plasmoids often make use of those effects. And if you are using Plasmoids or widgets that are updated from a network feed, you could easily see a slowdown should your connection fail or suffer a slowdown.

5: Use a different file manager

I know this might seem counterintuitive, as both Dolphin (KDE) and Nautilus (GNOME) are integrated file managers and should be optimized for use. But the thing is, those file managers are notorious resource hogs. Yes, they offer an incredible number of features and are hands-down the most user-friendly, feature-rich file managers you will ever use. But when speed is the key, you want a file manager like PCMan File Manager or Thunar. Both offer some unique features for a file manager and both will blow the competition out of the water when it comes to speed. Between the two, you will find PCMan File Manager to be the lighter weight, as it doesn't depend upon the Xfce libraries that Thunar requires for installation. But both of those solutions are blazing fast and will not slow down your system in the slightest.

When trying to decide upon which Linux desktop to use, you should rest assured that (unless your hardware demands a much lighter desktop) you should be able to tweak your desktop to the point where the increase in speed is noticeable. Although many would argue that today's powerful machines can handle anything thrown at them, not all businesses or homes can afford the latest-greatest. In those instances, it's always nice to know a leaner, lighter desktop can be had, thanks to Linux.


Monday, February 28, 2011

11 smart career tips for 2011

By Kathryn Ullrich

Takeaway: A Silicon Valley-based executive search consultant and author offers her tips for handling your career in 2011.

Today we have some advice from Kathryn Ullrich, a Silicon Valley-based executive search consultant and author.

Andy Warhol said, "Being good in business is the most fascinating kind of art."

As a passionate executive recruiter, I couldn't agree more, particularly when it comes to professionals being good in managing their careers. Here, for the New Year, are 11 career tips for 2011:

1.   Look out for #1. Take responsibility for your own career development. Many large organizations have scaled back on training and development-a common outcome of the economic downturn-and small companies can rarely provide significant support. Simply put, your career rests in one set of hands: yours.

2.   Be strategic. Have a long-term career strategy or, at the very least, a sense for where you're headed. Ask yourself, "What do I really want to do?" or "Where do I see myself in five to ten years?" Seek people in similar roles and ask for their advice.

3.   Work in step with your company's goals. Connect the dots from your role to your company's vision and key objectives. How does your work align with the organization's goals? What can you do to maximize your contributions?

4.   Be customer-centric. Whether your customers are internal or external, know their wants and needs, and be fervent about meeting them. Bring the voice of the customer into your day-to-day work and let it enhance your decisions and deliverables.

5.   Collaborate. Working with and through others is requisite to innovating, creating, and producing business results. Adopt a mindset for teaming and collaborating, and put it into daily practice.

6.   Hone your communication skills. Communication skills can make or break careers. Pick one area that needs your attention-considering skills such as listening, presenting, influencing, persuading, or distilling messages-and commit to improvement. Take a class, practice with a trusted friend or colleague, or join a group such as Toastmasters.

7.   Cross over functionally. Many successful executives have risen through the ranks by taking cross-functional roles, such as moving from finance to sales or from marketing to IT. Follow their lead and you can grow your skills, your network, and your political capital.

8.   Expand your experience. Volunteer for special projects or assignments that are outside your everyday role. Discuss your goals with your boss, an HR representative, or a senior leader, and ask for help in finding opportunities to broaden your experience base.

9.   Find a guide. Mentors can serve as influential role models and provide important guidance for your career. Reach out to a potential mentor within your company or industry and see if he or she would be open to mentoring you for a specific purpose and timeframe.

10. Network-now. The best time to increase your network is today. Starting now, get involved in groups such as professional associations, charitable organizations, or even sports leagues. Step into leadership roles and make your expertise known.

11. Specialize. Today, companies look for specialists, not generalists. Develop a personal brand, distinguish your skills and strengths, and determine how to best market yourself.

Kathryn Ullrich is a Silicon Valley-based executive search consultant and author of the award-winning book Getting to the Top: Strategies for Career Success (Silicon Valley Press, 2010, $19.95). She also leads Alumni Career Services at UCLA Anderson School of Management. Contact her at info@ullrichassociates.com.

Tuesday, February 8, 2011

Tips to Avoid Having Your Google AdSense Account Banned

by Steven Papas

Google's AdSense program is a fantastic way to earn extra money on your website or blog, but unless you're extra careful, you may risk being banned from participating. In this article we will outline several tips which can help you avoid being banned from Google AdSense, including some which may surprise you.

Tips to Avoid Being Banned from Google AdSense

In terms of the rules set forth by Google for their AdSense program, the company is very fair and makes it extremely easy to participate. There are, however, a few surefire ways to have your account banned—ways that you may want to avoid at all costs. Here are just a few of those ways:

· Clicking on Your Own Ads. This may seem like a no-brainer, but according to the good folks at Google, it is the number one reason people have their AdSense account banned. Now this doesn't mean that if you occasionally and accidentally click on your own ad your account will be banned, but it does mean that if you try to trick Google by persistently clicking on your ads, you will quickly find yourself on the outside looking in.

· Signing up for more than one account. Some of the veterans of Google's AdSense will tell you there's a few ways around this rule, but if you want to be safe from the threat of being banned, you'll probably want to stick to just the one account.

· AdSense clicking rings. Getting together with friends or colleagues and conspiring to click on each other's ads may sound like a profitable idea, but if you think you're going to fool Google you have another thing coming. This is a "deal breaker" and can quickly result in having your account banned permanently.

· Questionable or Illegal Content. Sites which feature illegal or questionable content—sites such as gambling sites, porn sites and even hacker sites—are not eligible for Google AdSense. Attempting to include Google AdSense on these types of sites is a no-no and will get you banned.

· Images or Pictures Adjacent to your AdSense blocks. Google will afford you a lot of freedom with regard to the placement of your ads, but if you feature pictures or images which are relative to your AdSense blocks they cannot appear next to your ads or you will eventually be banned. Why? Because Google feels this practice is akin to tricking your visitors into clicking on your ads.

· Avoid putting AdSense on Pop-Up Ads. Placing Google AdSense material on pop-ups, especially those pop-ups which generate other pop-ups when users try to close them, is not acceptable in the eyes of Google and can have your account banned until you correct the violation.

· Disclosing your potential earnings. According to Google's terms of service, any information concerning your click-through rates or earnings per impressions or clicks is not allowed on the same site where you will feature any AdSense blocks.

· Having Blank or AdSense-Only Pages. Sites which have no content or those sites featuring nothing but Google AdSense ads are not allowed and can get you banned from the program.



Of course these are just a few of the ways to get your account banned, and while you may not completely agree with all of them, failing to comply can be a one-way ticket to having your account banned, either temporarily or permanently. To ensure that your ads remain up and running, simply follow the rules outlined in Google's terms of service for the AdSense program and avoid questionable conduct altogether.


Saturday, February 5, 2011

Five tips for building a successful global IT workforce

By Jay Patel

Takeaway: By harnessing the IT talent that's available around the world, you can build a high-performing global workforce that meets your organization's needs. These tips will help you develop and grow a flexible, effective IT group.

Successful managers agree: The strength of an organization's IT talent pool is a critical component to building and growing a successful company. And today's global environment makes it possible for an organization to build its workforce without restrictive geographical boundaries. An organization can pull talent and resources from around the world to build the strongest and most efficient team possible.

As a result, it is important for organizations to develop a systematic approach for recruiting and maintaining talent on a global level. In addition, organizations must implement strategies to optimize and harness the global IT service talent that best meets their IT service business requirements.

The following five tips will help CIOs and executives recruit global IT talent more effectively to ensure their organization's workforce is built for success.

1: Set objectives but allow for flexibility in roles

Setting goals and objectives is necessary when determining roles and responsibilities in an organization; however, it is also important to maintain flexibility to make room for individuals' unique skills and experiences. Maintaining a capable IT workforce is most effective when role requirements are clearly defined while still being flexible enough to incorporate the broad range and the scope of skills and talents available. For example, executives may consider redesigning service technicians' roles so an employee's unique skill set can shine through. By remaining flexible, it is easier to ensure organizational culture will support a diverse group of employees who thrive by playing up their strengths and following their instincts.

2: Recruit and promote from within

Companies should work to identify internal resources to develop and grow their workforce. Many managers have found that their company's most valuable resources lie inside the organization. Given the right training and support, internal candidates are put in a position to perform a broader variety of tasks, a particularly vital capability within the IT service industry where technologies and processes are constantly evolving.

3: Hire for innate talents and be willing to invest in training

Most executives trying to build a successful organization understand that it's important to find a balance between innate abilities and specific experience or qualifications when looking for IT talent. Often, hiring managers find a candidate who may have the right personality, experience, and problem-solving skills but may lack a particular certification or technical skill set.

When it comes to pooling talent and building an IT workforce, decision makers need to understand that even though certain skills can be taught, the innate abilities and attitude of a prospective hire can't be instilled with training. When a candidate with the right personality becomes available — even if he or she lacks a certain skill set — it helps to define the skills required for the position and determine whether certification gaps can be successfully achieved through training.

4: Build a candidate pipeline

To maintain the most efficient and well-balanced IT workforce, it's essential to be consistently on the lookout for talent. This is even more important as talent pools continue to globalize, resulting in larger and more diverse candidate pools. Having a candidate pipeline will reduce the likelihood an organization will be caught off guard or unprepared when a position opens up. Managers should ensure that they are never making hasty decisions or missing opportunities for talent. Examine your organization's business plan and try to anticipate future needs, including geographical expansions or relocations. Network and nurture relationships in an effort to recruit talent that aligns with your organization's future needs and direction.

5: Diversify

The most diverse organizations tend to be those that are flexible and strategic about recruiting and maintaining IT talent. Executives at these organizations understand the value of diversity in experience, perspective, and skill when building a workforce. This is even more important when building a global IT workforce, as there is a greater opportunity to connect with individuals with a wide variety of skill sets. By leveraging the existing talent pool, nurturing global networks, and investing in diversity, organizations can effectively mine new IT service talent sources, build multicultural talent, and be well positioned for market success.

Summary

In today's global environment, decision makers must consider business goals and the direction of the organization when mining talent and managing an IT workforce. By prioritizing company needs, being open to diversity and unique skill sets, and valuing the talent that already exists internally, executives are more apt to employ a workforce aligned with company values — one that plays a strategic role in a company's ability to develop new services and expand into new markets. By focusing on having the right resources to identify new sources of talent, optimizing the IT talent pool, and building a strong talent pipeline, organizations can gain access to skills that support business goals, build bench strength, and recruit effectively to enhance competitive advantage.

Jay Patel is Director of Professional Services for Europe, Middle East, and Africa (EMEA), Worldwide TechServices.

ITWORLD
If you have any question then you put your question as comments.

Put your suggestions as comments