Asp.Net, C#, Java Script, Jquery, Web

Convert base64 string into file using Java script

Here you find java script code convert base64 string to file. I converted excel file to base64 string to demo example. I did it in c# code.

Code to convert file into Base64

using System;
using System.IO;
using System.Linq;

namespace Demo
{
public class Program
{
public static void Main(string[] args)
{
var fileBytes = File.ReadAllBytes(@”d:\temp.xlsx”);

string encodedFile = Convert.ToBase64String(fileBytes);

Console.WriteLine(“Base 64 Encoded File : {0}”, encodedFile);

var decodedFileBytes = Convert.FromBase64String(encodedFile);

File.AppendAllText(“d:\\temp.txt”,encodedFile);

File.WriteAllBytes(@”d:\newtempfile.xlsx”, decodedFileBytes);
}
}
}

You can expose file upload or download via service where file can be transferred as base64 string.
Java script code to consume base64 string and download as file:

 

function convertBase64ToExcel()
{

var data = “UEsDBBQABgAIAAAAIQBi7p1oXgEAAJAEAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AgAAsQUAAA0AAAAAAAAAAAAAAAAAUBIAAHhsL3N0eWxlcy54bWxQSwECLQAUAAYACAAAACEAChQRqw8CAAA3BQAAGAAAAAAAAAAAAAAAAAABFQAAeGwvd29ya3NoZWV0cy9zaGVldDEueG1sUEsBAi0AFAAGAAgAAAAhAJbKnjo+AQAAUQIAABEAAAAAAAAAAAAAAAAARhcAAGRvY1Byb3BzL2NvcmUueG1sUEsBAi0AFAAGAAgAAAAhAN5BFtmKAQAAEQMAABAAAAAAAAAAAAAAAAAAuxkAAGRvY1Byb3BzL2FwcC54bWxQSwUGAAAAAAoACgCAAgAAexwAAAAA”;

var contentType = ‘application/vnd.ms-excel’;
var blob1 = b64toBlob(data, contentType);
var blobUrl1 = URL.createObjectURL(blob1);

window.open(blobUrl1);

}

function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || ”;
sliceSize = sliceSize || 512;

var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);

var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

var byteArray = new Uint8Array(byteNumbers);

byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, {type: contentType});
return blob;
}

You can find running code here: Jsfiddle

//jsfiddle.net/neerajkaushik_123/s9g9nqa1/6/embedded/

Asp.Net, CodeProject, DotNet, KnockoutJs

CRUD operations using KnockOutJS and Asp.Net MVC3

 

In last posts about knockoutJs, I gave examples of Search, Binding server side model to KnockoutJs ViewModel. I’ll discuss today about sending data back to server so that we can do server side operations. I would like to present it doing CRUD operations for Account entity.

Account entity has AccountId, Name and AccountBalance.

I start with creating Controller’a action methods Search and Update.

Search method expects search criteria to search records and send back to client in json format.

Update method expects accountid, name etc to from client to do server side operations and send back updated values to client in json format.

Controller Class

AccountController

 

 public class AccountController : Controller
    {
        public ActionResult Index()
        {
            return View("Account");
        }

        /// 
        /// Search Method
        /// 
        public JsonResult Search(string SearchCriteria)
        {
            //Temporary Code
            //todo: can write actual search functionality
            Random rnd = new Random();

            return Json(new { AccountId = 1, Name = "test", 
			Balance = rnd.NextDouble() * 93.244d });
        }

        /// 
        /// Save method
        /// 
       public JsonResult Update(int AccountId, string Name)
        {
            ////Temporary Code
            //todo: can write actual update code
            Random rnd = new Random();

            return Json(new { AccountId = AccountId, Name = "test", 
		Balance = rnd.NextDouble() * 93.244d });
        }

    }

View

In view file( Account.cshtml) html controls are bind with viewmodel fields with data-bind attribute.

 

@{
    ViewBag.Title = "Account";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Scripts {
    <script type="text/javascript" src="../../Scripts/Account.js"></script>
}

<div id="search">
    Search By AccountId <input type="text" data-bind="value:SearchCriteria" />
  <p>
        <input type="button" id='btnSearch' title="Search" value="Search" /></p>
</div>

<div>
    <p>
        AccountId:<input type="text" data-bind="value:AccountId" /></p>
    <p>
        Account Name<input type="text" data-bind="value:Name" /></p>
    <p>
       Balance<input type="text" data-bind="value:Balance" /></p>
    <p>
        <input type="button" id='btnSave' title="Save" value="Update" /></p>
</div>

image

Account.Js

We initialize viewModel that is using as knockoutjs viewmodel.

AccountViewModel contains properties AccountId, Name, Balance and two methods Search and Update.

Search Method:  It sends self.SearchCriteria value in ajax request to call controller action method ie. Search.

Response: an object with AccountId, Name and Balance is returning from server and knockoutjs view model’s properties are further setting up from response.

As view model’s properties are observable in nature here, therefore html controls bind to these values will automatically display changed values.

Update Method: This method sends Ajax request to server (controller action method). Input parameters are from viewmodel ie. AccountId and Name. Similarly we can create Delete,Add method to delete and Add records respectively.

var accountmodel;

$(document).ready(function () {

    //initializing viewmodel

    accountmodel = new viewModel();

    //binding for ko

    ko.applyBindings(accountmodel);

    //bind event

    $("#btnSearch").click({ handler: accountmodel.Search });

    $("#btnSave").click({ handler: accountmodel.Update });


});

function viewModel() {

    var self = this;

    self.AccountId = ko.observable(”);

    self.Name = ko.observable(”);

    self.Balance = ko.observable(null);

    self.SearchCriteria = ko.observable(”);

    self.Search = function () {

        $.ajax({

            url: "Account/Search",

            data: { SearchCriteria: self.SearchCriteria },

            type: "POST",

            success: function (response) {

                self.AccountId(response.AccountId);

                self.Name(response.Name);

            }

        });

    };

    self.Update = function () {

        $.ajax({

            url: "Account/Update",

            data: { AccountId: self.AccountId, Name: self.Name },

            type: "POST",

            success: function (response) {

                self.AccountId(response.AccountId);

                self.Name(response.Name);

                self.Balance(response.Balance);

            }

        });

    }

};

image

You can find code here.

Asp.Net, CodeProject, DotNet, KnockoutJs

Implement Jquery.tmpl (template) with KnockoutJS, Asp.Net Mvc3

In continuation of my previous post on search implementation using knockoutjs. In previous example I bind grid with knockoutjs observable array object. Because of observable characteristics, once view model update then knockoutjs engine render html controls which are bound to that view model. I found one problem in it when dealing with huge data.

I had a requirement to show thousands of records in grid without paging. If I use knockoutjs way of binding with html table it takes time to load and browser also popup message about “Unresponsive script” which ask to further render or to stop script.

I wanted to use same view model for data but i didn’t want to use “data-bind” attribute in html. I found one of good plugin of jquery (jQuery.tmpl) through which we can define template and can inject data in runtime. Here I’ll show you how to implement it. I am using same code base which I used in previous post.

 

How to reproduce error?

Let say I am adding 20000 employees in collection and it will render on UI.

image

Binding with HTML table:

 

image

 

I get following error message.

 

image

 

Solution:

Implementation of Jquery.tmpl

To avoid this message and to render data fast I choose jquery.tmpl to render html table.

Here are steps which will define step by step implementation:

Step1 : download Jquery.tmpl.js file from jquery

http://github.com/jquery/jquery-tmpl

http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js

and save in scripts folder.

You can directly reference script file as well if you want.

 

Step 2: Reference jquery.tmpl.min.js in relevant page or _layout.cshtml file.

 

<script src="@Url.Content("~/Scripts/jquery.tmpl.min.js")" 
	type="text/javascript"></script>

 

You can also give direct path from

<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>

 

Step 3: Create blank tbody where data will populate.

<tbody id="datalist"></tbody>

Step 4: Create template of <tr> element in which data will render.

 

image

Step 4: Populate data in template.

 

image

 

Step 5: Run application.

image

 

image

 

You can find code here.

Asp.Net, DotNet, Java Script, Web

Implement Search screen using knockoutjs, Jquery and asp.net mvc3

 

Here I am trying to explain steps for how to use knockoutjs viewmodel, jquery ajax request in asp.net mvc3 project.

I am taking practical example to show behaviour. This example will have simple UI screen with search textbox and button. When click on search button ajax request will go to server and will call action method of controller class which will return results in json format, then we will see how json result will bind to viewmodel and html controls.

Following is flow of information across different layers:

 

image

 

Let’s start implementation.

Implementation

Model

Create model class Employee.

 

class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Dept { get; set; }
    }

Controller

  • Create Controller class in controller folder i.e. EmployeeController
  • Implement Action method “Search” which will search on empname.
public JsonResult Search(string EmpName)
        {
            var emplist = PrepareEmpList();

            var searchedlist= from emp in emplist
                            where emp.Name.Contains(EmpName)
                            select emp;

            return Json(new { Items = searchedlist});
        }

        private static List PrepareEmpList()
        {
            var emplist = new List();
            //create list of employee
            for (int i = 0; i < 20; i++)
            {
                var emp = new Employee();
                emp.EmployeeID = i;
                emp.Name = string.Format("Employee-{0}", i);
                emp.Address = string.Format("ABC New Delhi- 1{0}", i);
                if (i % 2 == 0)
                    emp.Dept = "IT";
                else
                    emp.Dept = "Admin";

                emplist.Add(emp);
            }
            return emplist;
        }

 

In above code controller has action method “Search” which has code to search on supplied search condition and send back result in json object.

View

@{
    ViewBag.Title = "Employee Search";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section head{
<script src="../Scripts/knockout-2.0.0.js"></script>
}

<h2>
    Employee List</h2>

<div>
Search:<input type="text" data-bind="value:empname" />

<input type="button" id='btnSearch' title="Search" value="Search"/>
</div>

<table style="border-style:solid;border-width:1px">
    <thead style="background-color:Gray">
        <tr>
            <th>
                ID
            </th>
            <th>
                Name
            </th>
             <th>
                Address
            </th>
            <th>
                Phone
            </th>
        </tr>
    </thead>
    <tbody data-bind="foreach: employeemodel.employees">
        <tr>
            <td data-bind="text: EmployeeID">
            </td>
            <td data-bind="text: Name">
            </td>
        </tr>
    </tbody>
</table>

<input type="text" data-bind="value:empname" />

this is input text box which is bind to empname property of knockoutjs viewmodel which is defined in javascript file.

<tbody data-bind="foreach: employeemodel.employees">

This will use for looping in viewmodel’s observable collection.

Note: “data-bind” attribute is used to bind knockoutjs viewmodel.

View Model

Viewmodel is defined in java script file. This viewmodel also has search function which sends ajax request to “Search” action method on server and receive json result .

Employee.js

var employeemodel;
$(document).ready(function () {

    //initializing viewmodel
    employeemodel = new viewModel();
    //binding for ko
    ko.applyBindings(employeemodel);
    //bind event
    $("#btnSearch").click({ handler: employeemodel.search });
    //call search method
    //employeemodel.search();

});

function viewModel() {
    var self = this;
    self.employees = ko.observableArray([]);
    self.empname = ko.observable('');
    self.search = function () {
        $.ajax({
            url: "Employee/Search",
            data: { EmpName: self.empname },
            type: "POST",
            success: function (response) {
                //bind data                
                self.employees(response.Items);
                self.DeptId(response.DeptId);
            }
        });

    }
}

 

Output

image

 

You can find code here.

Asp.Net, CodeProject

Client side Model binding with ASP.NET MVC 3 and KnockoutJs

Client side Model binding with ASP.NET MVC 3 and KnockoutJs Knockoutjs is type safe client side library which provides declarative bindings of DOM with model data, Automatic UI refresh when view model changes etc. You can read more about KnockoutJS on its website. You can read more about AspNet MVC3 on Asp.Net MVC website.

Model

Create Model class on server side MarketPriceModel. its collection class MarketPriceCollectionModel.

public class MarketPriceCollectionModel
    {
        public List Prices { get; private set; }

        public void Add(MarketPriceModel model)
        {
            if (Prices == null)
                Prices = new List();
            Prices.Add(model);
        }
    }

    public class MarketPriceModel
    {
        public string Symbol { get; set; }
        public double Open { get; set; }
        public double Close { get; set; }
        public double Low { get; set; }
        public double High { get; set; }
        public DateTime TimeStamp { get; set; }
    }

Controller: MarketWatchController

This controller class has action method “MarketPriceUI” which return MarketPriceUI view and injecting MarketPriceCollectionModel class as model.

public class MarketWatchController : Controller
    {
        //
        // GET: /MarketWatch/

        public ActionResult MarketPriceUI()
        {
         MarketPriceCollectionModel collection = new MarketPriceCollectionModel();
         collection.Add(new MarketPriceModel() { Symbol = "MSFT", 
		Open = 34.5d, Close = 35.5d, Low = 33.4d, High = 36.5d });
         collection.Add(new MarketPriceModel() { Symbol = "Goog", 
		Open = 54.5d, Close = 58.65d, Low = 52.78d, High = 59.23d });

         return View(collection);
        }
    }

View MarketPriceUI.cshtml @model: contain object returns from controller. We can use this object to show data in view but here I want to convert @model to knockoutJS viewmodel.

            var initialData = @(Html.Raw(Json.Encode(Model.Prices)));

viewModel = {prices: ko.observableArray(initialData)
                };

           ko.applyBindings(viewModel);

@(Html.Raw(Json.Encode(Model.Prices))) converts model data into json and this data is set as observablearray for knockoutjs viewmodel.

“data-bind="foreach: viewModel.prices" statement can loop in this viewmodel to show data on page.

@model MarketWatchWebSample.Models.MarketPriceCollectionModel
@{
    ViewBag.Title = "MarketWatch";
    Layout = "~/Views/Shared/_Layout.cshtml";
}




var viewModel;
    $(document).ready(function () {
  
            var initialData = @(Html.Raw(Json.Encode(Model.Prices)));

viewModel = {prices: ko.observableArray(initialData)
                };

           ko.applyBindings(viewModel);
});

}



<table>
    <tr>
        <td>
            Symbol
        </td>
        <td>
            High
        </td>
        <td>
            Low
        </td>
    </tr>
    <tbody data-bind="foreach: viewModel.prices">
        <tr>
            <td>
                <span data-bind="text:Symbol"></span>
            </td>
            <td>
                <span data-bind="text:High"></span>
            </td>
            <td>
                <span data-bind="text:Low"></span>
            </td>
        </tr>
    </tbody>
</table>

Output

image

Asp.Net, DotNet

What is Difference between HttpGet and HttpPost?

Http GET method

  • Data is submitted as a part of url.
  • Data is visible to the user as it post as query string.
  • it is not secure but fast and quick.
  • It use Stack method for passing form variable.
  • Data is limited to max length of querystring.
  • It is good when you want user to bookmark page.

Http POST method

  • Data is submitted in http request body.
  • Data is not visible in the url.
  • It is more secure but slower as compared to GET.
  • It use heap method for passing form variable
  • It can post unlimited form variables.
  • It is advisable for sending critical data which should not visible to users.

References: http://triaslama.wordpress.com/2008/05/01/interacting-with-get-and-post-methods-in-aspnet/

Asp.Net

JQGrid methods

I am listing here some useful methods of JqGrid (Jquery data grid plugin). you can read more about JqGrid here. You can also see demo of this grid here.

Html tag to declare JqGrid on web page

<table id="<nameofgrid>"></table> <div id="pager1"></div>

Grid Hide & Show

$(‘#<nameofgrid>’).hide();

$(‘#<nameofgrid>’).show();

Clear JQGrid Data

$(‘#<nameofgrid>’).clearGridData(false);

Fade In & Fade Out

$(‘#<nameofgrid>’).fadeIn("fast");

Align Column Header Text

$(‘#<nameofgrid>’).jqGrid(‘setLabel’, <Column Name>, ”, { ‘text-align’: ‘right’ });