JG Vimalan's Blog

It is all about coding!

Shortcut to collapse javascript fuctions in Visual Studio 2012

There are times where you will have lot of functions in your javascript file and you want to collapse them all. Use the following shortcut keys to achieve it,

Ctrl+M,Ctrl+O

August 1, 2014 Posted by | JavaScript | Leave a comment

Dynamic columns in jqGrid

In this post we are going to see how to display jqGrid with dynamic columns.
I am using the following plugins and languages for preparing this article,
a. jqGrid 4.5.4 plugin
b. jQuery 1.8.2
c. ASP.NET WebForms
d. C#
e. Visual Studio 2012

Step 1:

I am assuming that you already have an ASP.NET project configured with jqGrid plugin.
The first thing to do is, create a class as shown below to hold the column header names, model names and actual data generated at runtime.

public class Dashboard
{
private List _model = new List();
//at runtime you will know the column names, set them here.
public List Model
{
get
{
return _model;
}
set
{
_model = value;
}
}

private List _headers = new List();
//if you want to give more meaningful names for column, set them here.
//The order of model name should match with header name
public List Headers
{
get
{
return _headers;
}
set
{
_headers = value;
}
}
//Store the actual data generated at runtime here.
//I converted datatable generated at runtime in to List<Dictionary<string, object>>
public List<Dictionary<string, object>> DashboardContent { get; set; }

}

Step 2:

In your ASP.NET page, define table controls as shown below,

<table id=”ReportGrid”></table>
<div id=”ReportGridPager”></div>

Step 3:

In the code behind, write the WebMethod that returns the Dashboard object.

[WebMethod]
public static Dashboard GetReportDashboard()
{
//In the ‘GetDailyDashboard’ method, you will get dynamic data from database
//and build the datatable at runtime. Then get the columns, headers from datatable and set it to
//Model and Headers property in Dashboard object. Also convert the datatable to
//List<Dictionary<string, object>> object and set it to DashboardContent property.

return ReportQueryManager.GetDailyDashboard();
}

Step 4:

In your javascript file, which holds the logic to build jqGrid on table object use the following code,

Basically, in the AJAX success method, get the Dashboard property values and set them to
jqGrid properties and bind the data to jqGrid.

$.ajax({
url: methodUrl, //set the method url here
dataType: “json”,
type: ‘POST’,
data: null,
contentType: “application/json; charset=utf-8”,
success: function (data) {
var dataArray = data.d //here you get the Dashboard object

var reportModel = dataArray.Model //Model property in Dashboard object
var header = dataArray.Headers ////Header property in Dashboard object
var dashboardData = dataArray.DashboardContent //Actual data with column

var ColModel = [];
for (index in reportModel ) {
var colName = reportModel[index]
var colWidth = 100
var isFixed = false
var sortTypeValue = “int”
var alignPosition = ‘center’

if (colName == “Name”) {
isFixed = true
colWidth = 300
sortTypeValue = “text”
alignPosition = ‘left’
}
ColModel.push({ name: colName, index: name, frozen: isFixed, width: colWidth, sorttype: sortTypeValue,
align: alignPosition });
}

var customButton = function (options) {
ReportGrid.jqGrid(‘navButtonAdd’, pageSelector, options);
ReportGrid.jqGrid(‘navButtonAdd’, ‘#ReportGrid’ + “_toppager”, options);
};

ReportGrid.jqGrid({
datatype: “local”,
mtype: “GET”,
cmTemplate: { sortable: true, resizable: true },
height: $(document).height() – reduceGridHeight,
rowNum: 20,
rowList: [],
altRows: true,
altclass: ‘gridAltRowClass’,
gridview: true,
pgbuttons: false,
loadonce: true,
shrinkToFit: false,
autoencode: true,
sortname: null,
width: $(“#SerReportGridWrapper”).width(),
ignoreCase: true,
viewrecords: true,
sortorder: “desc”,
pager: pageSelector,
pgtext: null,
scrollrows: true,
loadui: ‘disable’,
colNames: header, //set the header object here
colModel: SerColModel, //set the model object here
caption: “Dashboard”
});

ReportGrid.jqGrid(‘navGrid’, ‘#ReportGridPager’, {
view: true, add: false, edit: false, del: false, refresh: false, search: false, viewtext: ‘View Selected Row’
}, {}, {}, {}, {},
{ width: 400 });

ReportGrid.jqGrid(‘setFrozenColumns’);

customButton({
caption: “Export To Excel”,
title: “Export To Excel”,
onClickButton: function () {
if (serReportGrid.jqGrid(‘getGridParam’, ‘records’) == 0) {
Block(ReportGridBox, “No record(s) found to export”)
}
else {
Export()
}
}
});

ReportGrid[0].addJSONData(dashboardData);
},
error: function (d) {
if (d.statusText != ‘abort’) {
$.unblockUI();
$(“#ErrorMessage”).show()
}
}
});

Thats all. Now, you will be able to display dynamic columns in your jqGrid.

February 23, 2014 Posted by | ASP.NET, C#.NET, JavaScript, jqGrid, JQuery, JSON | , | 2 Comments

Escape double quotes in JavaScript

There may be situations where you need to escape double quotes in JavaScript.  In order to do that, you can use the replace function as shown below,

var note = “I am “Vim”, software developer”;

note = note.replace(/[“]/g, “\\\””);

Output:

Escape Double Quotes - JS

February 7, 2013 Posted by | JavaScript | Leave a comment

Save xml file in client machine without user interaction using asp.net

I got a task where I need to save an xml file in client machine whenever user vists a specific asp.net webpage. As my web application is IE compatible only, I have not verified this solution in other browsers.

In the following code I am going to read an xml file (data source) from the server and paste it in the client machine. The data source can be a session object, a variable in the code behind or a value in hidden field in asp.net page. My sample project structure is given below,

As a first step, add reference to jquery in your aspx page. Using jquery ajax, read the xml file. Then, using FileSystemObject ActiveX create the file in the target location. Then populate the file with the xml object.

Complete code is given below,

<head runat=”server”>
<title>Process XML using jQuery</title>
<script src=”Scripts/jquery-1.7.2.min.js” type=”text/javascript”></script>

<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {;
$.ajax({
type: “GET”,
url: “UserInfo.xml”,
dataType: “xml”,
success: function (xmlObj) {
var fileSystemObject = new ActiveXObject(“Scripting.FileSystemObject”);
varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0);
varFileObject.write(xmlObj.xml);
varFileObject.close();
alert(“Download complete”);
close();
},
error: function () {
alert(“Download failed. Please contact the administrator.”);
}
});
});

</script>

This does not require any user interaction. I am displaying javascript alert messages just for testing purpose.

In the line, varFileObject = fileSystemObject.OpenTextFile(“C:\\Data\\UserInfo.xml”, 2, true, 0); parameter true creates the file if it does not exist.

September 21, 2012 Posted by | ASP.NET, JavaScript, JQuery, VS 2010 | 6 Comments

Setting css class with javascript

In this post, I am going to explain about setting css class for controls using javascript.

The following javascript will give you an idea of setting css class to a control for IE and other browsers.

//Javascript

var anchl = document.getElementById(‘largeFontSwitch’); //Id of the control

//Remove class
anchl.setAttribute(“class”, “”); //Other browsers
anchl.className = “”; //IE

//Set class

anchl.setAttribute(“class”, “selectedFont”); //Other browsers
anchl.className = “selectedFont”; //IE

September 6, 2011 Posted by | JavaScript | Leave a comment

Read AppSettings in JavaScript

The following code snippet provides information on reading AppSettings value in JavaScript.

<script type=”text/javascript” >

        window.location = ‘<%=(System.Configuration.ConfigurationManager.AppSettings[“DefaultRedirectUrl”].ToString()) %>’;

</script>

August 16, 2011 Posted by | ASP.NET, JavaScript | Leave a comment