Pages

Tuesday, August 26, 2014

Redirect using javascript in same tab

There are two ways to achieve this:
location.assign();
assign() simply reloads the page with given url.


location.replace();
replace()  doesn't save current page in session history so back button will not be available to navigate back..


<html>
<head>
<script>
function assignx()
{
                       //assign simply reloads the page with given url
document.location.assign('http://dirtycodes.blogspot.com/');
}
function replacex()
{
                        //replace()  replaces the history so back button will not work
window.location.replace("http://dirtycodes.blogspot.com/");
}
</script>        
    </head>
<body>
<a href="javascript:void(0)" onclick="assignx();">ASSIGN</a>
</br>
<a href="javascript:void(0)" onclick="replacex();">REPLACE</a>              
               
    </body>
</html>

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

Wednesday, May 30, 2012

Visual Studio Shortcuts


Navigation
Ctrl + ]  Moves the cursor to the matching Closing or Opening brace
Ctrl + hyphen Moves cursor to its previous position
Shift + F7 Switch between the Design View and Source View
Ctrl + Tab Displays the all open files in VS
Ctrl + Shift + F Find
F3 Search Again or continue search


Editing
Ctrl + k + c Comment a selected line or all selected lines of code 
Ctrl + k + u  Uncomment a selected line or all selected lines of code
Ctrl + x, Ctrl + c, Ctrl + v  Cut, Copy, Paste


Code Related
Ctrl +SpaceBar Complete word if exist
Tab (Twice) Inserts Code snippet, eg type while and press Tab twice, or type prop and press Tab twice
Ctrl + Period (.) Shows SmartTag menu
F5 Start or run the application 
F6 or Ctrl + Shift + B Build the solution  Insert or remove breakpoint
F9 Insert or remove breakpoint
Ctrl + S Save 
Ctrl + Alt + L  Open Solution Explorer





Tuesday, April 17, 2012

Elmah Error Loging Module and Handler for Asp.net

Introduction
            ELMAH is an open source project used to add error logging capabilities to an ASP.NET Web application. ELMAH essentially provides a means for logging and reporting unhandled exceptions in applications. I came across this very nifty tool while working with the MASS LEG team to create the Legislative Automated Workflow System (LAWS) application for the Massachusetts Legislature. We used ELMAH to uncover issues in the application that were producing unhandled and non-descriptive exceptions.  Using ELMAH, the dev team was able to use the stack trace of the exception to pinpoint and fix the problem. The following provides a brief description of how to set up ELMAH and enable & configure its error logging.
Link for tutorial:
Integrating ElMAH in asp.net is preety straight forward:
1. Download ELMAH and add the Elmah.dll assembly to your web application, 
2. Register ELMAH's HTTP Modules and Handler in Web.config,
3. Specify ELMAH's configuration options, and
4. Create the error log source infrastructure, if needed.

Follow instruction in tutorial, Your Final web config may look lik this:



After you change your web.Config add reference of elmah.dll to your Bin directory and create the table ELMAH_Error in sqlserver

You can execute the sqlserver.sql file in order to create table and store procedures.. and its done :)
you can see the logs by adding elmah.axd in root directory like
www.example.com/elmah.axd or localhost/something/elmah.axd
good luck

Tuesday, March 27, 2012

Vanity Url using Url Rewriting in asp.net 4.0

Url rewriting can be accomplish via two methods:
1.HTTP module 
2HTTP handler
let us discuss using HTTP handler:


Since SEO comes into consideration it becomes the part of web development. These days every website being developed should be optimized to some extent so it could get crawled by Search Engines.Its advisable that you should take care of your URL’s rather than showing them in a raw format make them readable by user as well SEO friendly.
URL is the important part that search engines want to take a look before they crawl the pages of your website. There are enormous open source libraries and ISAPI filter available that provides support to help you rewriting your URLs. The SEO and url rewriting is now taken into account and is introduced a supported extension for IIS 7.0/7.5 by providing URLRewriterExtension. But here we’re going to discuss how you can rewrite you URL in your Asp.net website with just 3 steps.

1. Create a Route path entry in RouteCollection
First of all add below code your to you Global.asax file. you can add as many route as you want to the RouteCollection object.

image




2. Create a class specific to the particular section that implements the IRouteHandler interface
to handle the incoming Route and receiving the data from the URL
 
image

3. Finally get into the Asp.net web form and process the request
span style="font-family: 'Courier New';">protected void Page_Load(object sender, EventArgs e)
 {
 int catid = Convert.ToInt32(HttpContext.Current.Items["catid"]);     
 var product = awe.Products.Where(item => item.ProductSubcategoryID == catid);             GridView1.DataSource = product;

 GridView1.DataBind(); 
}

sources: 
http://msdn.microsoft.com/en-us/library/ms972974
http://somenewkid.blogspot.com/2006/05/charlie-has-cool-urls-part-1.html

Download Source Code

Tuesday, January 31, 2012

Asp.net development server failed to start listening on port xxxx.

 I got the message:

Asp.net development server failed to start listening on port xxxx.
Error Message: only one usage of each socket address is normally permitted .

Search on net, people all think that if the port is not available, just change the port for the web development server and it will work. Based on this theory, I changed the port number of the ASP.NET web development server, and it worked for me. I typed the steps here…
Go to the Solution Explorer in Visual Studio, click on the web site application, hit ‘F4′ key to bring up the application’s property window. In this property window, set ‘Use Dynamic Port’ to ‘False’, and you will be able to set the Port number to a number other than the previous port number.
See this official MSDN document on how to change the port number for the ASP.NET development server:
http://msdn.microsoft.com/en-us/library/ms178109(VS.80).aspx

Wednesday, October 19, 2011

Query to find non unique column from a table

I have a users table that has over 10,000 registered users (from a database that I've inherited). The original code allows for multiple registrations with the same email address which I want to eliminate. 

Thursday, October 13, 2011

asp:XXXXX is not a known element. This can occur if there is a compilation error in the web site.

Problem occurred when I re-install Visual Stdio 2005...after digging for awhile i find the solution. Changing tag prefix did the job.
<webconfig

<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
change tagPrefix="asp" to tagPrefix="ajax" or whatever prefix you want. Then change your existing ajax control tags to use that prefix instead. E.g. <asp:UpdatePanel...> becomes <ajax:UpdatePanel...>

Monday, September 12, 2011

Database Connectivity Class(layered)

This is a custom Class, Tested and error free. Download it and copy and paste in your solution within Appcode folder. and call the methods via its class name .
here is the Download link: Download
hope this will help you.

Editable Dropdownlist using java script

Introduction
In ASP.Net Dropdownlist control cannot be editable by default. We can easily overcome this problem. This article is used to overcome this issue.
Using the code
Create one blank asp.net web page(Default.aspx) and include one textbox and dropdownlist control. see the following code.
<asp:TextBox ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" runat="server">

    <asp:ListItem Value="test1" >test1</asp:ListItem>

    <asp:ListItem Value="test2">test2</asp:ListItem>

</asp:DropDownList>
       
After inserted this controls into web page we need to set the following style into textbox control.
style="position:absolute" 
The position property places an element in a static, relative, absolute or fixed position. There are four types of position like static, relative, absolute and fixed.
Value
Description
static
Default. An element with position: static always has the position the normal flow of the page gives it (a static element ignores any top, bottom, left, or right declarations)
relative
An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position
absolute
An element with position: absolute is positioned at the specified coordinates relative to its containing block. The element's position is specified with the "left", "top", "right", and "bottom" properties
fixed
An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)
<asp:TextBox style="position:absolute" ID="txtDisplay" runat="server"></asp:TextBox> 

After adding the position style we need to set the equal width for both textbox and
 dropdownlist control.
<asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" style="width:140px" runat="server">

<asp:ListItem Value="test1" >test1</asp:ListItem>

<asp:ListItem Value="test2">test2</asp:ListItem>

</asp:DropDownList>

After adding the Styles we need to create javascript function. This function is used to display the selected dropdwon
text into textbox control.

<script language="javascript" type="text/javascript">

function DisplayText()
{
    document.getElementById("txtDisplay").value = document.getElementById("ddSelect").value;
    document.getElementById("txtDisplay").focus();
}
</script>
After adding the javascript function. use this function for Dropdown change event fires.
Add the following code into Default.aspx.cs file.

protected void Page_Load(object sender, EventArgs e)
{
         ddSelect.Attributes.Add("onChange", "DisplayText();");
}