Tuesday, December 30, 2014

How to display Google map in Asp.net Page along with Direction Service


This code allow us to learn how to integrate the maps and direction service

Description Work Flow:-

While properly running the code it will display the empty Google maps then

Click two times anywhere in the map the first click will considered as the source and the second click will takes as destination from these two points one poly line will appear with shortest direction between two points.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="Maps._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=Place the API key here"></script>
    <script type="text/javascript" src="../JavaScript/jquery.1.5.min.js"></script>
   
    <script type="text/javascript">
        var dTable;
        var index = -2;
        var registration = 0;
        var lng = -2;
        var direct = -2;
        var MapCitys = [];
        var MapLables = [];
        var ibLabel;
        var objData = {};
        var geocoder;
        var indexone = 0;
        var GroupName = "All Zones";
        var map;
        var clickCount = 0;
        var click1;
        var directionsDisplay;
        var markers = [];

        var directionsService = new google.maps.DirectionsService();

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var mapProp = {
                center: new google.maps.LatLng(17.438523, 78.399038),
                zoom: 13,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            map = new google.maps.Map(document.getElementById("map"), mapProp);
            //var mc = new MarkerClusterer(map);
            directionsDisplay.setMap(map);
            google.maps.event.addListener(map, 'click', function (event) {
                //debugger;
                clickCount = clickCount + 1;
                if (clickCount == 1)
                    click1 = event.latLng
                //debugger;
                if (clickCount == 2) {
                    calcRoute(click1, event.latLng);
                    clickCount = 0;
                    // map = new google.maps.Map(document.getElementById("map"), mapProp);
                }

            });
        }
        function calcRoute(st, en) {
            var start = st;
            var end = en;
            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    //debugger;
                    directionsDisplay.setDirections(result);
                    for (var index = 0; index < result.routes[0].overview_path.length; index++) {
                        var latlngs = new google.maps.LatLng(result.routes[0].overview_path[index].lat(), result.routes[0].overview_path[index].lng())
                        //debugger;
                        var mark = new google.maps.Marker({
                            position: latlngs,
                            map: map
                        });
                        markers.push(mark);
                    }
                    //debugger;
                    var markerCluster = new MarkerClusterer(map, markers);
                    //debugger;
                }
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    <table width="100%">
        <tr>
            <td>
                <div id="map" style="width: 925px; height: 600px" />
            </td>
        </tr>
    </table>
</asp:Content>




Detailed code Explanation :-

This is the main heart for the maps and the library to integrate the Google map in to the page

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&key=Place the API key here"></script>

Download this javascript file and add the reference
jquery.1.5.min.js

Main method to initialize the maps
initialize()

This is the method for drawing the direction with parameters of source, destination latitude and Longitude

calcRoute(Source,Destination)



Read More »

Monday, December 29, 2014

How to convert Data Set to the SQL Lite DB file in Asp.net C#

How to convert Data Set to the SQL Lite DB file in Asp.net C#

Introduction:-

Actually the article is use full for both Android and C# users ,because all the android devices are working with open source DB SQL Lite .All the android users are usually use to create database from SQL Lite .From that we are processing the operation (pushing that data in to main Data base).

For overcome all these situation we tackled this code.

Step1:-  Download the SQL Lite DLL file and add the reference
using System.Data.SQLite;

Step2:-  Make sure all name spaces are mandatory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SQLite;
using System.Data.Common;

Step3:-Create one Dynamic data set for same purpose passing to that method
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Sno");
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
dt.Columns.Add("Status");
dt.Rows.Add(1, "Lokesh", "B.Tech", 10);
dt.Rows.Add(2, "Vijay", "Msc", 50);
dt.Rows.Add(3, "Balaji", "MS", 61);
dt.Rows.Add(4, "Kishore", "B.Tech", 90);
ds.Tables.Add(dt);

Step4:-Create the SQL Lite Conversion Method
private static string SaveAsSqlite(DataSet ds)

and also add the supported methods
private static string GetColumnType(Type type)
private static DbType GetColumnDbType(Type type)




In this code we gave one sample path for saving that DB file in some particular location

                string directoryPath = HttpContext.Current.Server.MapPath("~/TempSql");



The who .cs file is look like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.SQLite;
using System.Data.Common;

namespace SampleTestingCodes
{
    public partial class CreateSQLiteFileFromDataSet : System.Web.UI.Page
    {
        /// <summary>
        /// Saves as sqlite.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns></returns>
        private static string SaveAsSqlite(DataSet ds)
        {
            string tableQuery = string.Empty, insertQuery = string.Empty, valueQuery = string.Empty;
            try
            {
                //You can access this path also like this way
                //string directoryPath = HttpContext.Current.Server.MapPath("../TempSql");
                //
                string directoryPath = HttpContext.Current.Server.MapPath("~/TempSql");
                DirectoryInfo sqlFolder = new DirectoryInfo(directoryPath);
                if (!sqlFolder.Exists)
                {
                    sqlFolder.Create();
                }

                string fileName = string.Format("SampleSQLite_{0}{1}{2}{3}{4}{5}_{6}.db", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, "Lokesh");
                SQLiteConnection con = new SQLiteConnection();
                con.ConnectionString = new DbConnectionStringBuilder()
                        {
                            {"Data Source", HttpContext.Current.Server.MapPath("~/TempSql") + "/" + fileName},
                            {"Version", "3"},
                            {"FailIfMissing", "False"},
                        }.ConnectionString;

                con.Open();
                // Create a table in the database to receive the information from the DataSet
                SQLiteCommand cmd = new SQLiteCommand(con);

                foreach (DataTable table in ds.Tables)
                {
                    cmd.CommandText = "DROP TABLE IF EXISTS " + table.TableName;
                    cmd.ExecuteNonQuery();
                    tableQuery = "CREATE TABLE " + table.TableName + "(";
                    insertQuery = string.Format("INSERT INTO {0} (", table.TableName);
                    valueQuery = " VALUES(";
                    foreach (DataColumn column in table.Columns)
                    {
                        tableQuery += string.Format("{0} {1},", column.ColumnName, GetColumnType(column.DataType));
                        insertQuery += string.Format("{0},", column.ColumnName);
                        valueQuery += string.Format("@{0},", column.ColumnName);
                    }

                    tableQuery = tableQuery.Substring(0, tableQuery.Length - 1);
                    tableQuery += ")";
                    cmd.CommandText = tableQuery;
                    cmd.ExecuteNonQuery();

                    insertQuery = insertQuery.Substring(0, insertQuery.Length - 1);
                    insertQuery += ")";
                    valueQuery = valueQuery.Substring(0, valueQuery.Length - 1);
                    valueQuery += ")";
                    cmd.CommandTimeout = 0;
                    cmd.CommandText = insertQuery + valueQuery;
                    cmd.Parameters.Clear();
                    foreach (DataColumn column in table.Columns)
                    {
                        cmd.Parameters.Add("@" + column.ColumnName, GetColumnDbType(column.DataType));
                    }

                    foreach (DataRow row in table.Rows)
                    {
                        for (int i = 0; i < row.ItemArray.Length; i++)
                        {
                            cmd.Parameters[i].Value = row[i];
                        }

                        cmd.ExecuteNonQuery();
                    }
                }

                cmd.Dispose();
                con.Close();
                con.Dispose();
                return "FILENAME:" + fileName.Replace(".db", string.Empty);
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// Gets the type of the column.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>Returns the sqlite data type</returns>
        private static string GetColumnType(Type type)
        {
            string dataType = string.Empty;
            if (type.Equals(typeof(int)))
            {
                dataType = "INTEGER";
            }
            else if (type.Equals(typeof(float)) || type.Equals(typeof(double)) || type.Equals(typeof(decimal)))
            {
                dataType = "REAL";
            }
            else if (type.Equals(typeof(byte[])))
            {
                dataType = "BLOB";
            }
            else
            {
                dataType = "TEXT";
            }

            return dataType;
        }
        /// <summary>
        /// Gets the type of the column.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>Returns the sqlite data type</returns>
        private static DbType GetColumnDbType(Type type)
        {
            if (type.Equals(typeof(int)))
            {
                return DbType.Int32;
            }
            else if (type.Equals(typeof(float)) || type.Equals(typeof(double)) || type.Equals(typeof(decimal)))
            {
                return DbType.Decimal;
            }
            else if (type.Equals(typeof(byte[])))
            {
                return DbType.Binary;
            }
            else
            {
                return DbType.String;
            }
        }
    }
}




Read More »

Download a file from Asp.net C#

Download a file from Asp.net C#

How to download the file from the server using the asp.net c#

For sample purpose i used one .css file for download

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleTestingCodes
{
    public partial class DownloadingFiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //File Extension
            string Extension = ".css";
            //File Name
            string fileName = "Site";
            //File path Location
            //You can also use this like
            //string path = Server.MapPath("../TempSql/") + fileName + Extension;
            string path = Server.MapPath("~/Styles/") + fileName + Extension;
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + Extension);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/....";
                Response.WriteFile(Server.MapPath("~/Styles/") + fileName + Extension);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }
}


Read More »

Tuesday, December 23, 2014

Simple way to creating the update query for the table in SQL Server

Declare @TableName sysname = 'MemberRegistration'
Declare @result varchar(max) = ''
Declare @StartString varchar(max) = 'Update '+@TableName+' Set'
SELECT
       @result = @result + '
       [' + ColumnName + ']=@' + ColumnName +','
FROM (SELECT
       REPLACE(col.name, ' ', '_') ColumnName,
       column_id,
       (CASE
              WHEN (typ.name = 'nvarchar' OR
                     typ.name = 'varchar') THEN typ.name + '(' + CONVERT(NVARCHAR(10), (col.max_length / 2)) + '),'
              ELSE typ.name + ','
       END) AS ColumnType
FROM sys.columns col
JOIN sys.types typ
       ON col.system_type_id = typ.system_type_id
       AND col.user_type_id = typ.user_type_id
WHERE object_id = OBJECT_ID(@TableName)) t
ORDER BY column_id

SET @result = @StartString + '' + @result + ')
Where '

print @result


Read More »