Pages

Tuesday, December 17, 2013

Find delete/Update statements been executed in SqlServer

USE master; 
SELECT deqs.last_execution_time AS [Time], dest.TEXT                
AS [Query]
FROM   sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE  dest.text LIKE '%Delete%from%'
ORDER  BY deqs.last_execution_time DESC


Result:


Tuesday, October 22, 2013

Insert a text with single quote (') in MySQL

Scenario:
 
"This is today's example" 
 
You need to insert following text as value into MySQL:
MySQL doesn't allow us to insert single quote ('), so simply use escape characters.
"This is today''s example"
        OR
"This is today\'s example" 

//C#
// if you are using textbox value use String.Replace()
 
 
string str= textbox1.text.Replace("'","''");
        OR 
string str= textbox1.text.Replace("'","\'");

Wednesday, August 28, 2013

Convert Address to Lattitude/Longitude (using Geocoding Google maps)

Geocoding example using javascript and C#


Google provides easy way to convert human readable address into Latitude/Longitude set.
[Detail]
A Geocoding API request:

http://maps.googleapis.com/maps/api/geocode/output?parameters

Google response are either of the following format
1. JSON
2. XML
Following code will tell long story in short:

1. Using Javascript:

//address format for the most accurate lat/lang ( address + ', ' + city + ', ' + state + ' ' + zip) 
eg:- 2842 Crescent Park Ln, Atlanta, GA 30339
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places,geometry"></script>

 findLatlong(address){ 
var address="2842 Crescent Park Ln, Atlanta, GA 30339";
  var point=null;
 geocoder.geocode({ 'address': address }, function (results, status) {
              
                if (status == google.maps.GeocoderStatus.OK) {

                    point.lat = results[0].geometry.location.lat();
                    point.lng = results[0].geometry.location.lng();
               
                }
                else {
              
                    alert('Geocode was not successful for the following reason: '
+ status);
                }
 
            });
return point;
}
[Note: geocode is called asynchronously so mind the flow. ]

2.Using C#:

The following c# code explains how to call Google geocode service and parse the response using LINQ to XML:

public static point getLocation(string address)
{
   WebRequest request = WebRequest
      .Create("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address="
         + HttpUtility.UrlEncode(address));

   using (WebResponse response = request.GetResponse())
   {
      using (Stream stream = response.GetResponseStream())
      {
         XDocument document = XDocument.Load(new StreamReader(stream));

         XElement longitudeElement = document.Descendants("lng").FirstOrDefault();
         XElement latitudeElement = document.Descendants("lat").FirstOrDefault();

         if (longitudeElement != null && latitudeElement != null)
         {
            return new point
            {
               Longitude = Double.Parse(longitudeElement.Value, CultureInfo.InvariantCulture),
               Latitude = Double.Parse(latitudeElement.Value, CultureInfo.InvariantCulture)
            };
         }
      }
   }

   return null;
}

[Serializable]
public class point
{
   public double Longitude { get; set; }
   public double Latitude { get; set; }
 
   public override string ToString()
   {
      return String.Format("{0}, {1}", Latitude, Longitude);
   }
}

Hope this helps , Cheers !

Thursday, August 22, 2013

Nautical Distance Between Two Points( latitude/longitude)

Earth as a Sphere:

We always see maps 2D and assume the distance between two place is easy to calculate, However it is slightly complicated. Earth is some what spherical in shape, hills mountains adds more complication which makes almost impossible to calculate accurate distance between two places. Basically we will be calculating approximate distance between two points assuming earth as a sphere ignoring ellipsoidal effects.


Concept of Spherical Geometry  talks about this concept in detail.

Rather than going to detail we will focus on implementation.

There are few options:
1. Haversine formula[Detail]
Haversine formula: a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
                                 c = 2.atan2(√a, √(1−a))
                                 d = R.c
where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km)
  note that angles need to be in radians to pass to trig functions!

JavaScript:
var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;
d is the distance between two point in KM.

[note: toRad() should convert decimal to radient so simply add this function following the function which calculate distance 
  /** Converts numeric degrees to radians */
    if (typeof (Number.prototype.toRad) === "undefined") {
        Number.prototype.toRad = function () {
            return this * Math.PI / 180;
        }
    }]
2. Spherical Law of Cosines: [Detail]

Spherical law of cosines: d = acos( sin(φ1).sin(φ2) + cos(φ1).cos(φ2).cos(Δλ) ).R
JavaScript:
var R = 6371; // km
var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + 
                  Math.cos(lat1)*Math.cos(lat2) *
                  Math.cos(lon2-lon1)) * R;
Excel: =ACOS(SIN(lat1)*SIN(lat2)+COS(lat1)*COS(lat2)*COS(lon2-lon1))*6371
(Note that here and in all subsequent code fragments, for simplicity I do not show conversions from degrees to radians; see code below for complete versions).

3. Google Spherical  computeDistanceBetween():[Detail]

Google Map API provides static method to get distance between two point.

<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry">
     function calculatedis(){
        var d = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(lat1, lon1), new google.maps.LatLng(lat2, lon2));
    
        return d;
}
</script>
[note: Donot forget to add libraries=geometry ]

Hope this will help you Cheers!!!

Thursday, March 21, 2013

Find Currently Running Query- SQL SERVER


This script gives the list of sql queries running currently on SQL SERVER

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext