Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, August 22, 2013

How to show Facebook feeds on ASP.NET webpage


Now a days intergation of SNS - Social Networking Sites links and feeds to web site is common requirement in almost all web application development.

This article helps how to display facebook feeds on webpage in ASP.NET.

Facebook provides API calls to get feeds using TOKEN.

Storing token in web.config, database is good place.

protected void Page_Load(object sender, EventArgs e)
{
FacebookToken.Value=ConfigurationManager.AppSettings["FacebookToken"];
}


Use below ASPX page for displaying Facebook feeds

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Show Facebook Tags</title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {
            $("#FacebookFeeds").attr("data-href", "http://www.facebook.com/" + $("#FacebookToken").val());
            FacebookFeeds(document, 'script', 'facebook-jssdk');
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <h1 align="left">
                Facebook Feeds</h1>
        </div>
        <div>
            <div>
                <div>
                    <div id="fb-root">
                    </div>

                    <script type="text/javascript">
                        function FacebookFeeds(d, s, id) {
                            var js, fjs = d.getElementsByTagName(s)[0];
                            if (d.getElementById(id)) return;
                            js = d.createElement(s); js.id = id;
                            js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
                            fjs.parentNode.insertBefore(js, fjs);
                        }
                     </script>

                    <div id="FacebookFeeds" class="fb-like-box" data-width="400" data-height="600" data-border-color="white"
                        data-show-faces="false" data-stream="true" data-header="false">
                    </div>
                </div>
            </div>
            <!—Code Ends Here//-->
        </div>
    </div>
    <asp:HiddenField ID="FacebookToken" runat="server"></asp:HiddenField>
    </form>
</body>

</html>

Please leave your comments or share this tip if it’s useful for you.

Tuesday, August 20, 2013

How to migrate or upgrade VB project to VB.NET Project


Before .NET, VB was primary language for application development on Windows platform.

Several applications are still running in VB worldwide. End users are habitual with these VB application and don’t want to stop these.

But there are need to change those VB applications to .NET.

However end user / client can’t wait, invest to rewrite all these VB applications to .NET.

So what’s the middle and safe way?

Migration or Upgradation is the only answer. It saves time, money and efforts of both clients as well as developers.

How to migrate or upgrade VB code to VB.NET?

It’s a 5 steps process.

Open VB project file [extension is .VBP] in Visual Studio from either File -> Open -> Project / Solution… or Press Ctrl + Shift + O or click on Open: Project… link on Start Page as below

 

1.   First screen is welcome screen. Just click on Next > button as below

 

2.   This screen asks which type of project you want. Here you have two option – either select .EXE or DLL as per your VB project

 

3.   Specify location of new migrated project

 

4.   At this point, all required information is available to Visual Studio for migration. Click on Next > button as below


5.   Last wizard shows you progress of migration.


Build the migrated project.

After migration, visual studio creates Upgrade report with name “_UpgradeReport.htm” in project itself. This is very useful report. One should have to check it as it includes all passed and failed coding area which finally helps to fix migrated errors.


Please leave your comments or share this tip if it’s useful for you.

Windows… Option - Secrets of Visual Studio


Least known but yet most powerful facility of Visual Studio is Windows… option.

What is Windows…?

Suppose you have 8 windows or forms opened in Visual Studio as below
·         TestPage1.aspx
·         TestPage2.aspx
·         TestPage3.aspx
·         TestPage4.aspx
·         TestPage1.aspx.cs
·         TestPage2.aspx.cs
·         TestPage3.aspx.cs
·         TestPage4.aspx.cs



Now how can you close only some of the forms?

Way 1:-
Close each form one by one by right click on form tab and select Close as below


Way 2:-
Close all opened forms except only selected form by right click on any one form tab and select Close All But This as below


Way 3:-
Close all opened forms from menu Window -> Close All Documents as below


Way 4:-
From ours all 8 opened forms suppose I want only 3 forms should be opened and rest should be closed.

Below forms should be opened
·         TestPage1.aspx
·         TestPage2.aspx
·         TestPage4.aspx.cs

Below forms should be closed

·         TestPage3.aspx
·         TestPage4.aspx
·         TestPage1.aspx.cs
·         TestPage2.aspx.cs
·         TestPage3.aspx.cs

Visual Studio provides to achieve this from its Window… option
This option is available in menu Window -> Windows…  [Last menu item]


On Click on Windows… item, a window should appear

Now select the forms and click on “Close Window(s)”.


All selected forms should be closed.

Also you can activate any forms from Windows… option. Just select any form and click on Activate as below


Your form should appear as selected form in Visual Studio IDE.



Please leave your comments or share this tip if it’s useful for you.

Wednesday, August 14, 2013

How to show directions with route details between two locations on Google maps in ASP.NET

         
For displaying directions with route details first we need latitude and longitude of two locations.

To know how to get Latitude and Longitude of any place in Google maps? Please Visit here

Location 1 is act as source point and location 2 is destination point.

I am considering
·         Source Location - 28.67854, 77.23938 - Red Fort, New Delhi, India
·         Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra

UI Design:-

Here is a screenshot of Google map from Red Fort to Tajmahal






We need to develop similar webpage with same details in ASP.NET



How to do this in ASP.NET using C#?

Google team already developed API for map and its functionality. These API works with JQuery or Javascript.

C# Code

·         Create Location Entity class to store Latitude and Longitude

public class LocationInfo
{
    public string Latitude { get; set; }
    public string Longitude { get; set; }
}

·         Create one Helper class for creating JSON string and registering Javascript.
Include namespcase “using System.Web.Script.Serialization;” in your code for  accessing “JavaScriptSerializer” class

public static class Helper
{
    /// <summary>
    /// Generates Json for specific object instance
    /// </summary>
    /// <param name="instance">Instance to be converted to Json </param>
    /// <param name="recursionDepth">Recursion depth optional paramter</param>
    /// <returns>Json for specific object instance</returns>
    public static string ToJson(this object instance, int recursionDepth) {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize(instance);
    }

    /// <summary>
    /// Register java script
    /// </summary>
    /// <param name="script"></param>
    /// <param name="control"></param>
    public static void BindClientScript(string script, Control control)
    {
        ScriptManager.RegisterStartupScript(control, typeof(Page), Guid.NewGuid().ToString(), script, true);
    }
}


·         Get source and destination location details in entity class from database [Leaving database access part]

//Source Location - Red Fort, New Delhi, India
LocationInfo sourceLocation = new LocationInfo() { Latitude = "28.67854", Longitude = "77.23938" };

//Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
LocationInfo destinationLocation = new LocationInfo() { Latitude = "27.175114", Longitude = "78.042154" };

·         Convert this location entities into its JSON representation as below

string jsonSourceResponse = Helper.ToJson(sourceLocation, 100);
string jsonDestinationResponse = Helper.ToJson(destinationLocation, 100);

·         Register javascript function by passing this Json string as below

string script = "PushLocationData(" + jsonSourceResponse + "," + jsonDestinationResponse + ");";

Helper.BindClientScript(script, this);

ASPX

·         First we need two javascript file. You don’t need to download these file

Map functionality - http://maps.google.com/maps/api/js?sensor=false
JQuery - https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

·         So its declaration in ASPX file is as below

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     

·         Create javascript function to get the JSON string and hold it in javascript global variable as

source = null;
destination = null;

function PushLocationData(objsource, objdestination) {
    source = objsource;
    destination = objdestination;
}

·         Create google maps direction service object as

directionsService = new google.maps.DirectionsService();

·         Get the latitude and longitude of source and destination location [Like X,Y co-ordinates in graph in mathematics]

sourceLatLng = new google.maps.LatLng(source.Latitude, source.Longitude);

destinationLatLng = new google.maps.LatLng(destination.Latitude, destination.Longitude);

·         Set different option of maps like zoom level, alignment of point in map, map type, navigation control as

var mapOptions = {
                    zoom: 15,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    navigationControl: true
                };

·         Create map object with all specified optins and show in DIV as below

map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

·         Specify the way you want directions on google maps as below

directionsRenderer = new google.maps.DirectionsRenderer({
    'map': map,
    'draggable': false,
    'hideRouteList': true,
    'suppressMarkers': true
});

·         Draw route from source to destination location  in driving mode on maps. With each route we will get directions informations such as route description, distance, duration etc. as below

directionsService.route({
    'origin': sourceLatLng,
    'destination': destinationLatLng,
    'travelMode': 'DRIVING'
},

    function(directions, status) {
        for (var i = 0; i < directions.routes.length; i++) {
            var thisRoute = directions.routes[i];

            for (var j = 0; j < thisRoute.legs.length; j++) {
                var thisLeg = thisRoute.legs[j];

                var useDistance = thisLeg.distance.text;
                var useDuration = thisLeg.duration.text;

                var directionsHTML = '';
                for (var k = 0; k < thisLeg.steps.length; k++) {
                    var thisStep = thisLeg.steps[k];
                    directionsHTML += '<div>' + (k + 1) + '. ' + thisStep.instructions + '<BR/>-------------------' + thisStep.distance.text + '</div>';
                    directionsHTML += '<div></div>';
                }
                $('#total_distance').html(useDistance);
                $('#total_duration').html(useDuration);
                $('#direction_steps').append(directionsHTML);
            }
        }
        directionsRenderer.setDirections(directions);

    }
);
                            

Here is complete C# code and ASPX. Just copy and paste below code and bingooooo here you go


C# Code

    public partial class GoogleDirections : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Source Location - Red Fort, New Delhi, India
            LocationInfo sourceLocation = new LocationInfo() { Latitude = "28.67854", Longitude = "77.23938" };

            //Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
            LocationInfo destinationLocation = new LocationInfo() { Latitude = "27.175114", Longitude = "78.042154" };

            string jsonSourceResponse = Helper.ToJson(sourceLocation, 100);
            string jsonDestinationResponse = Helper.ToJson(destinationLocation, 100);

            string script = "PushLocationData(" + jsonSourceResponse + "," + jsonDestinationResponse + ");";
            Helper.BindClientScript(script, this);
        }
    }

    public class LocationInfo
    {
        public string Latitude { get; set; }
        public string Longitude { get; set; }
    }

    public static class Helper
    {
        /// <summary>
        /// Generates Json for specific object instance
        /// </summary>
        /// <param name="instance">Instance to be converted to Json </param>
        /// <param name="recursionDepth">Recursion depth optional paramter</param>
        /// <returns>Json for specific object instance</returns>
        public static string ToJson(this object instance, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(instance);
        }

        /// <summary>
        /// Register java script
        /// </summary>
        /// <param name="script"></param>
        /// <param name="control"></param>
        public static void BindClientScript(string script, Control control)
        {
            ScriptManager.RegisterStartupScript(control, typeof(Page), Guid.NewGuid().ToString(), script, true);
        }
    }

ASPX


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Google Directions with route info</title>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">

        source = null;
        destination = null;

        function PushLocationData(objsource, objdestination) {
            source = objsource;
            destination = objdestination;
        }

        $(document).ready(function() {

            directionsService = new google.maps.DirectionsService();

            //Source Location - Red Fort, New Delhi, India
            sourceLatLng = new google.maps.LatLng(source.Latitude, source.Longitude);

            //Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
            destinationLatLng = new google.maps.LatLng(destination.Latitude, destination.Longitude);

            //set the map options
            var mapOptions = {
                zoom: 20,
                center: destinationLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                navigationControl: true
            };

            //create the map object
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            directionsRenderer = new google.maps.DirectionsRenderer({
                'map': map,
                'draggable': false,
                'hideRouteList': true,
                'suppressMarkers': true
            });

            directionsService.route({
                'origin': sourceLatLng,
                'destination': destinationLatLng,
                'travelMode': 'DRIVING'
            },
            function(directions, status) {
                for (var i = 0; i < directions.routes.length; i++) {
                    var thisRoute = directions.routes[i];

                    for (var j = 0; j < thisRoute.legs.length; j++) {
                        var thisLeg = thisRoute.legs[j];

                        var useDistance = thisLeg.distance.text;
                        var useDuration = thisLeg.duration.text;

                        var directionsHTML = '';
                        for (var k = 0; k < thisLeg.steps.length; k++) {
                            var thisStep = thisLeg.steps[k];
                            directionsHTML += '<div>' + (k + 1) + '. ' + thisStep.instructions + '<BR/>-------------------' + thisStep.distance.text + '</div>';
                            directionsHTML += '<div></div>';
                        }
                        $('#total_distance').html(useDistance);
                        $('#total_duration').html(useDuration);
                        $('#direction_steps').append(directionsHTML);
                    }
                }
                directionsRenderer.setDirections(directions);
            });
        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
    <table style="border: thin solid #000000; font-family: Verdana; font-size: small;"
        width="100%">
        <tr>
            <td valign="top" width="40%">
                <div id="direction_steps_holder" style="width: 100%">
                    <div>
                        <b>Directions to TajMahal, Agra (<span id="total_distance"></span> - about <span
                            id="total_duration"></span>) </b>
                    </div>
                    <div id="direction_steps">
                    </div>
                </div>
            </td>
            <td valign="top">
                <div id="map_canvas" style="width: 750px; height: 700px;">
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>


Similar articles which you may like

Latitude and longitude, showing image, info popup window on google maps are necessary base part of google maps. You can get more info from below articles




Please leave your comments or share this article if it’s useful for you.