Download Excel with AJAX Request

This is a simple example where we will discuss how we can download excel through ajax request. This example will use jquery and .net mvc and NPOI framework to create an Excel worksheet.

Below is the snippet where we are making an ajax call to an action method on controller on button click.

 


$(document).ready(function () {

$('.js-getExcel').on('click', function (e) {
e.preventDefault();
var $this = $(this);
if ($this.hasClass("processing")) {
console.log("Form submission in progress..");
return false;
}
$this.addClass("processing");
var $form = $this.closest('form');
var url = $form.attr("action");
$.getJSON(url, function (result) {
$this.removeClass("processing");
if (result && result.success) {
var arr = ['MyFileName_', getFormattedTime(), '.xls'];
var fileName = arr.join('');
var a = document.createElement("a");
a.href = "data:application/octet-stream;base64," + result.response;
a.download = fileName;
a.click();
} else {
$('.js-message').html(result.response).show().delay(8000).hide(400);
}
});
return false;
});
});

function getFormattedTime() {
var today = new Date();
var y = today.getFullYear();
var mo = today.getMonth() + 1;
var d = today.getDate();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return y + "-" + mo + "-" + d + "-" + h + "-" + m + "-" + s;
}

Below is the snippet of controller action.


public JsonResult ExportExcel(Model model)
{
List report = new List();
try
{
// populate report Object with data you want to write to excel
var workBook = WriteToExcel(report, "xls");

//Write the Workbook to a memory stream
MemoryStream output = new MemoryStream();
workBook.Write(output);
String file = Convert.ToBase64String(output.ToArray());
return Json(new { success = true, response = file }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = false, response = ex.Message }, JsonRequestBehavior.AllowGet);
}
}

private IWorkbook WriteToExcel(List report, string extension)
{
IWorkbook workbook;

if (extension == "xls")
{
workbook = new HSSFWorkbook();
}
else
{
throw new Exception("This format is not supported");
}

ISheet sheet = workbook.CreateSheet("SheetName");

//make a header row
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Id");
headerRow.CreateCell(1).SetCellValue("Name");

//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);

int rowNumber = 1;

foreach (var item in report)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber++);

//Set the Values for Cells
row.CreateCell(0).SetCellValue(item.Id);
row.CreateCell(1).SetCellValue(item.Name);

sheet.CreateRow(rowNumber++);
}

for (int i = 0; i < sheet.GetRow(0).PhysicalNumberOfCells; i += 1)
{
sheet.AutoSizeColumn(i);
}
return workbook;
}

 

Posted in C#, javascript, Javascript and Jquery | Tagged , , | Leave a comment

EarthQuake impacts around Kathmandu and Lalitpur

It has been 12 days today of the massive earthquake and I am in Kathmandu. Kathmandu including Lalitpur and Bhaktapur has become almost empty these days, with very less people and vehicles on the road. Few days back i could hear around 3 lakhs people leaving Kathmandu daily.

The city is a hub for almost everything. Many of government offices, embassies, NGOs, ING-Os, agencies and also industry are centralized to Kathmandu. There by making it so much crowded.

Images from different places of Kathmandu and Lalitpur.

Most of the houses have been destroyed and even more houses are cracked. Even a minor earthquake can make them fall. There are lot of such cracked houses now. With these condition, its very risky to stay in such house. Most of the people that have returned back to villages stay in rented house. People have returned back either because their houses in villages have fallen down, or the houses they were living in Kathmandu are cracked and its risky. Also, many of places in city is stinging and there are chances of being ill. Lack of water and other food supplies being expensive in Kathmandu can be the other reason. Also offices, schools and other organizations are not functional for few weeks.

But they will have to soon return back as offices, schools resumes. But i wonder, will there be enough houses for people to stay safely. This trauma of houses rotating around them and this earthquake is going to last long.

Posted in ASP.NET | 1 Comment

Villages near Barpak, Gorkha after Earthquake

Barpak, the name that has become well known to the people all over the world, is the epicenter of the calamitous earthquake that hit Nepal on April 25, 2015. This earthquake which finished all the infrastructure and killed many human lives within seconds in Barpak and its nearby villages namely Muchchok, Simjunj, Ghyachok, Laprak, Saurpani. These villages from Gorkha district lack transportation facilities and telecommunication towers are also down. A lot of damage has occurred and basic needs of living are not fulfilled. We could hardly see any house upright there.

I along with few of my friends reached Muchchok of Gorkha. As the village is very near to Barpak, the effect was so high that not a single house is suitable for living. All the villagers are living outside in tents which is making their life so difficult especially when wind blows hard and there is rain. So it is very hard to maintain proper sanitation making them prone to several diseases.

Food grains got almost completely destroyed making them dependent on noodles, biscuits and other relief materials. The food grains and rice provided has not reach to these remote villages. Villagers need to walk around 6-10 hours to collect these relief materials. They are not interested in collecting these items as they get very less of these items and there is lack of manpower in their home.

We talked with one of the teacher of the village. This is what he has to say about earthquake and its impacts on life.

It’s a high time to try managing all the basic stuffs needed so that people bounce back to their normal life as soon as possible.

Posted in Uncategorized | 1 Comment

HTTP GET and POST

Both HTTP method can achieve the same goals, but making incorrect choice between them can lead to unexpected and potentially harmful results.

Basically GET is used to retrieve remote data, and POST is used to insert/update remote data.
Applications which use the HTTP protocol SHOULD NOT use GET based forms for the submission of sensitive data, because this will cause this data to be encoded in the Request-URI as querystring.

For example you are submitting credentials using HTTP GET request can lead to following, displaying userID and password in queryString which was probably not intended.
e.g GET /login/?username=gokul&password=somevalue

As query strings are transferred openly in GET requests, we have to consider our security and that of our users when dealing with sensitive data like passwords or credit card numbers.

However with HTTP POST request, the data is included in the body of the request. These credentials will be hidden and passed as the body of POST requests:

POST /login/
username=gokul&password=somevalue

So, POST should be used for unsafe actions(i.e Inserts and Updates)

So, what are the advantage of using HTTP GET or whay shouldn’t we use HTTP POST for safe operations
GET requests are more useable:

GET requests can be cached.
GET requests can remain in the browser history.
GET requests can be bookmarked.
GET requests can be distributed & shared.

Thanks for reading.

Posted in ASP.NET | Leave a comment

generate hyphen key

In this example i am trying to do some string manipulation.
Depending on the value of this string different sorts of new hyphenated string will be generated.

Such as
Input String is “data”, output will be “data-1”
Input String is “data-1”, output will be “data-2”
Input String is “data-1a”, output will be “data-1a-1” and so on.

If the suffix of the string is not numerical then new integer value will be appended.

You can better try experimenting this using the fiddle here.


using System;

public class Program
{
public static void Main()
{
string data = "gokul2-5a";
string hyphened_data = string.Empty;
string valueBeforeLastHyphen = string.Empty;
string valueAfterLastHyphen = string.Empty;
int indexOfHyphen = data.LastIndexOf("-");
// If Hypnen is found in ContractCode
if (indexOfHyphen != -1)
{
valueBeforeLastHyphen = data.Substring(0, indexOfHyphen).Trim();
valueAfterLastHyphen = data.Substring(indexOfHyphen + 1).Trim();
// increment valueAfterLastHyphen
int suffixNum;
if (int.TryParse(valueAfterLastHyphen, out suffixNum))
{
hyphened_data = String.Format("{0}-{1}", valueBeforeLastHyphen, suffixNum + 1);
}
else
{
hyphened_data = String.Format("{0}-1", data);
}
}
// Id contractCode has no hyphen
else
{
hyphened_data = String.Format("{0}-1", data);
}

Console.WriteLine(hyphened_data);
}
}

Posted in C# | Leave a comment

C# : new and virtual keywords

Example demonstrate how we can access derived class method without overridng the base class method.
Fiddle

public class Base
{
public virtual void Run()
{
Console.WriteLine("Base running");
}
}

public class Derieved : Base
{
public new void Run()
{
Console.WriteLine("Derieved running");
}
}

public class Program
{
public static void Main()
{
Base b = new Derieved();
var b1 = b as Derieved;
// Always make sure to check if casting worked or not
if (b1 != null)
{
b1.Run(); // Derieved running
}

b.Run(); // Base running
}
}

Posted in C# | Tagged , | Leave a comment

Use and Advantage :private set

Basically, I want to create an instanceof a class, and once the instance is created, the properties of that object should not be allowed to be modified.

Bit tricky, when you hear this for the first time.

It can be achieved through private setter as follows.
Create the instance of the class using the constructor, and initialize the members through it.

Here is the solution:

public class Program
{
public static void Main()
{
Example ab = new Example("Gokul");
//ab.Name="ram"; Compiler Error
}
}

public class Example
{
public string Name { get; private set; }

// Constructor
public Example(string name) {
Name = name;
}

public void SayHi() {
Console.WriteLine(" Hi " + Name);
}
}

Thanks for reading.

Posted in C# | Leave a comment

Excluding object properties while json-stringifying

Example to exclude the properties of javascript object.


var graphic= new GraphicalElement();
graphic.objectType = "CIRCLE";
graphic.data = {
radius: 20
};

//Removes the property objectType from graphic object
graphic.toJSON = function() {
var attrs = {};
for (var attr in this) {
window.console.log(attr);
if ("objectType" !== attr) {
attrs[attr] = this[attr]; // force to string
}
}
return attrs;
};
window.console.log(JSON.stringify(graphic));

Posted in javascript | Tagged , | Leave a comment