Extension method with default parameter value and fastest way to convert with minimal chace of exception

public static T? ToTypeOrNull<T>(this object val, T? alt = null) where T : struct, IConvertible
        {
            var strVal = Convert.ToString(val);
            switch (typeof(T).Name)
            {
                case "Boolean":
                    bool vBool;
                    if (bool.TryParse(strVal, out vBool))
                        return ChangeType<T>(vBool);
                    break;
                case "Byte":
                    byte vByte;
                    if (byte.TryParse(strVal, out vByte))
                        return ChangeType<T>(vByte);
                    break;
                case "Char":
                    char vChar;
                    if (char.TryParse(strVal, out vChar))
                        return ChangeType<T>(vChar);
                    break;
                case "SByte":
                    sbyte vSByte;
                    if (sbyte.TryParse(strVal, out vSByte))
                        return ChangeType<T>(vSByte);
                    break;
                case "Int16":
                    short vShort;
                    if (short.TryParse(strVal, out vShort))
                        return ChangeType<T>(vShort);
                    break;
                case "Int32":
                    int vInt;
                    if (int.TryParse(strVal, out vInt))
                        return ChangeType<T>(vInt);
                    break;
                case "Int64":
                    long vLong;
                    if (long.TryParse(strVal, out vLong))
                        return ChangeType<T>(vLong);
                    break;
                case "Float":
                    float vFloat;
                    if (float.TryParse(strVal, out vFloat))
                        return ChangeType<T>(vFloat);
                    break;
                case "Double":
                    double vDouble;
                    if (double.TryParse(strVal, out vDouble))
                        return ChangeType<T>(vDouble);
                    break;
                case "Decimal":
                    decimal vDecimal;
                    if (decimal.TryParse(strVal, out vDecimal))
                        return ChangeType<T>(vDecimal);
                    break;
                case "DateTime":
                    DateTime vDateTime;
                    if (DateTime.TryParse(strVal, out vDateTime))
                        return ChangeType<T>(vDateTime);
                    break;
                case "TimeSpan":
                    TimeSpan vTimeSpan;
                    if (TimeSpan.TryParse(strVal, out vTimeSpan))
                        return ChangeType<T>(vTimeSpan);
                    break;
            }
            try
            {
                return ChangeType<T>(strVal);
            }
            catch { }
            return alt;
        }

private static T ChangeType<T>(object val) where T : struct, IConvertible
        {
            return (T)Convert.ChangeType(val, typeof(T));
        }

public static T ToType<T>(this object val, T alt = default(T)) where T : struct, IConvertible
        {
            try
            {
                return val.ToTypeOrNull<T>().GetValueOrDefault(alt);
            }
            catch
            {
                return alt;
            }
        }




Calculating Distance between two Latitude and Longitude Geo Coordinates

//Calculate distance by cordinates
        public static double CalculateDistance(string unit, double latitude1, double lon1, double latitude2, double lon2)
        {
            var theta = lon1 - lon2;
            var dist = Math.Sin(DegreetoRadian(latitude1)) * Math.Sin(DegreetoRadian(latitude2)) + Math.Cos(DegreetoRadian(latitude1)) * Math.Cos(DegreetoRadian(latitude2)) * Math.Cos(DegreetoRadian(theta));
            dist = Math.Acos(dist);
            dist = RadiantoDegree(dist);
            dist = dist * 60 * 1.1515;// Miles as default
            switch (unit)
            {
                case "Kilometers":
                    dist = dist * 1.609344;
                    break;
                case "NauticalMiles":
                    dist = dist * 0.8684;
                    break;
            }
            return (dist);
        }

        //Converts decimal degrees to radians
        public static double DegreetoRadian(double deg)
        {
            return (deg * Math.PI / 180.0);
        }

        //Converts radians to decimal degrees
        public static double RadiantoDegree(double rad)
        {
            return (rad / Math.PI * 180.0);
        }




List of country state city with postal code in MS SQL Databaes and flat text file

There are many paid and free services online with limited data. The problem with them is they provide a limited number of request per user or per api connection. I managed to create a SQL database from data provided by GeoNames with cities and postal code from major countries.
Download Links:

Download MS SQL 2014 Database

Download Flat text file format




Jquery to swap or move table column, works in repeater, datalist, gridview.

<script type="text/javascript" language="javascript">
//Extension method to swap columns
jQuery.moveColumn = function (table, from, to) {
var cols;
jQuery('tr', table).each(function () {
cols = jQuery(this).children('th, td');
cols.eq(from).detach().insertBefore(cols.eq(to));
});
}

$(document).ready(function () {
//Usage
jQuery.moveColumn($('table'), 2, 0);
});
</script>




Find duplicate in SQL and delete

A simple query for finding duplicates in a table. You can use this query to find duplicate values in one or more columns.
For single column
SELECT
    Field1, Count(*)
FROM TableName
Group By Field1
HAVING COUNT(*) > 1

Now delete rows with duplicate records
WHILE(EXISTS(SELECT MAX(ID)
    FROM TableName
    Group By Field1
    HAVING COUNT(*) > 1)
DELETE TableName
WHERE ID IN
(
    SELECT
        MAX(ID)
    FROM TableName
    Group By Field1
    HAVING COUNT(*) > 1
)

For duplicate in multiple columns (two or more)
SELECT
    Field1, Field2, Field3, Count(*)
FROM TableName
Group By Field1, Field2, Field3
HAVING COUNT(*) > 1

Now delete rows with duplicate records
WHILE(EXISTS(SELECT MAX(ID)
    FROM TableName
    Group By Field1, Field2, Field3
    HAVING COUNT(*) > 1)
DELETE TableName
WHERE ID IN
(
    SELECT
        MAX(ID)
    FROM TableName
    Group By Field1, Field2, Field3
    HAVING COUNT(*) > 1
)




ASPX to HTML

private void WebPageToString(string url)
{
var webRequest = WebRequest.Create(url);
var webResponse = webRequest.GetResponse();
var streamObject = webResponse.GetResponseStream();
var streamReader = new StreamReader(streamObject);
var htmlText = streamReader.ReadToEnd();
streamReader.Close();
}




Jquery's cross domain ajax call

Jquery:
$(document).ready(function() {
var surl = "http://www.yoursite.com/webservice.asmx";
$.ajax({
type: 'GET',
url: surl,
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { MemberID: 1054 },
dataType: "jsonp",
success: function(msg) {
$.each(msg, function(name, value) {
alert(value);
});
},
error: function(xhr, status, error) { alert('Servidor de error 404 !!'); },
async: false,
cache: false
});
});

    [WebMethod]
    public void JsonPTest(int a, int b)
    {
        int original_result = a + b;
        var context = HttpContext.Current;

        // Prepare
        string callback = context.Request.Params["callback"];
        string json = "{c: " + original_result + "}";//Newtonsoft.Json.JsonConvert.SerializeObject(...);
        string response = string.IsNullOrEmpty(callback) ? json : string.Format("{0}({1});", callback, json);

        // Response
        context.Response.ContentType = "application/json";
        context.Response.Write(response);
    }




Compare files and find duplicates to save lots of space (Free App)

Sometime we run out of space and can't delete anything important. Specially for professionals, the official documents and project files may consume some extra space and their backups are not easily manageable unless we use some profession versioning system like SVN. Regardless of the file name the code provided compare each byte in any two given files and returns a true value if files have same data. I've manage to create a simple desktop application to find out duplicate files and moves them to a separate folder for later action. This app is free to use and download. Application requirement is latest .net framwork.

bool FileCompare(string file1, string file2)
{
int file1byte;
int file2byte;
FileStream fs1;
FileStream fs2;

if (file1 == file2)
return true;

fs1 = new FileStream(file1, FileMode.Open, FileAccess.Read);
fs2 = new FileStream(file2, FileMode.Open, FileAccess.Read);

if (fs1.Length != fs2.Length)
{
fs1.Close();
fs2.Close();
return false;
}

do
{
file1byte = fs1.ReadByte();
file2byte = fs2.ReadByte();
}
while ((file1byte == file2byte) && (file1byte != -1));

fs1.Close();
fs2.Close();

return ((file1byte - file2byte) == 0);
}




301 Redirect

301 redirect is the most efficient and SEO Friendly method for webpage redirection. It's not that hard to implement and it should preserve your search engine rankings for that particular page. If you have to change file names or move pages around, it's the safest option. The code "301" is interpreted as "moved permanently".

  • In IIS Manager, right click on the file or folder you wish to redirect
  • Select the radio titled "a redirection to a URL".
  • Enter the redirection page
  • Check "The exact url entered above" and the "A permanent redirection for this resource"
  • Click on 'Apply'
From the code behind:-
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.
vikasrana..com");

In latest dot net framework:
Response.RedirectPermanent("http://www.vikasrana.com/");




Street View in your site with Google Maps

<script src="http://maps.google.com/maps?file=api&v=2&key=yourApiKey&sensor=false"
type="text/javascript"></script>

<script type="text/javascript">
var map;
var myPano;
var panoClient;
var nextPanoId;

function addToMap(response) {
var place = response.Placemark[0].Point;
var fenwayPark = new GLatLng(place.coordinates[1], place.coordinates[0]);

var fenwayPOV = { yaw: 0, pitch: 0 };
panoClient = new GStreetviewClient();
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(fenwayPark, 15);
GEvent.addListener(map, "click", function(overlay, latlng) {
panoClient.getNearestPanorama(latlng, showPanoData);
});

myPano = new GStreetviewPanorama(document.getElementById("pano"));
myPano.setLocationAndPOV(fenwayPark, fenwayPOV);
GEvent.addListener(myPano, "error", handleNoFlash);
panoClient.getNearestPanorama(fenwayPark, showPanoData);
}

function showPanoData(panoData) {
if (panoData.code != 200) {
//GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
return;
}
nextPanoId = panoData.links[0].panoId;
var displayString = [
"Location: " + panoData.location.description,
//"Panorama ID: " + panoData.location.panoId,
"LatLng: " + panoData.location.latlng,
//"Copyright: " + panoData.copyright,
//"Next Pano ID: " + panoData.links[0].panoId
].join("<br/>");
map.openInfoWindowHtml(panoData.location.latlng, displayString);

//GLog.write('Viewer moved to' + panoData.location.latlng);
myPano.setLocationAndPOV(panoData.location.latlng);
}

function next() {
// Get the next panoId
// Note that this is not sophisticated. At the end of the block, it will get stuck
panoClient.getPanoramaById(nextPanoId, showPanoData);
}

function handleNoFlash(errorCode) {
if (errorCode == 603) {
alert("Error: Flash doesn't appear to be supported by your browser");
return;
}
}
$(document).ready(function() {
new GClientGeocoder().getLocations('<%=Address %>', addToMap);
});
</script>

<div id="map_canvas" style="width: 350px; height: 200px">

<div name="pano" id="pano" style="width: 350px; height: 250px">