Plugin URL : https://github.com/biggora/bootstrap-ajax-typeahead
[sourcecode language="javascript"]
<script type="text/javascript">
var items;
$("#search_item").typeahead({
onSelect: function(item) {
add_order_item(item.value);
},
updater: function (item) {
return item;
},
highlighter: function(name){
var item = _.find(items, function (c) {
return c.name == name;
});
var itm = ''
+ "<div class='typeahead_wrapper'>"
+ "<div class='typeahead_labels'>"
+ "<div class='typeahead_primary'><span class='pname'>" + item.name + "</span></div>"
+ "<div class='typeahead_secondary'><span class='pprice'>Rs. "+ item.purchase_price +"</span><div>"
+ "<div class='typeahead_secondary'>Code: "+ item.code +" / SKU: " + item.sku + "</div>"
+ "</div>"
+ "</div>";
return itm;
},
ajax: {
url: "<?php echo base_url('items/suggest_json');?>",
timeout: 500,
item: '<li><a href="#"></a><p>fgfg</p></li>' ,
scrollBar: true,
valueField: "id",
displayField: "name",
triggerLength: 1,
method: "get",
loadingClass: "loading-circle",
preDispatch: function (query) {
//showLoadingMask(true);
return {
search: query
}
},
preProcess: function (data) {
//showLoadingMask(false);
if (data.success === false) {
// Hide the list, there was some error
return false;
}
// We good!
items = data.results;
return data.results;
}
}
});
function add_order_item(item_id){
alert(item_id);
</script>
[/sourcecode]
Friday, May 29, 2015
Wednesday, May 20, 2015
DataTables Server Side Processing with CodeIgniter
[caption id="attachment_1101" align="aligncenter" width="273"]
DataTables[/caption]
In this tutorial, we will see how to use popular dataTables with CodeIgniter framework. Note that, pagination is done in client side for this tutorial. Hence this example is not ideal for a big data set. Handling pagination in server side will be discussed in a future tutorial.
Table format
[sourcecode language="html"]
<th>Need identified thru</th>
<th>Total Estimate</th>
<th class="no-sort"></th>
<th class="no-sort"></th>
</tr>
</thead>
</table>
[/sourcecode]
Initializing and fetching data with ajax
[sourcecode language="javascript"]
<script>
$(document).ready(function() {
$('#dataTables').dataTable({
"ajax": "<?php echo base_url('test/get_json'); ?>",
"pageLength": <?php echo $this->config->item('results_per_page'); ?>,
"order": [[ 0, "desc" ]],
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [0] },
{
"bSortable": false,
"aTargets": ["no-sort"]
}],
"dom": 'T<"clear">lfrtip',
tableTools: {
"sSwfPath": "<?php echo base_url("plugins/data_tables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"); ?>"
}
});
});
</script>
[/sourcecode]
Test Controller
[sourcecode language="php"]
class Test extends CI_Controller {
public function get_json() {
$this->load->model('test_model');
$results = $this->test_model->load_grid();
$data = array();
foreach ($results as $r) {
array_push($data, array(
$r['rname'],
$r['year'],
$r['mname'],
$r['need'],
$r['total_cost'],
anchor('test/view/' . $r['id'], 'View'),
anchor('test/edit/' . $r['id'], 'Edit')
));
}
echo json_encode(array('data' => $data));
}
}
[/sourcecode]
Model
[sourcecode language="php"]
class Test_model extends CI_Model {
public function load_grid() {
$this->db->select("$this->tbl_urgent_needs.unid,$this->tbl_urgent_needs.year,$this->tbl_urgent_needs.needi,$this->tbl_urgent_needs.total_cost,$this->tbl_maintenance_type.name AS mname,$this->tbl_roads.name AS rname");
$this->db->from("$this->tbl_urgent_needs");
$this->db->join("$this->tbl_roads", "$this->tbl_roads.rid = $this->tbl_urgent_needs.rd_id");
$this->db->join("$this->tbl_maintenance_type", "$this->tbl_maintenance_type.id = $this->tbl_urgent_needs.maint_type_id", "left");
$this->db->order_by("$this->tbl_urgent_needs.unid", 'ASC');
$query = $this->db->get();
return $query->result_array();
}
}
[/sourcecode]
DataTables[/caption]In this tutorial, we will see how to use popular dataTables with CodeIgniter framework. Note that, pagination is done in client side for this tutorial. Hence this example is not ideal for a big data set. Handling pagination in server side will be discussed in a future tutorial.
Table format
[sourcecode language="html"]
<th>Need identified thru</th>
<th>Total Estimate</th>
<th class="no-sort"></th>
<th class="no-sort"></th>
</tr>
</thead>
</table>
[/sourcecode]
Initializing and fetching data with ajax
[sourcecode language="javascript"]
<script>
$(document).ready(function() {
$('#dataTables').dataTable({
"ajax": "<?php echo base_url('test/get_json'); ?>",
"pageLength": <?php echo $this->config->item('results_per_page'); ?>,
"order": [[ 0, "desc" ]],
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [0] },
{
"bSortable": false,
"aTargets": ["no-sort"]
}],
"dom": 'T<"clear">lfrtip',
tableTools: {
"sSwfPath": "<?php echo base_url("plugins/data_tables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"); ?>"
}
});
});
</script>
[/sourcecode]
Test Controller
[sourcecode language="php"]
class Test extends CI_Controller {
public function get_json() {
$this->load->model('test_model');
$results = $this->test_model->load_grid();
$data = array();
foreach ($results as $r) {
array_push($data, array(
$r['rname'],
$r['year'],
$r['mname'],
$r['need'],
$r['total_cost'],
anchor('test/view/' . $r['id'], 'View'),
anchor('test/edit/' . $r['id'], 'Edit')
));
}
echo json_encode(array('data' => $data));
}
}
[/sourcecode]
Model
[sourcecode language="php"]
class Test_model extends CI_Model {
public function load_grid() {
$this->db->select("$this->tbl_urgent_needs.unid,$this->tbl_urgent_needs.year,$this->tbl_urgent_needs.needi,$this->tbl_urgent_needs.total_cost,$this->tbl_maintenance_type.name AS mname,$this->tbl_roads.name AS rname");
$this->db->from("$this->tbl_urgent_needs");
$this->db->join("$this->tbl_roads", "$this->tbl_roads.rid = $this->tbl_urgent_needs.rd_id");
$this->db->join("$this->tbl_maintenance_type", "$this->tbl_maintenance_type.id = $this->tbl_urgent_needs.maint_type_id", "left");
$this->db->order_by("$this->tbl_urgent_needs.unid", 'ASC');
$query = $this->db->get();
return $query->result_array();
}
}
[/sourcecode]
Tuesday, May 5, 2015
Sunday, April 12, 2015
ASP.Net Bulk Insert Excel Data using SqlBulkCopy
This code sample is for a Excel Import programmatically into SQL Server database.
Important points to note.
Excel format:
.aspx page
Code Behind File
[sourcecode language="csharp"]
protected void ImportExcel(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// SQL Server Connection String
string sqlConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["flexi_stocky"].ConnectionString;
// Bulk Copy to SQL Server
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
try
{
string path = string.Concat(Server.MapPath("~/uploads/" + FileUpload1.FileName));
FileUpload1.SaveAs(path);
// Connection String to Excel Workbook
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
DbDataReader dr = command.ExecuteReader();
bulkInsert.DestinationTableName = "your_sqlTableName";
bulkInsert.WriteToServer(dr);
bulkInsert.Close();
//Show success
}
catch (Exception ex)
{
bulkInsert.Close();
//Show error
}
}
else
{
//File not set
}
}
[/sourcecode]
Important points to note.
- Use excel data in a single sheet.
- The excel file format should match the table schema.
Excel format:
| Id | Name | Description | CreatedAt | CreatedBy | ModifiedAt | ModifiedBy | Enabled | Deleted |
.aspx page
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Import" CssClass="btn btn-warning" OnClick="ImportExcel" />
Code Behind File
[sourcecode language="csharp"]
protected void ImportExcel(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// SQL Server Connection String
string sqlConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["flexi_stocky"].ConnectionString;
// Bulk Copy to SQL Server
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
try
{
string path = string.Concat(Server.MapPath("~/uploads/" + FileUpload1.FileName));
FileUpload1.SaveAs(path);
// Connection String to Excel Workbook
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
DbDataReader dr = command.ExecuteReader();
bulkInsert.DestinationTableName = "your_sqlTableName";
bulkInsert.WriteToServer(dr);
bulkInsert.Close();
//Show success
}
catch (Exception ex)
{
bulkInsert.Close();
//Show error
}
}
else
{
//File not set
}
}
[/sourcecode]
Saturday, April 11, 2015
How to use Sessions in Web Services ASP.Net
Using sessions in web services is little different from its normal usage. Here we can not access sessions with Session as in Page methods. Instead we use HttpContext.Current.Session.
Sessions should be enabled for web methods.
A sample code snippet would be as follows.
[sourcecode language="csharp"]
/// Summary description for ReceivingService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ReceivingService : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string, object> removeItem(int Id)
{
var response = new Dictionary<string, object>();
bool found = false;
if ( HttpContext.Current.Session["rec_cart"] != null)
{
List<CartItem> cartItems = (List<CartItem>)Session["rec_cart"];
if (cartItems.Count > 0)
{
foreach(var item in cartItems){
if(item.Id == Id){
cartItems.Remove(item);
HttpContext.Current.Session["rec_cart"] = cartItems;
found = true;
break;
}
}
}
}
if (found)
{
response["status"] = true;
response["total"] = GetGrandTotal();
}
else
{
response["status"] = false;
}
return response;
}
}
[/sourcecode]
I also configured cookieless sessions in web.config to get web service call properly routed.
Sessions should be enabled for web methods.
A sample code snippet would be as follows.
[sourcecode language="csharp"]
/// Summary description for ReceivingService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class ReceivingService : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string, object> removeItem(int Id)
{
var response = new Dictionary<string, object>();
bool found = false;
if ( HttpContext.Current.Session["rec_cart"] != null)
{
List<CartItem> cartItems = (List<CartItem>)Session["rec_cart"];
if (cartItems.Count > 0)
{
foreach(var item in cartItems){
if(item.Id == Id){
cartItems.Remove(item);
HttpContext.Current.Session["rec_cart"] = cartItems;
found = true;
break;
}
}
}
}
if (found)
{
response["status"] = true;
response["total"] = GetGrandTotal();
}
else
{
response["status"] = false;
}
return response;
}
}
[/sourcecode]
I also configured cookieless sessions in web.config to get web service call properly routed.
<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="100"/>
Saturday, March 21, 2015
Add Default Item to DropDownList Dynamically
How to add a default item as 'N/A' to drop down list and set selected?
[sourcecode language="csharp"]
gnList.DataSourceID = "GNDS";
gnList.DataTextField = "Name";
gnList.DataValueField = "Id";
gnList.DataBind();
gnList.Items.Insert(0, new ListItem("N/A", "0"));
[/sourcecode]
Another way
[sourcecode language="csharp"]
gnList.Items.Add(new ListItem("N/A", "0"));
gnList.DataSourceID = "GNDS";
gnList.DataTextField = "Name";
gnList.DataValueField = "Id";
gnList.DataBind();
gnList.Items.FindByValue("0").Selected = true;
[/sourcecode]
[sourcecode language="csharp"]
gnList.DataSourceID = "GNDS";
gnList.DataTextField = "Name";
gnList.DataValueField = "Id";
gnList.DataBind();
gnList.Items.Insert(0, new ListItem("N/A", "0"));
[/sourcecode]
Another way
[sourcecode language="csharp"]
gnList.Items.Add(new ListItem("N/A", "0"));
gnList.DataSourceID = "GNDS";
gnList.DataTextField = "Name";
gnList.DataValueField = "Id";
gnList.DataBind();
gnList.Items.FindByValue("0").Selected = true;
[/sourcecode]
Friday, March 20, 2015
Static DropDownList in GridView
Displaying a DropDownList column in GridView and setting the selected item.
[sourcecode language="csharp"]
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Status") %>' autocomplete="off" Width="150">
<asp:ListItem Value="1">Enable</asp:ListItem>
<asp:ListItem Value="2">Disable</asp:ListItem>
<asp:ListItem Value="3">Delete</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
[/sourcecode]
[sourcecode language="csharp"]
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Status") %>' autocomplete="off" Width="150">
<asp:ListItem Value="1">Enable</asp:ListItem>
<asp:ListItem Value="2">Disable</asp:ListItem>
<asp:ListItem Value="3">Delete</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
[/sourcecode]
Add Dynamic Controls to Content PlaceHolders in ASP.Net
[sourcecode language="csharp"]
ContentPlaceHolder holder = Page.Master.FindControl("message") as ContentPlaceHolder;
HtmlGenericControl alertControl = new HtmlGenericControl();
alertControl.Attributes["class"] = "alert alert-success";
alertControl.TagName = "div";
holder.Controls.Add(alertControl);
Label message = new Label();
message.Text = "User deleted successfully.";
alertControl.Controls.Add(message);
[/sourcecode]
ContentPlaceHolder holder = Page.Master.FindControl("message") as ContentPlaceHolder;
HtmlGenericControl alertControl = new HtmlGenericControl();
alertControl.Attributes["class"] = "alert alert-success";
alertControl.TagName = "div";
holder.Controls.Add(alertControl);
Label message = new Label();
message.Text = "User deleted successfully.";
alertControl.Controls.Add(message);
[/sourcecode]
Friday, March 13, 2015
OpenLayers 3 Map with Marker

[sourcecode language="html"]
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://openlayers.org/en/v3.2.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://openlayers.org/en/v3.2.1/build/ol.js" type="text/javascript"></script>
<title>OpenLayers 3 example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div>
<script>
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [
new ol.layer.Tile({source: new ol.source.OSM()})
],
view: new ol.View({
//projection: 'EPSG:900913',
center: ol.proj.transform([80.6350, 7.2964], 'EPSG:4326', 'EPSG:3857'),
zoom: 10
})
});
//Full Screen
var myFullScreenControl = new ol.control.FullScreen();
map.addControl(myFullScreenControl);
map.addOverlay(new ol.Overlay({
position: ol.proj.transform(
[80.6350, 7.2964],
'EPSG:4326',
'EPSG:3857'
),
element: $('<img src="//map.geo.admin.ch/1403704943/img/marker.png">')
}));
map.on('singleclick', function(evt) {
var coord = evt.coordinate;
var transformed_coordinate = ol.proj.transform(coord, "EPSG:900913", "EPSG:4326");
console.log(transformed_coordinate);
});
</script>
</body>
</html>
[/sourcecode]
Saturday, March 7, 2015
ASP.Net Validating CheckBoxList with JavaScript
[sourcecode language="csharp"]
<asp:CheckBoxList ID="groupsList" runat="server" DataSourceID="GroupsDS" DataTextField="Name" DataValueField="Id" CssClass="span6 m-wrap groupsList" RepeatLayout="UnorderedList"></asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" ErrorMessage="Please select at least one group."
ForeColor="Red" ClientValidationFunction="ValidateCheckBoxList" runat="server" />
<asp:SqlDataSource runat="server" ID="GroupsDS" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>' SelectCommand="SELECT * FROM [Groups]"></asp:SqlDataSource>
[/sourcecode]
[sourcecode language="javascript"]
<script type="text/javascript">
function ValidateCheckBoxList(sender, args) {
var checkBoxList = document.getElementById("<%=groupsList.ClientID %>");
var checkboxes = checkBoxList.getElementsByTagName("input");
var isValid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
isValid = true;
break;
}
}
args.IsValid = isValid;
}
</script>
[/sourcecode]
<asp:CheckBoxList ID="groupsList" runat="server" DataSourceID="GroupsDS" DataTextField="Name" DataValueField="Id" CssClass="span6 m-wrap groupsList" RepeatLayout="UnorderedList"></asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" ErrorMessage="Please select at least one group."
ForeColor="Red" ClientValidationFunction="ValidateCheckBoxList" runat="server" />
<asp:SqlDataSource runat="server" ID="GroupsDS" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>' SelectCommand="SELECT * FROM [Groups]"></asp:SqlDataSource>
[/sourcecode]
[sourcecode language="javascript"]
<script type="text/javascript">
function ValidateCheckBoxList(sender, args) {
var checkBoxList = document.getElementById("<%=groupsList.ClientID %>");
var checkboxes = checkBoxList.getElementsByTagName("input");
var isValid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
isValid = true;
break;
}
}
args.IsValid = isValid;
}
</script>
[/sourcecode]
Friday, March 6, 2015
ASP.NET GridView ListBox Column Data Binding
[sourcecode language="c-sharp"]
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" CssClass="table" DataSourceID="GenericNamesDataSource" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Group Name" SortExpression="GroupName">
<EditItemTemplate>
<asp:ListBox ID="ListBox2" runat="server" DataSourceID="GroupsDataSource" DataTextField="Name" DataValueField="Id" SelectedValue='<%# Bind("GroupId") %>' SelectionMode="Multiple" CssClass="chzn-select" autocomplete="off" data-placeholder="Select Item(s)"></asp:ListBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("GroupName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="GenericNamesDataSource" runat="server" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>'
SelectCommand="SELECT GN.Id, GN.GroupId, GN.CreatedAt, G.Name AS GroupName FROM GenericNames AS GN INNER JOIN Groups AS G ON GN.GroupId = G.Id">
</asp:SqlDataSource>
<asp:SqlDataSource ID="GroupsDataSource" runat="server" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>' SelectCommand="SELECT DISTINCT [Id], [Name] FROM [Groups]"></asp:SqlDataSource>
[/sourcecode]
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" CssClass="table" DataSourceID="GenericNamesDataSource" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Group Name" SortExpression="GroupName">
<EditItemTemplate>
<asp:ListBox ID="ListBox2" runat="server" DataSourceID="GroupsDataSource" DataTextField="Name" DataValueField="Id" SelectedValue='<%# Bind("GroupId") %>' SelectionMode="Multiple" CssClass="chzn-select" autocomplete="off" data-placeholder="Select Item(s)"></asp:ListBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("GroupName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="GenericNamesDataSource" runat="server" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>'
SelectCommand="SELECT GN.Id, GN.GroupId, GN.CreatedAt, G.Name AS GroupName FROM GenericNames AS GN INNER JOIN Groups AS G ON GN.GroupId = G.Id">
</asp:SqlDataSource>
<asp:SqlDataSource ID="GroupsDataSource" runat="server" ConnectionString='<%$ ConnectionStrings:flexi_stocky %>' SelectCommand="SELECT DISTINCT [Id], [Name] FROM [Groups]"></asp:SqlDataSource>
[/sourcecode]
Subscribe to:
Posts (Atom)
How to enable CORS in Laravel 5
https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...
-
Today we are going to build another restful web service in eclipse using gson library. When client makes a request, the application queries ...
-
To import Excel data, first you need to have a Excel reader. It should be accurate enough to interpret Excel data as expected. There 's ...