Saturday, March 29, 2014

Asp.net Read/insert data into XML file and bind data to DataList

Introduction

Here I will explain how to insert data into XML and how to retrieve data from XML and how to bind data to DataList using asp.net.

Description:

XML means Extensible markup language why we need to use this one because by using XML we can store the data and we can easily retrieve and display the data without using database in our applications.if we need to display dynamic data in our application it will take time to conenct database and retrive data from database but if use XML to store data we can do operations with xml file directly without using database. If we store data in database that is incompatible to some of the computer applications but if we store data in XML format it will support for all applications. It is independent for all software applications and it is accessible with all applications.

Now I will explain inserting data into xml and retrive data from XML and bind data to datalist with simple example.

Design your aspx page like this

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width: 100px">
Name:</td>
<td style="width: 100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Location:</td>
<td style="width: 100px">
<asp:TextBox ID="txtLocation" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Email:</td>
<td style="width: 100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px" valign="top">
Comments:</td>
<td style="width: 100px">
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="104px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td>
</tr>
</table>
<br />
<asp:DataList ID="dlComments" Runat="server" Width="100%">
<ItemTemplate>
<hr size=0/>
Name: <%# DataBinder.Eval(Container.DataItem, "name") %><br />
E-mail: <a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%# DataBinder.Eval(Container.DataItem, "email") %></a><br />
Location: <%# DataBinder.Eval(Container.DataItem, "location") %><br />
Date: <%# DataBinder.Eval(Container.DataItem, "Date") %><br />
Description: <%# DataBinder.Eval(Container.DataItem, "Description") %>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>


After that add XML file to your application and give name as "Sample.xml" intially xml file like this root element is compulsary for XML files that’s why I added CommentInformation in XML file that root element in XML file.



 



<?xml version="1.0" encoding="utf-8"?>
<CommentsInformation>
 </CommentsInformation>


 



CodeBehind



------------------



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Xml;
using System.Data;
public partial class Default5 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Bind xml data to datalist
            BindDatalist();
        }
    }
    /// <summary>
    /// btnSubmit event is used to insert data into XML file
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath("Sample.xml"));
        XmlElement parentelement = xmldoc.CreateElement("Comments");
        XmlElement name = xmldoc.CreateElement("Name");
        name.InnerText = txtName.Text;
        XmlElement location = xmldoc.CreateElement("location");
        location.InnerText = txtLocation.Text;
        XmlElement email = xmldoc.CreateElement("Email");
        email.InnerText = txtEmail.Text;
        XmlElement Description = xmldoc.CreateElement("Description");
        Description.InnerText = txtComments.Text;
        XmlElement date = xmldoc.CreateElement("Date");
        date.InnerText = DateTime.Now.ToString();
        parentelement.AppendChild(name);
        parentelement.AppendChild(location);
        parentelement.AppendChild(email);
        parentelement.AppendChild(Description);
        parentelement.AppendChild(date);
        xmldoc.DocumentElement.AppendChild(parentelement);
        xmldoc.Save(Server.MapPath("Sample.xml"));
        BindDatalist();
    }
    /// <summary>
    /// Bind xml data to datalist
    /// </summary>
    private void BindDatalist()
    {
        XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample.xml"));
        DataSet ds = new DataSet();
        ds.ReadXml(xmlreader);
        xmlreader.Close();
        if (ds.Tables.Count != 0)
        {
            dlComments.DataSource = ds;
            dlComments.DataBind();
        }
        else
        {
            dlComments.DataSource = null;
            dlComments.DataBind();
        }
    }
}


 



Output:



Xml Image

Sunday, March 9, 2014

ASP.Net : Google Maps V3 with Multiple Markers Database Example

CREATE TABLE [dbo].[Locations](
	[Name] [varchar](50) NOT NULL,
	[Latitude] [numeric](18, 6) NOT NULL,
	[Longitude] [numeric](18, 6) NOT NULL,
	[Description] [varchar](300) NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
	[Name] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT INTO Locations
SELECT 'Mumbai', 18.9647, 72.8258, 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
UNION ALL
SELECT 'Pune', 18.5236, 73.8478, 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
UNION ALL
SELECT 'Alibaug', 18.6414, 72.8722, 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GoogleMap_Default" %>
<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    var markers = [
    <asp:Repeater ID="rptMarkers" runat="server">
    <ItemTemplate>
             {
                "title": '<%# Eval("Name") %>',
                "lat": '<%# Eval("Latitude") %>',
                "lng": '<%# Eval("Longitude") %>',
                "description": '<%# Eval("Description") %>'
            }
    </ItemTemplate>
    <SeparatorTemplate>
        ,
    </SeparatorTemplate>
    </asp:Repeater>
    ];
    </script>
    <script type="text/javascript">
        window.onload = function () {
            var mapOptions = {
                center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var infoWindow = new google.maps.InfoWindow();
            var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
            for (i = 0; i < markers.length; i++) {
                var data = markers[i]
                var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: data.title
                });
                (function (marker, data) {
                    google.maps.event.addListener(marker, "click", function (e) {
                        infoWindow.setContent(data.description);
                        infoWindow.open(map, marker);
                    });
                })(marker, data);
            }
        }
    </script>
    <div id="dvMap" style="width: 500px; height: 500px">
    </div>
    </form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class GoogleMap_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            // For Single record use below code
            //DataTable dt = this.GetData("select * from Locations where Name='Pune'");
            //For multiple record use below code
            DataTable dt = this.GetData("select * from Locations");
            
            rptMarkers.DataSource = dt;
            rptMarkers.DataBind();
        }
    }
    private DataTable GetData(string query)
    {
        string conString = ConfigurationManager.ConnectionStrings["masterConnectionString"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}


Map1



Source : http://www.aspsnippets.com/Articles/ASPNet-Google-Maps-V3-with-Multiple-Markers-Database-Example.aspx



Download:



https://onedrive.live.com/redir?resid=CA4A7B09B8F914E8!319&authkey=!AIU7vEw1-34-2Gw&ithint=file%2c.zip

Saturday, March 1, 2014

Custom DropDownList

Download:
------------
Source : http://patrickkunka.github.io/easydropdown/
(or)
https://onedrive.live.com/redir?resid=CA4A7B09B8F914E8!318&authkey=!AJ1H68jcK6IyEGs&ithint=file%2c.rar


Custom_Dropdown