Google Maps with ASP.NET MVC

January 10, 2010 A.Sethi Leave a comment

ASP.Net MVC

Once again i am back to my blog. In these days i was working on my project, which i developed using ASP.NET MVC. In that project i was in need of using google maps, for which i tried some of the things and i was able to use it. So i want to share that part with you. In this post i will be telling about “how to use the Google maps with ASP.net MVC”. It is a very simple application in which we will just put the marks(push pin) on the map and will send them back to controller to save them. Later on those can be again used to show it back in the Maps.

Google Map

First we will start with creating a new MVC project. To get the mark form the user we have to show him a map(google). To show him the map we are going to use the javascript function and for that we have to include the javascript api file given by google. http://www.google.com/jsapi?key=[You Key]. You have to get this key from the google so that you can access the map api. http://code.google.com/apis/maps/signup.html

After creating a new project open the index.aspx page in the view section of the project. There in the source view add the following code to get the map

with following lines we are adding the API file


<asp:Content ID"indexHead" ContentPlaceHolderID="HeadContent" runat="server">

<script type="text/javascript" src="http://www.google.com/jsapi?key=[YourKey]"></script>

Following is the code to load the google map in the webpage. You can get the same code from google documentation also with more extra functions and features. But what extra we are doing here is, we are adding all the points in the array so that we can send it back to the controller.


<script type="text/javascript">
var allMarks = [];
google.load("maps", "2");

//This function will help us to add the mark at
//location where user has double clicked. Then
//we will add all the marks in our array so that
//we can send it back to the controller
function initialize() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
GEvent.addListener(map, "dblclick", function(overlay, latlng) {
if (latlng) {
var mark = new GMarker(latlng);
allMarks.push(latlng);
map.addOverlay(mark);
}
});

}
google.setOnLoadCallback(initialize);

Following function is used for sending the data to the controller. It is ajax call with the data as the array and the description. We will be calling the controller with action name. Here we are creating a object GMap containing the data


//This function will be called for saving the mark
//for that it will send the data back to the controller
function saveMap() {

//gmap object with all values of the map mark
var gmap = {
Locations: allMarks,
Description: Description.value
}

//Ajax call for saving the data at the server. It will send the gmap
//object tot the server
            $.ajax({
type: "POST",
url: "/Home/Create",
data: gmap
});
}
</script>

</asp:Content>

That is it. After doing all this we have to write one create function in the HomeController.cs class. Have a look to the following code


public ActionResult Create(GMap gmap)
{
Session["MapData"] = gmap;
return View();
}

As you can see here we have used a GMap type. That type you can create as following


public class GMap
{
public object[] Locations { get; set; }
public string Description { get; set; }
}

Finally we are done with it. Now you can see the following screenshots to get an idea how it is working. Also you can download the sample from here

Google Map in ASP.NET MVC application

Action getting data from the webpage

Categories: ASP.NET, MVC Tags: , ,

.Net RIA Service Part 1

September 3, 2009 A.Sethi Leave a comment

What is a .Net RIA Service

It is set of libraries and tools given, to help develop the Rich internet application in much easier fashion. When we develop silverlight application we need to interact with the server for various reasons. Now .Net RIA Service will make that much easier and better.

In our normal silverlight application we used to interact with the server from the client code to move data in async fashion and managing it. But now .NET RIA Service will just hide it all from you and handles all those stuff. You can concentrate more on what to do with data rather than how to get the data.

It is link between the presentation layer and business logic layer. You can add various kind of validation also to be performed.

you can download these services from here

Now i am developing sample application of RIA Service with silverlight and will post it with complete working details of .net RIA Service

Categories: Silverlight Tags: ,

Exam Time

May 29, 2009 A.Sethi 2 comments

Exams

Hi all i am back now. Sorry for so much of delay :) But in these days i went through various new technologies. Now i will posting on that. First i will post on .NET RIA Service and further on WCF. If anything specific leave a comment for me.

Hi everybody. Thanks for visiting the blog. I am busy with exams so i will not be able to post new articles for few days. But i will try to post various good and nice article listed as soon as possible.

I have a list of nice articles to be posted mainly on following

MVC, JQuery, RESTful Service, RIA Service, WebServices, And others

If you want me to post on some specific topics or issue please leave a comments.

Categories: Towards Next

Glimmer jQuery Effects Designer

May 2, 2009 A.Sethi Leave a comment
Glimmer tool for creating interactive elements using JQuery

Glimmer tool for creating interactive elements using JQuery

It is tool which helps to create interactive elements in the webpage. It is nice tool developed in WPF. You can insert various effects too

Check the following screen shots and visit the glimmer website and check the video. also you can download setup from here

Its a nice tool check at mix

Sample Screen shots of glimmer.

Image Sequence Wizard

Image Sequence Wizard

Categories: JQuery Tags: ,

Event Calendar in MVC application Using jMonthCalendar(JQuery)

April 30, 2009 A.Sethi 9 comments

A good Jquery plugin is available as Event Calendar which can be download from following location.

http://www.bytecyclist.com/projects/jmonthcalendar/
or
http://code.google.com/p/jmonthcalendar/

I used it in one sample project with MVC and loaded certain events from the controller. Which can in return load from the Model. But for the time being in this sample i returned from the controller it self.


public ActionResult Events(string date)
{
MyEvents event1 = new MyEvents            
{
EventID = 11 ,
StartDate = new DateTime(2009,04,01),
Title = "Meeting with Boss",
Description = "Meeting on product release",
CssClass = "Meeting",
URL= "/Home/EventDetails/11"            
};

MyEvents event2 = new MyEvents            
{
EventID = 12,
StartDate = new DateTime(2009, 04, 01),
Title = "Celebration",
Description = "Fathers birthday",
CssClass = "Birthday",
URL = "/Home/EventDetails/12"            
};

string[] stringlist = new string[2];
stringlist[0] = event1.GetJSONResult();
stringlist[1] = event2.GetJSONResult();

return Json(stringlist);
}


For calling the events it did getJson call from the index page where the jMonthCalendar is shown. It will call one of the function the Controller and in return will get the array of the events which will then be sent to the jMonthCalendar. It will load the events. We can add the URL also so that when user clicks the event he will get the complete detail once again with the help of the controller


<script type="text/javascript">
    $().ready(function() {
var options = {

height: 650,
width: 980,
navHeight: 25,
labelHeight: 25,

onMonthChanging: function(dateIn) {
$.getJSON("http://localhost:1511/Home/Events",
function(data) {

//Array of my events                    
var events = new Array();

//Loop and load all the events and load them into the array
                    $.each(data, function(i, item) {

var oResultData = eval('(' + item + ')');
var event = { "EventID": 5, "Date": oResultData.StartDate,
"Title": oResultData.Title, "URL": oResultData.URL,
"Description": oResultData.Description,
"CssClass": oResultData.CssClass
};

events.push(event);

});

//Load the events into the calendar
                    $.jMonthCalendar.ReplaceEventCollection(events);
$.jMonthCalendar.DrawCalendar(dateIn);
});
return true;
},
onEventBlockOver: function(event) {
return true;
},
onEventBlockOut: function(event) {
return true;
},
onDayLinkClick: function(date) {
return true;
},
onDayCellClick: function(date) {
return true;
}
};

var newevents = [];
$.jMonthCalendar.Initialize(options, newevents);
});</script>


Download the sample from following location

EventCalendar

Here are the screen shot of the application.

Event Calendar in MVC Application

Event Calendar in MVC Application

Detail of selected=

Detail of selected Event

Categories: ASP.NET, MVC Tags: , , , ,

File upload in ASP.NET MVC

April 17, 2009 A.Sethi 13 comments

Here is a sample for handling upload of a file, In your MVC application. In this sample i used the Dialog box of JQuery, where user will select the file and will click upload


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    

<h2>Files uploaded to server</h2>    

<div id="dialog" title="Upload files">        
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>        
    <% } %>    
</div>
<a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>
</asp:content>


Then we have to handle this request in the respective controller which is specified in BeginForm of our above code (FileContoller) and action name (Upload). Following will be our code in the FileController Controller for the Upload action


public void Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}

RedirectToAction("Index", "File");
}


Download the sample code from here

File upload in MVC with JQuery Dialog

File upload in MVC with JQuery Dialog

Categories: ASP.NET, MVC Tags: , , ,

Convert ILIST, LIST to DataSet with child tables and relations

April 16, 2009 A.Sethi 6 comments

There was requirement to convert ILIST or LIST to DataSet so that it can be assigned to some of the controls like Grid or DevExpress Grid. For that i have written following class to convert from LIST or ILIST to DataSet

  • Converts only ILIST and LIST
  • Convert sub lists to another table which will be related to the parent list
  • Creates Relation between tables
  • Works only on the properties not on fields. You can easily modify it for that

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace TowardsNext
{
public static class ListConvertor    
{
public static DataSet ConvertToDataSet<T>(IList list)
{
DataSet dataSet = new DataSet();

CreateDataSet(dataSet, typeof(T), false);
FillDataSet(typeof(T), list.ToList(), dataSet, -1);
CreateRelations(dataSet, typeof(T), null);

return dataSet;
}

/// 
/// Create the structure for all the tables in the data set        
/// 
/// Data set in which tables will be created
/// Type of which dataset has to be created
/// Whether current type is a child table        
private static void CreateDataSet(DataSet dataSet, Type type, bool isChildTable)
{
DataTable dataTable = new DataTable(type.Name);

//Create the ID columns for having relation in the tables 
            dataTable.Columns.Add(new DataColumn("ID", typeof(int)));
if (isChildTable)
{
dataTable.Columns.Add(new DataColumn("ParentID", typeof(int)));
}

// Create the structure for the data tables to be
// added in the the data set            
foreach (PropertyInfo pInfo in type.GetProperties())
{
if (pInfo.PropertyType.IsGenericType &&
(pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
// If associate lists are there make then another table
                    CreateDataSet(dataSet,
pInfo.PropertyType.GetGenericArguments()[0],
true);
}
else                
{
dataTable.Columns.Add(new DataColumn(pInfo.Name, pInfo.PropertyType));
}
}

//Add the table to the dataset
            dataSet.Tables.Add(dataTable);
}

/// 
/// Fill all the tables of data set with data in the respective list        
/// 
/// Type of which datatable is to be filled
/// List of data
/// Data Set in which data tables will be filled with data
/// ID of parent record. If -1 one then no parent        
private static void FillDataSet(Type type, IList list, DataSet dataSet, int parentID)
{
PropertyInfo[] propertyInfos = type.GetProperties();
DataTable dataTable = dataSet.Tables[type.Name];
int id = dataTable.Rows.Count + 1;

foreach (object item in list)
{
DataRow row = dataTable.NewRow();

// Set new id and related parent id
                row["ID"] = id;
if (parentID != -1)
row["ParentID"] = parentID;

// Load all the data from the properties of the type
// and save them into the datatable                
foreach (PropertyInfo info in propertyInfos)
{
if (info.PropertyType.IsGenericType &&
(info.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| info.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
IList subList = (IList)info.GetValue(item, null);
if (subList != null && subList.Count > 0)
{
FillDataSet(subList[0].GetType(),
subList,
dataSet, id);
}
}
else                    
{
row[info.Name] = info.GetValue(item, null);
}
}

dataTable.Rows.Add(row);
id++;
}
}

/// 
/// Creates the relation between the tables according to the         
/// type and parent table on field ID and ParentID        
/// 
/// Data set containing parent and child table
/// Type of the list
/// Parent table to which relations has to be done        
private static void CreateRelations(DataSet dataSet, Type type, DataTable parentTable)
{
DataTable dataTable = dataSet.Tables[type.Name];

// If parent table exsits then create relation
// with child table on field Parent ID            
if (parentTable != null)
{
dataSet.Relations.Add(
new DataRelation(parentTable.TableName + "_ID_"
                        + "PARENTID_" + dataTable.TableName,
parentTable.Columns["ID"],
dataTable.Columns["ParentID"]));
}

// Check for other lists under current object
// go for another relation if exists            
foreach (PropertyInfo pInfo in type.GetProperties())
{
if (pInfo.PropertyType.IsGenericType &&
(pInfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
|| pInfo.PropertyType.GetGenericTypeDefinition() == typeof(IList<>)))
{
// If associate lists are there make then another table
                    CreateRelations(dataSet,
pInfo.PropertyType.GetGenericArguments()[0],
dataTable);
}
}
}
}
}


Tested with following code


;public class Student    
{
public string Name { get; set; }
public string Class { get; set; }
}

public class Teacher    
{
public string Name { get; set; }
public string Address { get; set; }
public List<Student> Students { get; set; }
}

class Program    
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
students.Add(new Student { Name = "Ram Prasad", Class = "LKG" });
students.Add(new Student { Name = "Dina Nath", Class = "Prep" });

List<Teacher> teachers = new List<Teacher>();
teachers.Add(
new Teacher{
Name="Om Prakash",
Address="Mangalore",
Students = students
});
teachers.Add(new Teacher                
{
Name = "Om Prakash 2",
Address = "Gurgaon",
Students = students
});

DataSet dataSet = ListConvertor.ConvertToDataSet<Teacher>(teachers);
}
}


It is not tested in all the cases and condition only checked with few cases and requirement. If any problem do reply, i will fix it up and re-post it. After converting we assigned it to devexpress grid and get the following successful output

Grid assigned to parent data table list with all child tables

Grid assigned to parent data table list with all child tables


Crop Image in ASP.NET using JCrop, JQuery

April 13, 2009 A.Sethi 12 comments

You might have seen various websites and web application giving features to Crop your image and save it. That can be done in DHTML or in Javascript. Lets see one example of doing it with the help of JCrop which can be download from here (JCrop)

How to start

1. First include the following file into your project

  • jquery.Jcrop.js
  • jquery.Jcrop.min.js
  • jquery.min.js

or you can directly drag and drop the JCrop folder in your project

JCrop files

JCrop files

2. We need to write code in our page. Include the JQuery function in the page and also add one event for crop control for updation of the cordinates in the variable on selection by users. Check the head section of the page given below

<head runat="server">    
<title></title>    

<script src="js/jquery.min.js"></script>

<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/jquery.Jcrop.js"></script>

<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />

		<script language="Javascript">

		    jQuery(document).ready(function() {
		    jQuery('#cropbox').Jcrop({
		            onSelect: updateCoords
		        });
		    });

		    function updateCoords(c) {
		        jQuery('#X').val(c.x);
		        jQuery('#Y').val(c.y);
		        jQuery('#W').val(c.w);
		        jQuery('#H').val(c.h);
		    };

		</script>
</head>

3. In your body section add following form to your page

<div>        
<asp:Button ID="Submit" runat="server" Text="Crop Image" 
onclick="Submit_Click" />        
<br />        
<br />        
<asp:Image ID="cropedImage" runat="server" Visible="False" />        
<br />        
<br />        

<img src="Sunset.jpg" id="cropbox" />

<asp:HiddenField ID="X" runat="server" />        
<asp:HiddenField ID="Y" runat="server" />        
<asp:HiddenField ID="W" runat="server" />        
<asp:HiddenField ID="H" runat="server" />        

</div>

4. We need to handle the click event of crop button in our code and crop the image there

protected void Submit_Click(object sender, EventArgs e)
{
if (this.IsPostBack)
{
//Get the Cordinates                
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);

//Load the Image from the location
                System.Drawing.Image image = Bitmap.FromFile(
HttpContext.Current.Request.PhysicalApplicationPath + "Sunset.jpg");

//Create a new image from the specified location to                
//specified height and width                
Bitmap bmp = new Bitmap(w, h, image.PixelFormat);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(image, new Rectangle(0, 0, w, h), 
new Rectangle(x, y, w, h), 
GraphicsUnit.Pixel);

//Save the file and reload to the control
                bmp.Save(HttpContext.Current.Request.PhysicalApplicationPath + "Sunset2.jpg", image.RawFormat);
cropedImage.Visible = true;
cropedImage.ImageUrl = ".\\Sunset2.jpg";
}
}

Download complete code from here

Selection by user for Croping

Selection by user for Croping

Cropped Image

Cropped Image

Categories: ASP.NET Tags: , ,

Using JQuery UI in ASP.NET MVC

April 10, 2009 A.Sethi 27 comments

I was developing one application in ASP.NET MVC, where i was in need of displaying Date Picker to the user. But if you generate View with the help of MVC extension then it will display text box for your date field. In order to show the datepicker i used jquery datepicker.
You can download it from JQuery UI here

Step 1

  • Include these files in your project. in the script folder
  • jquery-1.3.2.js
    ui.core.js
    ui.datepicker.js

    Also include the theme folder in project to apply the themes for the respective controls

  • Add the Script reference in your webpage, for that include the following code
  • <script type="text/javascript" src="/../../Scripts/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="/../../Scripts/ui.core.js"></script>
    <script type="text/javascript" src="/../../Scripts/ui.datepicker.js"></script>
    
  • Include the following script in your view page(where you want to show the date picker) giving it a ID. On that ID we will use it as a input. ID should be unique
  • <script type="text/javascript">
     $(document).ready(function(){
    $("#FromDate").datepicker();
    });
    </script>
    

Step 2

  • We need to create a Extension for HtmlHelper Class.
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace System.Web.Mvc.Html
    {
    public static class DatePickerExtension
    {
    public static string DatePicker(this HtmlHelper htmlHelper, string name)
    {
    return "<input type=\"text\" id=\"" + name +
    "\" name=\"" + name + "\" value=\"\"/>";
    }
    }
    }
  • In your view page you have to add the following code to have that control
  •  <label for="fromDate">From date:</label>             
    <%= Html.DatePicker("FromDate")%>

Output :

JQuery UI DatePicker

JQuery UI DatePicker

Categories: ASP.NET, MVC Tags: , , , , ,

Named & Optional Parameter, C# 4.0 Part 2

March 16, 2009 A.Sethi 1 comment

In visual basic we were having optional parameter option which can help you to send only some parameter to methods and reset will take the default values. Same feature is part of C# 4.0 where you can have default values for the parameters.

Optional Parameters & Their default values

Optional Parameters & Their default values


But one more noticeable feature is “named parameter”. You might have seen in VB also that if you want to set any of the parameter no values then you have to leave all other parameters also which are defined after that variable. To sort this out you can use named parameter which specify the name of the parameter and value for it “seats:4” where seats is the parameter and 4 is the value.

Named Parameters

Named Parameters


Both of the features are shown below in sample

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParameterFeatures
{
class Program    
{
static void Main(string[] args)
{
Vehicle car = new Vehicle("V6");
Vehicle van = new Vehicle(seats:4);

Console.WriteLine("Engine : " + car.Engine);
Console.WriteLine("Seats : " + van.Seats.ToString());

Console.ReadLine();
}
}

class Vehicle    
{
public string Engine { get; set; }
public int Seats { get; set; }

public Vehicle(string engine = "V8", int seats = 5)
{
Engine = engine;
Seats = seats;
}
}
}