Thursday, 30 May 2013

Google Advertisements

When I was looking for travel related information on Google, I found several links. While checking those links I got the required information but along with information, I observed some advertisements related to those information. Check below screenshot where ads are marked in red along with travel information.



As a common  man, when you search any information or product/services on net, you come across many informative sites or blogs. Most of these sites contain advertisements; have you ever wonder how all these millions of sites manage to get advertisement on their page. These ads are nothing but result of AdWords and Ad Sense. Lot of people tend to get confused with AdWords and Ad Sense and often use the words interchangeably. But they are actually opposite and are two different sides of the same coin. AdWords refers to the ad-selling system and Ad Sense is ad-publishing program and both are run by Google. Let’s see in detail what are these above terms and how they work.

What is Ad Sense ?



Ad Sense is a CPC (cost-per-click) advertising program that allows anyone who wants to put ads on their websites by inserting a small amount of HTML into their sites. It refers to the ad-publishing system that displays Google Ad words (ads by google) in websites which are not owned by Google. It is the system where website owners sign up to get those advertisements placed on their site. With Google Ad Sense, website owners who wish to place ads on their site, have to first set up an account with Google. Once the site is approved, Google Ad Sense program will display advertisements from the enormous database of Google AdWords. Google then pays the owner of the site displaying the ads. Google pays Ad Sense publishers based on a per click model - the percentage paid per click is secret, but high traffic websites can create a sizable revenue from Google Ad Sense. This service is free and you earn money every time when someone clicks on ads.

How Ad Sense works ?

Though you can't decide which ads appear on your site, Google does a very nice job of assessing your pages and supplying ads that might interest your visitors. The ads that appear on your site are targeted and relevant to the content your site. When you install the ad code in your site,


Ad Sense spiders will crawl your site to see what your entire page is about. They then check their inventory of ads and put related ads next to each of your articles. This works out well for everyone as someone reading an article on car is much more likely to buy car accessories. Remember that Google doesn't pay you when somebody sees an ad on your site; it pays you only when somebody clicks an ad. For those who are thinking to click their own ads, such people should know that Google Ad sense is capable enough to detect the invalid click activities on ads. If they notice any invalid click activity on your website then they will straight away deactivate your account without giving you any notice.
Now knowing this, if you want to insert ads in your website, you have to sign up on Google ad sense, select some space on your page for the ads, paste a few lines of code (Ad Sense Html Code) from Google into the HTML for your site and let Google fill in your pages with colour-coordinated ads. When somebody clicks one of the ads, Google pays you a fee (the amount varies). This is how ad Sense works. This is easiest way for bloggers or webmasters to start making money with their sites.
Now you might be thinking how much you can earn with Ad Sense if you sign up for it? Ad Sense is purely commission based program. It depend how many valid clicks you have in a month. Some people are earning monthly revenue of around $25,000 or more. You can earn from 1 cent to $15 for a valid click depending on ads served on your site. Generally getting above $1 per click is very rare. No one can predict the exact income with current traffic to your website. But we can say more traffic more money. In short, if you have a good website having a high organic traffic then you can earn a handsome income from Ad Sense program.

What is AdWords ?



Google AdWords is the system where people pay money to place their advertisements on Google or on any individual website registered with Google Ad Sense. AdWords is the name for Google’s pay-per-click (PPC) advertising program. It creates a way for companies to post their web site’s link along with a short pitch on the search engine’s results page.



What advertiser needs to do is to create an AdWord account, insert the desired advertisement and from several available plans, choose the maximum amount so as he willing to pay per click on the inserted ad. After the advertiser's credit card is approved, the advertisement goes out live on the web and every time when any internet surfer clicks on the advertisement, Google records it. Over a period of time, when the amount reaches a certain specified level, Google will then charge your credit card.

How does AdWords Work ?

Let’s understand the process before you use Google AdWords. The first step is to sign up for an AdWords account. It starts with the advertisers who create ads. They can create any ad format (text, image and video) to communicate message. Then user has to choose which keywords they would like to advertise on. Let’s suppose I want to advertise my new line of gardening tools that I just created then I would bid on certain keywords like “gardening, gardening tools, tillers, pulling weeds, etc”. When someone visits Google to do a search and enters the above keywords, your ad will be displayed in the far right column of the search engine (see above image) or in the results pages (with no guaranteed position) or in sites running the Google Ad Sense campaign. With thousands of high-quality websites, news pages, and blogs that partner with Google Display Network, AdWords ads can reach users all over the web to help you drive conversions. When a user clicks your advertisement and goes to your web site, you are charged a pre-determined amount for that click. The biggest advantage of AdWords is, you are advertising to an audience that are already interested in you. People will simply click your ad to make a purchase or learn more about you.
Next question might come to your mind that how do you choose your keywords and how much you have to pay? Well Google provides a free keyword tool where you either enter the URL to your web page containing your product or you enter a phrase with your keywords. When you submit the information, the keyword tool returns a listing of keyword and phrase suggestions that you can use in AdWord campaign. If you are a user to AdWords, you are going to pay an initial one-time $5.00 USD signup fee. Actually Google AdWords uses a bidding system in determining how much you will be charged when a user clicks on one of your ads. You have to bid on what you think your ad is worth per click (say 1 rupee per click) and your competitors will place their bids as well. Google uses other factors such as the quality of ads to determine the weight of your bid price. Users can also use AdWords Budget Optimizer to set their bids in a way to optimize for getting the most clicks as determined by the user budget. Whatever method you use, you never pay more than your budgeted amount per day. For Eg if you set a budget of 10 Rs for day with 1 rupee per click, it will display your ads 10 times a day only. Keep in mind that if you set a low budget for a highly-competitive keyword (a high-priced keyword) then there are fewer chances that your ad will display as often. The thing to remember is that when a keyword is popular and competitive, it will naturally command higher PPC rates.
Using your keywords, Google's contextual targeting technology can automatically match your ads to web pages in Google Ad Sense Display Network and display your ads on those website that are most relevant to your business. For example, an ad for a digital camera may show up next to an article reviewing the latest digital cameras. If you want greater control, use placement targeting to hand-pick specific sites or sections of sites you want your ads to appear on. AdWords also offer various reporting to advertiser like Placement Performance Report. You have visibility into where all your ads appear. Review your ad's performance on a site-by-site basis to see impression, click, cost, and conversion data, and use this data to identify well-performing sites to target more aggressively and low-value placements that require content optimization or exclusion.


In the end I would say that you are basically allocating funds dedicated to specific keywords which suits to your business. The more funds you put into it, the more your ad can appear per month all over the net. What I would suggest is to head over to Google website and learn in detail how this works. READ RE-READ grasp the concepts and guidelines and make an informed decision on how to integrate this into your marketing plan for the short and long run. Hope I have given sufficient information on Google AdWords and Ad Sense.

About Author:
Manish Chandak is social media enthusiast and works as business analysts with Systems Plus. He in free time reads and write on various technologies and process around social media, analysis and testing. He can be contacted at: manish.c@spluspl.com

Wednesday, 22 May 2013

Web Services - An Introduction

What are web Services

In simple team Web service is re-usable business logic on internet can consume by another application which needs the same logic. Web Service is a web functionality (that contains/defines Web Methods) which is hosted over internet so that we can use it in multiple applications.

A Web Service is application logic accessible to programs via standard web protocols, Web method is part of the web service. Web Services is application logic which can be used in other for applications to communicate with each other in a platform and programming language-independent way. A web service is an interface of a software component which describes a collection of operations that can be accessed through XML messages.



 








Why Web Services?

  1. Its platform-independent and language-independent, since they use standard XML languages
  2. Exposing your API onto a network connecting different applications
  3. Connect existing software.
  4. Exposing the existing function on to network
  5. Business opportunity to grow your business
  6. Almost every type of business can benefit from Web services such as expediting software development, integrating applications and databases, and automating transactions with suppliers, partners, and clients.

How it works

Web Services operate on a service-based model. In this model, the web service resides on the web server. A client computer can request and consume this web service and terminate the service as and when desired.















Example

Share market with stock quote on web site is one of the command examples for web service. Pay-TV, we can build web sites that can generate revenue for each request a user sends (monthly subscription). Attach is a sample code where ItemCode is passed to webservice which will generate barcode.

Source Code ( Use file ==> Download option )















About Author
Hemal Fofaria works with Systems Plus and is working on Dot Net technology projects.He can be contacted at: hemal.f@spluspl.com

Thursday, 16 May 2013

Tips to Boost ASP.NET Performance


Introduction

Performance tuning can be tricky. It's especially tough in Internet-related projects with lots of components running around, like HTML client, HTTP network, Web server, middle-tier components, database components, resource-management components, TCP/IP networks, and database servers. Performance tuning depends on a lot of parameters and sometimes, by changing a single parameter, performance can increase drastically.


1) Turn off Tracing unless until required

Tracing is one of the wonderful features which enable us to track the application's trace and the sequences. However, again it is useful only for developers and you can set this to "false" unless you require monitoring the trace logging. 

How it affects performance:
Enabling tracing adds performance overhead and might expose private information, so it should be enabled only while an application is being actively analyzed. 
Solution: When not needed, tracing can be turned off using
<trace enabled="false" requestLimit=”10” pageoutput=”false” traceMode=”SortByTime” localOnly=”true”>


2) Turn off Session State, if not required

One extremely powerful feature of ASP.NET is its ability to store session state for users, such as a shopping cart on an e-commerce site or a browser history. 

How performance is affected:
Since ASP.NET Manages session state by default, you pay the cost in memory even if you don't use it. I.e. whether you store your data in in-process or on state server or in a Sql Database, session state requires memory and it's also time consuming when you store or retrieve data from it.
Solution: You may not require session state when your pages are static or when you do not need to store information captured in the page.
In such cases where you need not use session state, disable it on your web form using the directive,
<@%Page EnableSessionState="false"%>
In case you use the session state only to retrieve data from it and not to update it, make the session state read only by using the directive,
<@%Page EnableSessionState ="ReadOnly"%> 


3)  Disable View State of a Page if possible

View state is 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.

How it affects performance:
It increases the total load 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. 
 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.
Solution:
Pages that do not have any server postback events can have the view state turned off.
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, simply set the EnableViewState property to false, or set it globally within the page using this setting: 
<%@ Page EnableViewState="false" %>
If you turn view state off for a page or control, make sure you thoroughly test your pages to verify that they continue to function correctly.


4) Set debug=false in web.config

When you create the application, by default this attribute is set to "true" which is very useful while developing. However, when you are deploying your application, always set it to "false".

How it affects performance:
Setting it to "true" requires the pdb information to be inserted into the file and this results in a comparatively larger file and hence processing will be slow.
Solution:
Therefore, always set debug="false" before deployment.


5) Avoid Response.Redirect

Response.Redirect () method simply tells the browser to visit another page.

How it affects performance:
They should only be used when you are transferring people to another physical web server. 
Solution:
For any transfers within your server, use .transfer! You will save a lot of needless HTTP requests. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.


6) Use the String builder to concatenate string

How it affects performance:
All the activities you do to the string are stored in the memory as separate references and it must be avoided as much as possible. i.e. When a string is modified, the run time will create a new string and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do it, but when a string is being modified repeatedly it begins to be a burden on performance: all of those allocations eventually get expensive.
Solution:
Use String Builder when ever string concatenation is needed so that it only stores the value in the original string and no additional reference is created.


7) Avoid throwing exceptions

How it affects performance:
Exceptions are probably one of the heaviest resource hogs and causes of slowdowns you will ever see in web applications, as well as windows applications. 
Solution:
You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow. 


8) Use Finally Method to kill resources

The finally method gets executed independent of the outcome of the Block. Always use the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.


9) Use Client Side Scripts for validations

User Input is Evil and it must be thoroughly validated before processing to avoid overhead and possible injections to your applications.

How It improves performance: 
Client site validation can help reduce round trips that are required to process user's request. In ASP.NET you can also use client side controls to validate user input. However, do a check at the Server side too to avoid the infamous Javascript disabled scenarios.


10) Avoid unnecessary round trips to the server

How it affects performance:
Round trips significantly affect performance. They are subject to network latency and to downstream server latency. Many data-driven Web sites heavily access the database for every user request. While connection pooling helps, the increased network traffic and processing load on the database server can adversely affect performance.
Solution:
Keep round trips to an absolute minimum. Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of the page that needs to be changed.


11) Use Page.ISPostBack

Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is first time loaded and not in response to client postbacks.

12) Use Paging

Take advantage of paging's simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster. 


13) Store your content by using caching

ASP.NET allows you to cache entire pages, fragment of pages or controls. You can cache variable data by specifying the parameters that the data depends. By using caching you help ASP.NET engine to return data for repeated request for the same page much faster.
When and Why Use Caching: A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.


14) Minimize the number of web server controls

How it affects performance:
The use of web server controls increases the response time of your application because they need time to be processed on the server side before they are rendered on the client side.
Solution:
One way to minimize the number of web server controls is to taking into consideration, the usage of HTML elements where they are suited, for example if you want to display static text.


15) Avoid using unmanaged code

How it affects performance:
Calls to unmanaged code are a costly marshaling operation.
Solution:
Try to reduce the number calls between the managed and unmanaged code. Consider to do more work in each call rather than making frequent calls to do small tasks.

16) Cleaning Up Style Sheets and Script Files

A quick and easy way to improve your web application's performance is by going back and cleaning up your CSS Style Sheets and Script Files of unnecessary code or old styles and functions. 


17) Place StyleSheets into the Header

when the browser loads the page progressively the header, the logo, the navigation components serve as visual feedback for the user. 
When we place style sheets near the bottom part of the html, most browsers stop rendering to avoid redrawing elements of the page if their styles change thus decreasing the performance of the page. So, always place StyleSheets into the Header


18) Put Scripts to the end of Document

Unlike StyleSheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all StyleSheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, browser does not start any other component downloads, even on different hostnames. So, always have scripts at the end of the document.


19) Make JavaScript and CSS External

Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number of HTTP requests thus improving the performance.

About Author
Priyanka Dodti works with Systems Plus and is working on Dot Net technology projects. She can be contacted at: priyanka.d@spluspl.com

Monday, 13 May 2013

Design Aestheticism in IT

Aesthetics plays an important role in helping humans decide what is beautiful or appealing and what is not. In its truest sense, aesthetics revolves round the wholeness of a particular thing or a scenario rather than bits and pieces or components. 


















It is important that we understand that aesthetics and design go hand-in-hand; especially more so for any IT organization that provides technological innovations and services or is in the business of making products for the gadgets of the future. Such an organization needs to make sure that aesthetics is involved in everything that we do. So, whether we are into making websites or software development such as internet-based software applications, mobile applications or client-server applications; I believe that everything we design has to first appeal to our eyes, then our heart and then our mind. This simply means that the end product has to have a pleasing, attractive look and feel along with being functionally perfect. It is just not enough for a technology firm to say that they take extra care where it concerns designs; the truth is – if anybody has to come out on top in today’s competitive world, they need to be seriously crazy about their work and can proudly say that their product/services are refined, elegant and simply awesome in all aspects.

 Aesthetics and the online world
































As more and more businesses are getting online, the competition in the online space to grab eyeballs is as real and harsh as it is between shops in a fiercely competitive marketplace such as a shopping mall or a roadside bazaar. It has become exceptionally challenging for any business firm to differentiate itself or its services and products from that of its competitors. Being just a big brand name will not always help. In the online world, every business has a chance to upstage its competitors. Having an awesome product or offering superior service is not enough to fight off the competition and emerge as a winner. , So, how do we create the differentiator…the difference that will drive potential customers to us? Well, the BIG differentiator is the DELIGHT aspect. And this is where aesthetic design steps in. Ergonomic design that offers both functionality as well as visual appeal in the form of elegant layouts, coupled with exceptional product quality and packaging brings in the much needed element of DELIGHT for the prospective clients/customers.

It was superior quality product design married with an aesthetic beauty that has made Apple products one of the most favored and admired product lines in the world today. It is the visually appealing websites that we often remember and like to visit, and most of the apps that we use or love have (not so surprisingly) pleasing look and feel.  Well-spaced & attractive layouts, beautiful icons, simple functionality, easy navigation are some of the features that we all look in the software that we use. So, if you are a business with a brilliant product to sell or exceptional service to offer, or simply someone who loves being in the limelight, it is important that you pay special attention to the schematic beauty of your offering. In fact, ergonomic design that has the right balance of aesthetic beauty and superior functionality provides an extra dash of creativity to any product or solution. It goes a long way in ensuring success in a highly competitive and fast-changing world. 

Aesthetic Beauty…A Commitment















As already mentioned, I strongly believe that aesthetics and simplicity in design and implementation is important to any information technology (IT) product; whether it is a website, systems applications, networks, ecommerce solutions, or software apps. The best way to go about ensuring aesthetics in IT product designs is implementing a clutter-free, simple and to-the-purpose (effective) functioning methodology in your firm’s operations. This very approach will go a long way in helping create products/services that will delight your clients and help them delight their customers as well. FeedbackI will be the happiest person if you can make the effort to write in your thoughts on the post. Also please feel free to share your views about on aesthetic design and today’s information technology (IT) led world. 

About Author:
Dhairut Dholakia is technology lover and is important part of Systems Plus technology Think Tank. He works in Systems Plus and actively contributes to technology.He can be contacted at: dhairut.d@spluspl.com

Wednesday, 8 May 2013

Caching!!

What is Caching?


Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.
Caching is extremely important for performance boosting in ASP.Net, as the pages and controls are dynamically generated here. It is especially important for data related transactions, as these are expensive in terms of response time.
Caching places frequently used data in quickly accessed media like the random access memory of the computer. The ASP.Net runtime includes a key-value map of CLR objects called cache. This lives with the application and is available via the HttpContext and System.Web.UI.Page.
In some respect, caching is similar to storing the state objects. However, the storing information in state objects is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic.
The data will not be available if its lifetime expires, or the application releases its memory, or caching does not take place for some reason.
You can access items in the cache using an indexer and may control the lifetime of objects in the cache and set up links between the cached objects and their physical sources.

Types of Caching:

1. Output Caching
2. Fragment Caching
3. Data Caching
4. Substitution Caching.

Output Caching

Here the response of the request is cached for a predefined period and the same is reused for all subsequent requests for the same page.

Cache.aspx:
<%@ OutputCache Duration="10" VaryByParam="txtDemo" VaryByHeader="referer"
VaryByCustom="Browser" Location="ServerAndClient" NoStore="true"%>
<asp:Label ID="lblCurrentTime" runat="server"></asp:Label>
<asp:TextBox ID="txtDemo" runat="server"></asp:TextBox>
<asp:Button ID="btnDemo" runat="server" Text="Demo" />

Cache.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    lblCurrentTime.Text = DateTime.Now.ToLongTimeString();
}

1. Duration and VaryByParam are the only required attributes and others are optional.
2. The value of "VaryByParam" can be either QueryString parameter, Cookie Name, Form element Name or Id of Control on the WebForm.
3. For every value of the parameter (parameters) mentioned in VaryByParam, a different cache copy of the response is maintained on the server and same is reused for those values of parameters for subsequent requests.
4. VaryByParam can be "none" or "*"(create separate cache copy if any parameter changes) or ";" separated list of parameters.
5. VaryByCustom="Browser" à For different browser types a different cache is created.
6. VaryByHeader = "Accept-language" à Different for every value of request header submitted along with the request.
7. Location:
Any Cache can be located on the browser (client) or Proxy or Server
None Cache is disabled everywhere
Downstream Cache can be located either on browser (client) or proxy.
Server Cache is located on the server
Client Cache is located on the browser (client).
ServerAndClient Cache on both Server and Client but not on Proxy

8. NoStore=”true” à page should not be cached on the client irrespective of the browser settings (By Default it is false).

Note: When Tracing is enabled on the page, response of the page is not cached
Note: Browser caches the response of the page based on the response header “Cache-Control” and it’s based on “Location” attribute of Output Cache directive.

To specify cache settings programmatically: (Comment the OutputCache directive in aspx page)
protected void Page_Load(object sender, EventArgs e)
{
    lblCurrentTime.Text = DateTime.Now.ToLongTimeString();
    Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
    Response.Cache.SetExpires(new DateTime(2009,12,31,10,20,30)); //For setting the absolute Data and            Time.
   //Response.Cache.SetMaxAge(new TimeSpan(0, 0, 10)); //For mentioning the relative Data and Time.    
    Response.Cache.VaryByHeaders["referer"] = true;
    Response.Cache.SetValidUntilExpires(true);
    Response.Cache.VaryByParams["txtDemo"] = true; //works only if SetValidUntilExpires is set to true
}

/Web.Config
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheInConfig" enabled="true" duration="10" location="ServerAndClient"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>

In CacheDemo.aspx:
<%@ OutputCache VaryByParam="txtDemo" CacheProfile="CacheInConfig"%>
Changes made to profile(i.e OutputCacheProfile) are automatically effected to all the webforms.

Fragment Caching
Here instead of caching the complete response of the page, only a small portion of it will be cached.

Step1 Add the following to the webform
Server Time: <%= DateTime.Now.ToLongTimeString() %>
Step2: To the Project à Add New itemàWeb UserControl (CacheControl.ascx)
Step3: In CacheControl.ascx add the following
<%@ OutputCache Duration="10" VaryByControl="none" %>
Note: when the output Cache directive is being used in UserControl replace “VaryByParam” attribute with “VaryByControl” i.e for mentioning the Control Id, but for cookie / querystring / form element use “VaryByParam”
Step4: Add to UserControl
<%= DateTime.Now.ToLongTimeString() %>
Step5: Drag and drop UserControl in WebForm
Step6: Run the application and Refresh the webform to note that the time rendered from UserControl is not changing but the time rendered from webform is changing.

Substitution Caching

If the response of the page is cached, after first request, for subsequent requests the cached output is rendered. If the webform has a Substitution control, even if the cached copy is rendered, the return value of the MethodName of the substitution control is used by ASP.NET for rendering latest content.
Step1: Cache the response of the page (Default.aspx) using
<%@ OutputCache Duration="10" VaryByParam="none" %>
Step2: Add the following to the webform
Server Time: <%= DateTime.Now.ToLongTimeString() %>
Step3: Drag and Drop Substitution control from ToolBox onto the WebForm.
Step4: Set its MethodName property = "GetServerTime"
Step5: Add the method as below to the aspx.cs file
static string GetServerTime(HttpContext context)
{
    return DateTime.Now.ToLongTimeString();
}
The return value of the above function is rendered in position of Substitution Control.
Step6: Run the application to view the webform in webbrowser. Refresh the page to note that overall response of the page is cached but latest time (return value of GetServerTime) is rendered in place of substitution control.

Data Caching
Instead of caching the response of the page we now cache the data used in making the response of the page. The cached data can be then reused for subsequent requests by any client for any WebForm i.e. the cached data is global.
When the memory is insufficient the Items in data cache automatically expires.
Step1: Add to the project a new webform - DataCacheDemo.aspx
Step2: Add to .aspx file the following two lines:
Server Time: <%= DateTime.Now.ToLongTimeString() %> <br />
Time From Cache: <asp:Label ID="lblTime" runat="server"/>
Step3: In Page_Load add the following:
if (Cache["dt"] == null)
Cache["dt"] = DateTime.Now;
DateTime dt = (DateTime)Cache["dt"];
lblTime.Text = dt.ToLongTimeString();
Step4: Run the webform and refresh it multiple times…
Note that the Server time is changing but the cached time is not changing.

To set expiration policy to expire the data cache
a) Cache Item dependency on file.
Step5: Append to .aspx file the following
<asp:Label ID="lblDemo" runat="server"/>
Step6: Project à Right clickà Add New itemàText File (Demo.txt) – Add some text to it
Step7: Top of .aspx.cs file add the following
using System.Web.Caching;
using System.IO;
Step8: Append the following to Page_Load
if (Cache["file"] == null)
{
    lblDemo.Text = "Fetched from file: ";
    string pp = MapPath("~/Demo.txt"); //To convert Virtual path to physical path
    StreamReader sr = new StreamReader(pp);
    CacheDependency dep = new CacheDependency(pp);
    Cache.Insert("file", sr.ReadToEnd(), dep); //The cache item is dependent on file and if file changed the      cached
    item immediately expires.
    sr.Close();
}
else
    lblDemo.Text = "Fetched from Cache: ";
    lblDemo.Text += (string)Cache["file"];
    Step9: Run the webform, first time the content if fetched from file. On refresh it fetched from Cache.
    Step10: In Studio, open Demo.txt and modify…
    Step11: Refresh the webform to note that again the content is fetched from file.

b) Cache Item dependency on Absolute Time.
Step12: Add the following to .aspx file
<asp:Label ID="lblTime1" runat="server"></asp:Label>
Step13: Append the following to Page_Load
if (Cache["dt1"] == null)
Cache.Insert("dt1", DateTime.Now, null, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration);
lblTime1.Text = ((DateTime)Cache["dt1"]).ToLongTimeString();
Step14: Run the WebForm, Keep refreshing…Note that every 10 seconds the label shows new server time.

c) Cache Item dependency on Sliding Expiration
If the data cache remains unused for a pre defined period the data must expire
Step15: Add the following to .aspx file
<asp:Label ID="lblTime2" runat="server"></asp:Label>
Step16: Append the following to Page_Load
if (Cache["dt2"] == null)
Cache.Insert("dt2", DateTime.Now, null, Cache.NoAbsoluteExpiration, new TimeSpan(0,0,10));
lblTime2.Text = ((DateTime)Cache["dt2"]).ToLongTimeString();
Step17: Run the WebForm, Keep refreshing…Note that even after 10 seconds the label shows cached time.
Step18: Refresh the form after waiting for 10 secs…this time the label shows server time because after 10 seconds from last request the cached item “dt2” expired.

Additional Methods:
Response.AddCacheItemDependency("dt"); //Response of the page in output cache expires if the data item “dt” expires
Response.AddCacheItemDependencies; // Cache item is dependent on Array of data items
Response.AddCacheDependency;
Response.AddFileDependencies; // Output Cache dependent on array of files
Response.AddFileDependency; // Output Cache item is dependent on single file

About Author
Rachna Bagwe works with Systems Plus and is working on Dot Net technology projects. She can be contacted at:rachna.b@spluspl.com

Monday, 6 May 2013

SQL Performance Improvement Guidelines

  • As a common practice, every table should have a clustered index. Generally, but not always, the clustered index should be on a column that monotonically increases, such as an identity column or some other column where the value is unique. In many cases, the primary key is the ideal column for a clustered index.

  • Do not automatically add indexes on a table because it seems like the right thing to do. Only add indexes if you know that they will be used by the queries run against the table.
  • Ideally a clustered index should be based on a single column (not multiple columns) that are as narrow as possible. This not only reduces the clustered index's physical size, it also reduces the physical size of non-clustered indexes and boosts SQL Server's overall performance.
  • When you create a clustered index, try to create it as a unique clustered index, not a non-unique clustered index.
  • Queries that include either the DISTINCT or the GROUP BY clauses can be optimized by including appropriate indexes. Any of the following indexing strategies can be used:
    • Include a covering, non-clustered index (covering the appropriate columns) of the DISTINCT or the GROUP BY clauses.
    • Include a clustered index on the columns in the GROUP BY clause.
    • Include a clustered index on the columns found in the SELECT clause.
    • Adding appropriate indexes to queries that include DISTINCT or GROUP BY is most important for those queries that run often.
    • Avoid use of cursor. It could be done using WHILE loops.
    • Avoid use of COUNT in a sub-query.
  • SET NOCOUNT ON
SET NOCOUNT ON at the beginning of each stored procedure you write. This statement should be included in every stored procedure, trigger, etc. that you write.
e.g.
USE AdventureWorks2012;
GO
SET NOCOUNT OFF;
GO

-- Display the count message.
SELECT TOP(5)LastName 
FROM Person.Person
WHERE LastName LIKE 'A%';
GO

-- SET NOCOUNT to ON to no longer display the count message.
SET NOCOUNT ON;
GO
SELECT TOP(5) LastName
FROM Person.Person
WHERE LastName LIKE 'A%';
GO

-- Reset
SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO
  • Between over IN
When you have a choice of using the IN or the BETWEEN clauses in your Transact-SQL, you will generally want to use the BETWEEN clause, as it is much more efficient.

e.g.
SELECT task_id, task_name
FROM tasks
WHERE task_id in (1000, 1001, 1002, 1003, 1004)
...is much less efficient than this:
SELECT task_id, task_name
FROM tasks
WHERE task_id BETWEEN 1000 and 1004

  • Avoid using the SUBSTRING function
If possible, you should avoid using the SUBSTRING function and use the LIKE condition instead for better performance. Instead of doing this:
WHERE SUBSTRING(task_name,1,1) = 'b'

Try using this instead:
WHERE task_name LIKE 'b%'

  • If you are creating a stored procedure to run in a database other than the Master database, don't use the prefix sp_ in its name. This special prefix is reserved for system stored procedures.Although using this prefix will not prevent a user defined stored procedure from working, what it can do is to slow down its execution ever so slightly. 
  •  When joining tables, you should specify a WHERE expression.
Joins without WHERE expressions are often time-consuming to evaluate because of the multiplier effect of the Cartesian product. For example, joining two tables of 1,000 rows each without specifying a WHERE expression or an ON clause, produces a result table with one million rows.
  • Creating Full Text Catalog and Full Text Search
Full Text Index helps to perform complex queries against character data.  These queries can include word or phrase searching. We can create a full-text index on a table or indexed view in a database.

FREETEXT( ) Is predicate used to search columns containing character-based data types. It will not match the exact word, but the meaning of the words in the search condition. When FREETEXT is used, the full-text query engine internally performs the following actions on the freetext_string, assigns each term a weight, and then finds the matches.
    • Separates the string into individual words based on word boundaries (word-breaking).
    • Generates inflectional forms of the words (stemming).
    • Identifies a list of expansions or replacements for the terms based on matches in the thesaurus.
e.g.
SELECT BusinessEntityID, JobTitle
FROM HumanResources.Employee
WHERE FREETEXT(*, 'Marketing Assistant');

  • You can speed up your query by rewriting it with OR condition as a UNION
e.g.
rewriting
SELECT * FROM table WHERE (Field1 = 'Value1') OR (Field2 = 'Value2') 
as
SELECT ... WHERE Field1 = 'Value1' 
UNION 
SELECT ... WHERE Field2 = 'Value2' 
  • Use of NOLOCK
Use of WITH(NOLOCK) can prevent reads being deadlocked by other operations
e.g.
SELECT *
FROM sys.all_objects a WITH (NOLOCK)
CROSS JOIN sys.all_objects b WITH (NOLOCK)



About Author
Rajratna Shelhalkar works with Systems Plus and is working on Dot Net technology projects. He can be contacted at: rajratna.s@spluspl.com