Sunday, September 27, 2015

SQL Timeout Exception Prevention and Tuning Stored Procedures


Prevent Stored Procedure Timeout

Write efficient Stored Procedures

Prevent More Disk Reads

Prevent Dead Locks


System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.


The following are the collection of my learning as a SQL developer.

Because of large data on the tables, the join operations and other operations will take up lot of time hence causing the application to time out, also reducing the performance.


Parameter Sniffing
In short, parameter sniffing is one exec plan for all parameter combinations. 

- This option causes the compilation process to ignore the value for the specified variable and use the specified value instead.
- Unlike the other workaround (Option(Recompile)), this option avoid the overhead of recompiling the query every time.


This is the most common problem, The workaround is to declare the input params  again with different variable name and use the
 new variable through out the SP.

In the Example @local_SetupId

CREATE PROCEDURE [dbo].[pr_get_user_ids]
(
@in_SetupId int
)
As
begin
Declare@local_SetupIdint=@in_SetupId
Select UserIdfrom UserDetailwhere SetupId=@local_SetupId

end




Use Local Temp Tables




Store the data from large tables such as Product / Orders/ Hierarchyinto Local temp Tables and Use them when joining – This is will Prevent the joining of heavy tables.

This is Subject to temp Db Size. Consider the temp Db size.

Select only the needed columns for your Transaction operation and put it into a local temp  table. Hence on performing joins the tables will be lighter  and preventing the use of excess Resource.

In the Example We have filtered out few columns  from productHierarchytable using setupid in Where  clause and used it to join with Product table.

SELECT * into #TempProductHierarchyFROM
(SELECT ProductHierarchy,ProductHierarchyId,ProductIdfromProductHierarchyDetails where SetupId=@local_SetupId)ASTPH          

SELECT ProductCodeInterfacefrommasters.ProductP
inner join #tempProductHierarchyonP.ProductId=#TempProductHierarchy.ProductId

Instead of
SELECT ProductCodeInterface frommasters.Product P
inner join masters.ProductHierarchyDetail PHD onP.ProductId=PHD.ProductId
where P.SetupId=@local_SetupId

Use NON Clustered Index
Use Non Clustered Index on temp tables for quicker Execution

Once you have created a temp table, set index on the primary key of the table – on which you will be performing the join operation.
In the example we have read the Product Hierarchy  table into a temp table and we have created a non-clustered  index onto the primary key i.e ProductId

 SELECT*into#TempProductHierarchyFROM
(SELECT ProductHierarchy,ProductHierarchyId,ProductIdfromProductHierarchyDetails
where SetupId=@local_SetupId)ASTPH                     

Create NonClusteredIndexIDX_TP4 On#TempProductHierarchy(ProductId)



Use With(NOLOCK)
NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive

Use NOLOCK on master tables and not everywhere.
Using NoLockmay become dangerous sometimes, so check the query exec plan when in doubt.

Select * from  ProductHierarchy  WITH(NOLOCK)











Join On the InputParameter
This will reduce the operation size and the disk read

Join on input parameter instead of filtering in where condition.
As you can see here we have joined on  setupid i.e the input parameter instead of  joining on the setupid of the other table  and then filtering in where condition. 

SELECT * from trans.PromotionP
inner join masters.ProductPP with(NOLOCK)   on PP.SetupId=@local_SetupId
inner join masters.CustomerCC with(NOLOCK)onCC.SetupId=@local_SetupId

Instead Of
SELECT * from trans.PromotionP
inner join masters.ProductPP with(NOLOCK)   on PP.SetupId=P.SetupId
inner join masters.CustomerCC with(NOLOCK)onCC.SetupId=P.SetupId
Where PP.SetupId=@local_SetupId


Prevent the use of “Select *”

Causes Indexing issues and Binding issues

Dont use "SELECT *" ina SQLquery

Insead use Select ProductId, ProductName from Products



Use EXISTS

To check if any data exists in a particular table, use EXISTS  instead of relying on Count its more effective.


SELECT OrderId,AmendVersionFROMtrans.OrdersWHEREEXISTS(SELECTtop 1 OrderId FROMtrans.OrderExtract WHERESetupId=1099)



Use Local Temp Tables (#TempTableName)







Prevent using Global hash tables (##)


SELECT * into #TempProductFROM(SELECTProductId,LevelId,ProductCodeInterface,NamefromProduct whereSetupId=@local_SetupIdandIsActive=1)ASTP                                          








Use Local Variables to Store the FunctionCall return

Prevent calling the string functions or date functions Over and over again, instead store ‘em in local variables  if you are going to reuse the value.

Declare@sampleStringvarchar(max)='nevermind the promotions'
Declare  @sizeOfStringint
set @sizeOfString=len(@sampleString)
SELECT @sizeOfString




Use Try - Catch

BEGIN TRY
-- Logic / Query here
END TRY           
            
BEGIN CATCH           
 -----------------------------------------------------------------------           
           
  DECLARE           
      @ErrMsg  VARCHAR(255)-- Error Message           
     ,@ErrNo   INT    -- Error Number           
     ,@ErrSeverityINT    -- Error Severity           
     ,@ErrProc  VARCHAR(255)-- Error Procedure           
     ,@ErrLine  INT    -- Error Line           
               
  SELECT           
      @ErrMsg  = ERROR_MESSAGE()           
     ,@ErrNo   = ERROR_NUMBER()           
     ,@ErrSeverity=17           
     ,@ErrProc  = ERROR_PROCEDURE()           
     ,@ErrLine  = ERROR_LINE()           
                           
  RAISERROR  (           
      @ErrMsg           
     ,@ErrSeverity           
     ,1           
     ,@ErrNo           
     ,@ErrLine           
     ,@ErrProc           
     )           
 -----------------------------------------------------------------------           
 END CATCH           
END           
           
           
           
     
 Use  SET NOCOUNT ON

Whenever we write any procedure and execute it a message appears in message window that shows number of rows affected with the statement written in the procedure.

When SET NOCOUNT is ON, the count is not returned.

SETNOCOUNTON
Select PromotionId from Promotion 


Prevent Usage of DDL Statements

Do not try to use DDL statements inside a stored procedure that will reduces the chance to reuse the execution plan.
DDL statements like CREATE,ALTER,DROP,TRUNCATE etc.


Use Alias



If an alias is not present, the engine must resolve which tables own the specified columns. A short alias is parsed more quickly than a long table name or alias. If possible, reduce the alias to a single letter

--Wrong Statement
SELECT PromotionId,P.VersionedPromotionId,Name,PIE.InvestmentTypeIdfromPromotion P
Inner join PromotionInvestmentPIE onPIE.VersionedPromotionId=P.VersionedPromotionId
where P.Name='Blah'

--Correct Statement
SELECT P.PromotionId,P.VersionedPromotionId,P.Name,PIE.InvestmentTypeIdfromPromotion P
Inner join PromotionInvestmentPIE onPIE.VersionedPromotionId=P.VersionedPromotionId
where P.Name='Blah'



Don't use UPDATE instead of CASE

Take this scenario, for instance: You're inserting data into a temp table and need it to display a certain value if another value exists. Maybe you're pulling from the Customer table and you want anyone with more than $100,000 in orders to be labeled as "Preferred." Thus, you insert the data into the table and run an UPDATE statement to set the CustomerRankcolumn to "Preferred" for anyone who has more than $100,000 in orders. The problem is that the UPDATE statement is logged, which means it has to write twice for every single write to the table. The way around this, of course, is to use an inline CASE statement in the SQL query itself. This tests every row for the order amount condition and sets the "Preferred" label before it's written to the table.






Avoid Functions on RHS

Dont use this

select *
from Promotion
where YEAR(StartDate)=2015
and  MONTH(StartDate)=

Use this

Select *
From Promotion
Where StartDatebetween'6/1/2015'
    and'6/30/2015'



 Specify optimizer hints in SELECT

most cases the query optimizer will pick the appropriate index for a particular table based on statistics, sometimes it is better to specify the index name in your SELECT query.
Do not use this unless you know what you are doing.

SELECT *
FROM Promotion
WITH ( Index(IdxPromotionId))
WHERE Name ='blah'
and Setupid=1099 




Hope these tips will help you prevent and solve the timeout exception  you face. If you want to add any please mention in the comments.

Tuesday, September 15, 2015

SSIS Log Simplifier

Here's a simple tool made on winforms that will help you simplify the log files generated by the execution of SSIS packages .

Analysis of the log file may take up large quantities of time,
ie. to find an error that occurred during the execution of the packages we use search function in notepad to traverse through the log file generated by the package execution. 



This tool will help ease up the process by providing a parsed HTML file which is readable version of the log file, highlighting and grouping the errors and warnings thus making it easy to find the error quicker. 

Read on to find out more

Steps:
1. Launch SSIS PILL .exe



2. Click on Get Files after 

  •     Selecting your folder that contains the SSIS log files
  •     Click on Get Files - on the left side all files in the selected directory will be displayed
  •     This will show the status of the file like success or failure and time taken
  •     This is a pictorial indication that the file is a success
  •     These are where warnings are displayed


3. On selection of file with error records
 

  •     Now the picture is different for log files with ERRORS.
  •     The first grid shows the ERRORS and the second the WARNINGS
  •     This thing works full screen too


4. Click on Open In HTML for Parsed Log File, the parsed file will open in browser.
As you can see this is in  a better readable format.


  • Has status of execution at the top
  • First grid is of ERRORS
  • Second Grid is of WARNINGS



5. Other buttons

Export to HTML will Create a directory in the same as your parent directory of your log folder and place the Parsed HTML files there.

Open in HTML will open the selected log file's parsed format like in step 4 in the browser

Open in Text - will open normally in a text editor




6. Mail
Export - Mail will add the attachment of the parsed log file and open up outlook ready to send.



(you can configure default path for the log folder and the email id to which mail needs to be sent in the config file )


If the above setup file doesnt work then use the one below, extract from the zip folder and run the SSISLogSimplifier.exe file


Monday, September 1, 2014

Rooting and flashing Sony Xperia J ST26i

Writing this post after successfully flashing Sony Xperia J ST26i with DARK MOON AVD ROM

I followed the instructions given in
http://forum.xda-developers.com/xperia-j-e/development/st26i-dark-moon-avd-rom-4-1-2-v1-6-t2309415

Steps:
PART 1:

Take a backup of your contacts, sd card etc. I used My phone Explorer

Update the phone's firmware
Go to Settings > About phone > Software updates > System updates
or use SONY PC Companion

PART 2:

Unlock BootLoader
Followed the steps given here
http://www.android.gs/unlock-bootloader-sony-xperia-devices-universal-tutorial/

How to Unlock Bootloader of Sony Xperia Devices (official and universal tutorial)
  1. Go here and check whether your smartphone is on the “unlock bootloader” list or not. If your phone is not listed there it means that you cannot use this guide for unlocking the system.
  2. Also, on your handset type and dial: *#*#7378423#*#*; then go to “Service info -> Configuration -> Rooting Status” and check if the “Bootloader unlock allowed” says yes. If the “no” answer will be displayed then you will not be able to unlock the bootloader of your device.
  3. Now, extract the file named “downloadinf.zip” (which has been downloaded before) on your computer.
  4. Then, copy the obtained file (“android_winusb.inf”) to path c:\android-sdk\extras\google\usb_driver.
  5. Click yes if asked to overwrite something.
  6. Type *#06# on your phone and get the IMEI number; write it down as you will need it a little bit later.
  7. Now, go here.
  8. On the first page click on “Yes, I’m sure”.
  9. Agree to Sony’s legal terms and then hit “I accept”.
  10. On the next page enter your name, email and your device’s IMEI number and click on “Submit”.
  11. An unlock code will now be offered; note it down.
  12. Turn off your device and connect the same with the computer by pressing on the Menu button (for the Xperia arc, Xperia arc S, Xperia neo, Xperia neo V, Xperia pro handsets), or on the Search button (for the Xperia Play device) or on the Volume Up button (for the Xperia mini, Xperia mini pro, Xperia ray, Xperia active, Live with Walkman, Xperia S smartphones).
  13. Install the drivers on the path mentioned above (c:\android-sdk\extras\google\usb_driver).
  14. Now, on your computer open command prompt: “start -> run -> type cmd”.
  15. On the cmd window enter the following commands (one at a time): cd C:\android-sdk\platform-tools; fastboot.exe -i 0x0fce getvar version; fastboot.exe -i 0x0fce oem unlock 0xKEY (replace key with the code obtained before).
  16. That’s all, now the bootloader will be unlocked.
  17. In the end, remove the USB cable and reboot your smartphone.

Problem Faced: STEP 13  The driver to be installed was not accepted by the system.
Soln: 
Hold down the Windows key on your keyboard and press the letter C to open the Charm menu, then click the gear icon (Settings).

Click More PC Settings.

Click General.

Under Advanced Startup, click Restart Now.

NOTE: In Windows 8.1, the ‘Restart Now’ button has moved to ‘PC Setting -> Update & Recovery -> Recovery.’

After restarting, click Troubleshoot.

Click Advanced Options.

Click Windows Startup Settings.

Click Restart.

After restarting your computer a second time, choose Disable driver signature enforcement from the list by typing the number 7 on your keyboard.

Your computer will restart automatically.

After restarting, you will be able to install the  drivers normally; however, Windows will display a warning message. When the warning appears, click Install this driver software anyway

Soln from:  https://learn.sparkfun.com/tutorials/disabling-driver-signature-on-windows-8/disabling-signed-driver-enforcement-on-windows-8

So after unlocking your bootLoader.

PART 3:

Download from here
AVD Rom Latest Release

Addon Archive

Kernel ftf

FIXES_FOR_AVD_1.6_V.zip


place Rom & Addon zip on externel sdcard


Place the downloaded file ClockworkMod-6.0.2.5.img into the folder  C:\android-sdk\platform-tools

Instructions:
  • Download ClockworkMod from the link above
  • Switch off phone
  • Hold Vol-UP button
  • Insert USB cable, wait for blue light
On the cmd window enter the following commands (one at a time): cd C:\android-sdk\platform-tools
type:
run fastboot flash boot ClockworkMod-6.0.2.5.img

and then type
run fastboot reboot

  • when the purple LED shines, press and hold the Vol-UP button
You are now in ClockworkMod Recovery!

Wipe data/factory reset, wipe cache partiton, go to advanced wipe dalvik cache. then go to mounts & storage format system.

Go to install zip from sdcard choose zip from externel sdcard. flash rom

when installation is finished go back to advanced choose fix permissions



PART 4:

Now we need to download and install flashtool 
After installing it. 

The Kernel ftf  that you downloaded
"st26i_11.2.A.0.31 Kernel By Gavster26@XDA_Central Europe.ftf" needs to be extracted. 
You need to have 7Zip or any other file extracting programs.
Once you are done extracting you will find a file called kernel.sin 

follow the instructions in the video
Note: u need to browse for the kernel.sin file that you extracted.


Note:Be careful while browsing and selecting the right file, I happened to choose the wrong one and my phone would not startUp but I retried with the right file and it worked.
Now Flashing of new kernel is done.

PART 5:

Next for Addon Package: It is the same as the instructions in part 3. 
Except that here we select the addon package zip from sd card 
After that follow PART 4 (Flash the kernel again)

PART 6:
The file you downloaded FIXES_FOR_AVD_1.6_V.zip extract it and place the files on sd card.

Download Root Browser place it on ur phone SD card.

Start your phone and install the RootBrowser APK that you downloaded.

Now open it up and copy systemui.apk from the extracted files of FIXES_FOR_AVD_1.6_V.zip to /system/app give permissions rw-r-r
Note: there will already be a copy of systemui.apk rename it to sytemui_copy.apk and then push/copy the file. Tap and hold on the file for long and select permissions from the menu and give it as rw-r-r

Similarly copy  framework.jar to system/framework give permissions rw-r-r
Note: there will already be a copy of framework.jar rename it to framework.jar_copy.apk and then push/copy the file. Tap and hold on the file for long and select permissions from the menu and give it as rw-r-r

You are done.
Be careful while flashing/rooting/unlocking as the methods vary from each model.
Refer XDA forums when in doubt.


Sunday, August 31, 2014

Top 5 reasons to root your Android device


1. Increase Internal memory
2. Fix any broken button
3. Better ROMS
4. Better Looks
5. Performance

If you have an Android phone and in need of any of the above for your phone. Then you need to root your android phone.

Rooting is a means of unlocking the device's capability allowing the user to have complete control.
Rooting method is different for different phone. Lookit up well before you proceed.
For more info: www.xda-developers.com/

Tuesday, May 27, 2014

Remove HulaToo adware manually

HulaToo is an Adware that puts ads on ur browsers and slows down ur system. It comes with unwanted downloads.

HulaToo Ads
Anyways if you begin to see HulaToo ads on ur browsers its safe to remove them.

Steps:
1. Go to Control Panel and select Install/Uninstall Software and select HulaToo and Unistall it.

2. Reset ur Browsers.

3. Go to Win+R type regedit and hit ctrl + F and search for HulaToo and delete all the entries that contains this. Repeat this search and delete till there are no such entries

If the above steps does'nt work then do the following
Steps
1. Go to Win+R (run window) type services.msc

2. All the services running in your system opens up. Search for updateHulaToo.exe and utilHulaToo.exe and just to make sure look out for any name containing HulaToo in the window.

3. Now double Click on one process like updateHulaToo.exe select startUp type in the window as Disabled repeat the same for the other process i.e. utilHulaToo.exe and other services with the HulaToo in it.

4. Restart System

5. Go to MyComputer-> C Drive > ProgramFiles (x86) or ProgramFIles and delete HulaToo Folder. Later Reset ur Browsers.
6. Go to Win+R type regedit and hit ctrl + F and search for HulaToo and delete all the entries that contains this. Repeat this search and delete till there are no such entries

If u have any doubts or need assistance do as in the comment section

Monday, April 21, 2014

Consuming the Twitter API v1.1

A short tutorial on Consuming the Twitter API 1.1
Consuming Twitter API in Dot Net c#, using this you can collect tweets aggregate it to do some data-mining or for a simple widget on your website to display your recent tweets or tweets about any particular topic or entity. Here I shall show a simple way to search for tweets of a particular entity and display it on a GridView of a ASP.Net Application.



Twitter is an online social networking and microblogging service  that enables users to send and read short 140-character text messages, called "tweets"

Companies have already started using twitter as it is the new way to promote, connect and brand a company.
Why?? – Connecting with customers, InstantFeedBack, Latest News, Marketing etc

Why Twitter Analytics are Imp?
Analyzing your followers, your own activity, and what other people are talking about online are all smart ways to make sure you’re getting the most benefit out of your social media presence.
see what users are saying about your business or products, and monitor Twitter feedback as best as possible.




Twitter API v1.1 

Twitter bases its application programming interface (API) off the Representational StateTransfer (REST) architecture. 
By allowing third-party developers partial access to its API, Twitter allows them to create programs that incorporate Twitter's services.


Twitter supports a few authentication methods and with a range of OAuth authentication styles you may be wondering which method you should be using. When choosing which authentication method to use you should understand the way that method will affect your users experience and the way you write your application.




Initially Twitter had API v1 which was pretty much straight forward 
Where you constructed the url and pinged it to return ur result in JSON or XML

Then when the API was updated to v1.1 many third party apps were affected coz of it.
There are many reasons for this, like request limitations to prevent the abuse of the service.


In this article I shall focus on getting the data of a twitter home-timeline or a twitter search.

If you use the...
Send...
REST API
Streaming API

What can it do?


Steps
Create an twitter account
Head to dev.twitter.com/apps/ and log in using your Twitter ID and password. 

Click the Create a new application button and enter the name and description of your application. The website should be a page where you can download your code but, since you’re still writing it, enter your home page URL and change it later. Leave the callback URL blank.



Next
•Create an Access Token
Click the Create my access token button at the bottom of the Details tab on your application’s page. You’ll now see various strings against:

•OAuth: Consumer key
•OAuth: Consumer secret
•Token: Access token
•Token: Access token secret


Now coming to Visual Studio

Hope you got nugget Manager if not install it from extension manager

Create a ASP Application Project.

Go to Nuget Package Manager-> Package Manager Console

In the console that will appear at the bottom of VS type in
Install-Package TweetSharp

TweetSharpis a Twitter API library that greatly simplifies the task of adding Twitter to your desktop, web, and mobile applications. You can build simple widgets, or complex application suites using TweetSharp.


using TweetSharp; // In v1.1, all API calls require authentication

var service = new TwitterService(_consumerKey, _consumerSecret);
service.AuthenticateWith(_accessToken, _accessTokenSecret); 

Here we see we need to replace the keys and tokens which we had generated earlier from the twitter website.

var tweets = service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
foreach (var tweet in tweets)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
You can try out this simple app on console, that will get all the statuses from your current timeLine


Here is my app , 
A simple web app with a gridView to hold the tweets. All tweets that contains "Bruce Wayne" are searched from twitter and displayed here.



The code:
Default.aspx.cs

using TweetSharp;


namespace Tweetz
{
    public class TweetAttribs {

        public string imageUrl { getset; }
        public string userName { getset; }
        public string tweetText { getset; }


}

    public partial class _Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            List<TweetAttribs> tweetsList = new List<TweetAttribs>();
            var service = new TwitterService("oHLA""OgKbtiOg");
            service.AuthenticateWith("22fwghS7T""HMEB5jvSVve");
            var options = new SearchOptions { Q = "Bruce Wayne"  };

            var tweets = service.Search(options);
            foreach (var tweet in tweets.Statuses)
            {
                TweetAttribs taObj = new TweetAttribs();
                taObj.userName = tweet.User.ScreenName;
                taObj.imageUrl = tweet.User.ProfileImageUrl;
                taObj.tweetText = tweet.Text;
                tweetsList.Add(taObj);
            }

            GridView1.DataSource= tweetsList.ToList();
           // GridView1.BackImageUrl = "http://9to5mac.files.wordpress.com/2012/07/screen-shot-2012-07-08-at-8-45-25-pm.png";
            GridView1.DataBind();

        }
    }
}

note:  The keys used are samples, please generate your own and then run the code.

Default.aspx
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:ImageField DataImageUrlField="imageUrl" HeaderText="Pic">
                </asp:ImageField>
                <asp:BoundField DataField="userName" HeaderText="ScreenName" />
                <asp:BoundField DataField="tweetText" HeaderText="Tweet" />
            </Columns>

        </asp:GridView>

References:
So just with a few lines of code and with some major help from tweet sharp we were able to fetch the info we wanted.
TweetSharp simplifies things a lot.         

Sunday, April 20, 2014

Getting over the Heartbleed

Not the love life, the life Online

The simple explanation:
Heartbleed allows a hacker/attacker to have access to a random chunk of memory on the server that contains ur encryption keys or un-encrypted passwords, site data etc while the hacker remains anonymous. You would not know if it hit you.



What can the end user do???
Check if your provider/website of which you are a member of has patched the heartbleed bug. 
Here's the list of websites which have been affected by the heartbleed bug.
 Just change the Password.



 Android users update ur phones.

In detail:
Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic protocols which are designed to provide communication security over the Internet. 
One library that implements TLS is OpenSSL.

66% of the websites use OpenSSL, so knowingly or unknowingly u have been bugged.

A few versions earlier to the current OpenSSL, the negotiation between the client and server before sending expensive data was expensive. Most of the time the packets used to get lost or corrupt due to too many requests and need to drop its end of the TLS connection.
So the guys at the OpenSSL formulated a solution. i.e A way of telling that the server is available or its currently overwhelmed by different requests.  This way of telling if the server was available was done with the help of "KEEP ALIVE" messages known as "HEARTBEATS".


How does the HEARTBEAT work?
ex: suppose you send an request as a payload "you there man" the size is 13 so the webserver to whom you requested stores the payload as well as the size 13 into its memory. So when you send the "keep-alive" request the message is sent back to the client this is done by reading the message out from the memory of the server where it was stored following 13 places(size of ur payload).So, ur connection is kept alive.


The FLAW: Heartbleed
OpenSSL library never checked that the Heartbeat payload size corresponds with the actual length of the payload being sent.  A user is allowed to input any number up to 65535 (64 kilobytes) regardless of the true size of the payload. 
So now the attacker will send an heartbeat request for 64kb even though his payload size is 13 bytes. The server will start responding to the heartbeat request by sending the first 13 bytes and  continuing upto 64kb from the server memory to the client. The data received by the client will contain encryption keys, usernames, unencrypted passwords, user information, site information etc etc . In short whatever is put onto the server memory which is relatively everything.
All this can be performed anonymously and in a repeated manner so accessing different parts of the server memory. 


The CURE:
Affected users should upgrade to OpenSSL 1.0.1g. Users unable to immediately
upgrade can alternatively recompile OpenSSL with -DOPENSSL_NO_HEARTBEATS.

1.0.2 will be fixed in 1.0.2-beta2.
--Official Statement
Check if your site is affected by using this tool by LastPASS

You need to revoke your current secret TLS keys and regenerate new ones. Coz there is no telling if you have been hit and run coz all these attacks are anonymous. 

Android users of V.4.1.1 Jellybean, need to update their phones. (Better to update all android devices irrespective of the version) Download Lookout’s Heartbleed Detector or Bluebox’s Heartbleed Scanner apps, both of which will tell you if your Android device is affected by the bug.

Change ur passwords of websites that are affected(atleast by a letter) 

Even VPN's are suffering from Heartbleed. You will have to regenerate the client certificates. http://www.pcworld.com/article/2144962/vpn-provider-proves-openvpn-private-keys-at-risk-from-heartbleed-bug.html

Don't stop there, coz even if you have patched it from the patch received from the vendor there still might be a lot of ways to steal the information. Everyone's checking and trying to find out more vulnerabilities (so should you) and a few have found too like the Reverse HeartBleed


Reverse Heartbleed
The Heartbleed bug (CVE-2014-0160)can be used to attack clients as well as servers. Many organizations have hosts which initiate outbound SSL connections (pulling updates, fetching images, or pinging webhook URLs). These hosts are often on a separate infrastructure (with different SSL dependencies) within the organization firewall. These hosts may be vulnerable to the reverse Heartbleed attack. 
This is the tool to check for it. https://reverseheartbleed.com/

Reverse Heartbleed is more tricky for the attacker however once you have patched the heartbleed the reverse heartbleed becomes more trickier.


This bug has been around for 2 years
There are claims that no hackers knew about this and it was the researchers who found about it probably the NSA and Google(since a month) knew it. 
The race is on to find the next bug. It's got a reward too. http://www.theregister.co.uk/2014/04/16/open_ssl_crowdfunding/

Microsoft determined that Microsoft Account, Microsoft Azure, Office 365, Yammer and Skype, along with most Microsoft Services, are not impacted by the OpenSSL “Heartbleed” vulnerability. Windows’ implementation of SSL/TLS is also not impacted. A few Services continue to be reviewed and updated with further protections. 


 References:
https://xkcd.com/
http://security.stackexchange.com