CRUD operation using AngularJS and WebAPI in ASP.NET WebForm

In this article I will show you how easy it is to consume the WebAPI using AngularJS. To achieve that we are going to create Customer web page where we can do CRUD and filter on List of Customers. Here’s what it look like.
webapi angularjs

For This webpage we need to create ASP.NET WebAPI and AngularJS script to fetch WebAPI data.

Create Customer ASP.NET WebAPI

We are using WebAPI which I created in this article.

Getting Started with Web Form and WebAPI using Entity Framework 5

AngularJS script

How we fetch WebAPI data?
The $http service is a core Angular service that facilitates communication with the remote HTTP servers. This article we are using $http methods to call WebAPI. You can also use $resource instead on $http.

Define CustomerApp and Factory

var app = angular.module('customerApp', []);
        var url = 'api/Customers/';	
	app.factory('customerFactory', function ($http) {
            return {
                getCustomer: function () {
                    return $http.get(url);
                },
                addCustomer: function (customer) {
                    return $http.post(url, customer);
                },
                deleteCustomer: function (customer) {
                    return $http.delete(url + customer.CustomerID);
                },
                updateCustomer: function (customer) {
                    return $http.put(url + customer.Id, customer);
                }
            };
        });

CustomersController
In this controller script we going to use “customerFactory” to do CRUD on Customer Data.

app.controller('CustomersController', function PostsController($scope, customerFactory) {
            $scope.customers = [];
            $scope.loading = true;
            $scope.addMode = false;
 
            $scope.toggleEdit = function () {
                this.customer.editMode = !this.customer.editMode;
            };
            $scope.toggleAdd = function () {
                $scope.addMode = !$scope.addMode;
            };
            $scope.save = function () {
                $scope.loading = true;
                var cust = this.customer;
                customerFactory.updateCustomer(cust).success(function (data) {
                    alert("Saved Successfully!!");
                    cust.editMode = false;
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Saving customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
 
            // add Customer
            $scope.add = function () {
                $scope.loading = true;
                customerFactory.addCustomer(this.newcustomer).success(function (data) {
                    alert("Added Successfully!!");
                    $scope.addMode = false;
                    $scope.customers.push(data);
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Adding customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
            // delete Customer
            $scope.delcustomer = function () {
                $scope.loading = true;
                var currentCustomer = this.customer;
                customerFactory.deleteCustomer(currentCustomer).success(function (data) {
                    alert("Deleted Successfully!!");
                    $.each($scope.customers, function (i) {
                        if ($scope.customers[i].CustomerID === currentCustomer.CustomerID) {
                            $scope.customers.splice(i, 1);
                            return false;
                        }
                    });
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Saving customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
 
            //get all Customers
            customerFactory.getCustomer().success(function (data) {
                $scope.customers = data;
                $scope.loading = false;
            })
            .error(function (data) {
                $scope.error = "An Error has occured while loading posts! " + data.ExceptionMessage;
                $scope.loading = false;
            });
 
        });

Full Page Code:

<!DOCTYPE html>
<html data-ng-app="customerApp">
<head>
    <title>Customer App | AshishBlog</title>
    <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <link type="text/css" href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css" rel="stylesheet" />
    <style>
        #mydiv { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; background-color: grey; opacity: .8; }
        .ajax-loader { position: absolute; left: 50%; top: 50%; margin-left: -32px; /* -1 * image width / 2 */ margin-top: -32px; /* -1 * image height / 2 */ display: block; }
         
    </style>
</head>
<body>  
    <div data-ng-controller="CustomersController" class="container">
        <h2>Customers</h2>
        <strong class="error">{{ error }}</strong>
        <div id="mydiv" data-ng-show="loading">
            <img src="Images/482.gif" class="ajax-loader" />
        </div>
        <p data-ng-hide="addMode"><a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New</a></p>
        <form name="addCustomer" data-ng-show="addMode" style="width: 600px; margin: 0px auto;">
            <label>Name:</label><input type="text" data-ng-model="newcustomer.Name" required />
            <label>Email:</label><input type="email" data-ng-model="newcustomer.Email" required />
            <br />          
            <span class="error" data-ng-show="addCustomer.$error.email">Invalid Email format!</span>
            <br />
            <input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addCustomer.$valid" class="btn btn-primary" />
            <input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
            <br />
            <br />
        </form>
        <table class="table table-bordered table-hover" style="width: 800px">
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Email</th>
                <th></th>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="text" data-ng-model="search.Name" /></td>
                <td>
                    <input type="text" data-ng-model="search.Email" /></td>
                <td></td>
            </tr>
 
            <tr data-ng-repeat="customer in customers | filter:search">
                <td><strong data-ng-hide="customer.editMode">{{ customer.CustomerID }}</strong></td>
                <td>
                    <p data-ng-hide="customer.editMode">{{ customer.Name }}</p>
                    <p data-ng-show="customer.editMode">
                        <input type="text" data-ng-model="customer.Name" />
                    </p>
                </td>
                <td>
                    <p data-ng-hide="customer.editMode">{{ customer.Email }}</p>
                    <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Email" /></td>
                <td>
                    <p data-ng-hide="customer.editMode"><a data-ng-click="toggleEdit(customer)" href="javascript:;">Edit</a> | <a data-ng-click="delcustomer(customer)" href="javascript:;">Delete</a></p>
                    <p data-ng-show="customer.editMode"><a data-ng-click="save(customer)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(customer)" href="javascript:;">Cancel</a></p>
                </td>
            </tr>
        </table>
        <hr />
    </div>
   <script src="app.js"></script>
</body>
</html>

Thanks

Import/Export Excel (.Xlsx) or (.Xls) File into SQL Server

To, Import/Export data To/From Excel (.xls) need Microsoft.Jet.OLEDB.4.0 and for Excel 2007 (.xlsx) need 2007 Office System Driver: Data Connectivity Components. You can download from here.

Export Data to Excel file
Create an Excel file named testing having the headers same as that of SQLServerTable columns
Here is Query:
Excel 2003 (.Xls) file:

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;', 'SELECT * FROM [Sheet1$]') select * from SQLServerTable

Excel 2007 (.Xlsx) file:

insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;', 'SELECT * FROM [Sheet1$]') select * from SQLServerTable

Import data from Excel to new SQL Server table
Excel 2003 (.Xls) file:

select * into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')

Excel 2007 (.Xlsx) file:

Select * into SQLServerTable FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;HDR=YES', 'SELECT * FROM [Sheet1$]')

Import data from Excel to existing SQL Server table
Excel 2003 (.Xls) file:

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=D:\testing.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')

Excel 2007 (.Xlsx) file:

INSERT INTO SQLServerTable select * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=D:\testing.xlsx;HDR=YES', 'SELECT * FROM [Sheet1$]')

Import data from Excel to new SQL Server table with dynamic table name (ex. SQLTABLE_200110413)

DECLARE @table varchar(500)
DECLARE @Q varchar(2000 )
SET @table='SQLTABLE_' +(CONVERT(VARCHAR(8),GETDATE(),112))
SET @Q= 'select * into '+  @table + ' FROM OPENROWSET("Microsoft.ACE.OLEDB.12.0", "Excel 12.0;Database=D:\testing.xlsx;HDR=YES", "SELECT * FROM [Sheet1$]")'
Exec(@Q)

May be you find error like below while Import/Export data To/From Excel
Error 1:

Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. Access denied.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

Here is solution might work for you..

USE [master] 
GO 
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1 
GO 
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1 
GO 

Error 2:

Msg 15281, Level 16, State 1, Line 1
SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see "Surface Area Configuration" in SQL Server Books Online.

here is solution might work for you

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE

If above Query showing following error…

Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
Msg 5808, Level 16, State 1, Line 2
Ad hoc update to system catalogs is not supported.

then user RECONFIGURE WITH OVERRIDE instead of RECONFIGURE..

EXEC sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE WITH OVERRIDE

If above solution is not working, ere is solution link might work for you..
http://www.kodyaz.com/articles/enable-Ad-Hoc-Distributed-Queries.aspx

Thanks.

Getting started with ArangoDB using NodeJS (Nodejs + ejs + ArangoJS)

In this post I will be discussing how to use ArangoDB database backend in NodeJS WebApp. We are going to create User Management WebApp using NodeJS Express and ejs view engine.
Nodejs,ejs,ArangoDB,ArangoJS

What is ArangoDB?

ArangoDB (multi-model NoSQL database) is a distributed free and open-source database with a flexible data model for documents, graphs, and key-values. Build high performance applications using a convenient SQL-like query language or JavaScript extensions. More info visit www.arangodb.com

Pre-requisites:

To work with this article, we following thing install on system:

Let’s develop a NodeJS WEBAPP

First check you have install NodeJS on your system.

> node –v 
> npm –v

If not, install nodejs from https://nodejs.org/download/

Now that we have Node running, we going to create NodeJS app using express-generator. Express-generator is a scaffolding tool that creates a skeleton for express-driven sites. In your command prompt, type the following:

> npm install -g express-generator

So let’s use this installed generator to create the scaffolding for a website. In your command prompt, type the following.

> Express nodeArangoWebApp

Result:

> express nodeArangoWebApp
   create : nodeArangoWebApp
   create : nodeArangoWebApp/package.json
   create : nodeArangoWebApp/app.js
   create : nodeArangoWebApp/public/images
   create : nodeArangoWebApp/routes
   create : nodeArangoWebApp/routes/index.js
   create : nodeArangoWebApp/routes/users.js
   create : nodeArangoWebApp/public
   create : nodeArangoWebApp/views
   create : nodeArangoWebApp/views/index.jade
   create : nodeArangoWebApp/views/layout.jade
   create : nodeArangoWebApp/views/error.jade
   create : nodeArangoWebApp/public/stylesheets
   create : nodeArangoWebApp/public/stylesheets/style.css
   create : nodeArangoWebApp/public/javascripts
   create : nodeArangoWebApp/bin
   create : nodeArangoWebApp/bin/www

   install dependencies:
     > cd nodeArangoWebApp && npm install

   run the app:
     > SET DEBUG=nodeArangoWebApp:* & npm start

Now we have basic NodeJS Express WebApp. Return to your command prompt and type below cmd for navigate to our WebApp folder and install required dependency package:

> cd nodeArangoWebApp
> npm install

Above cmd install required webapp dependency of our WebApp. Now run our webapp by typing this:

> npm start

if our WebApp started then you see below result for above cmd

> nodeArangoWebApp 0.0.0 start xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> node ./bin/www

Let’s open http://localhost:3000 in browser where you will see a welcome to Express page.
welcomeExpress
Our basic WebApp up and running. Now open Visual Studio Code editor and open our WebApp
basicWebApp
And select our WebApp folder “nodeArangoWebApp”
OpenWebApp
By default express-generator use jade view engine but in our WebApp we going to use ejs view engine as it has simple html syntax. More info about ejs you can find at http://www.embeddedjs.com/

To use ejs we need to install ejs in our WebApp, return to your command prompt and navigate to our WebApp directory and type this:

> npm install ejs --save

– – save : save ejs package as our WebApp dependency if you see package.json you can see ejs in dependencies section
projson
Now we have installed ejs in our WebApp, to use ejs as view engine we need to change app.js file. Open app.js file and modify as follow:
From:
ejs
To:
jade
Also we need to change all default jade view to ejs view. Delete all jade view from view and create new folder “partials” in view folder (nodeArangoWebApp\views\partials) and create following two ejs view (head.ejs and footer.ejs)

head.ejs
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Nodejs + ejs + ArangoDB</title>
		<!-- CSS -->
		<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
		<style>
			body 	{ padding-top:50px; }
		</style>
	</head>
	<body class="container">
		<header>
			<nav class="navbar navbar-default" role="navigation">
				<div class="container-fluid">
					<div class="navbar-header">
						<a class="navbar-brand" href="#">Nodejs + ejs + ArangoDB</a>
					</div>
					<ul class="nav navbar-nav">
						<li>
							<a href="/">Home</a>
						</li>
						<li class="active">
							<a href="/users">User</a>
						</li>
					</ul>
				</div>
			</nav>
		</header>
footer.ejs
<footer>
	<p class="text-center text-muted">&copy; Copyright 2015 Ashishblog.com</p>
</footer>
</body>
</html>

Now create another two ejs view (index.ejs and error.ejs) in view folder (nodeArangoWebApp\views)

index.ejs
<% include ./partials/head %>
	<main>
		<div class="jumbotron">
			<h2>Nodejs + ejs + ArangoDB</h2>
			<p>Welcome to <%= title%></p>
                        <p>ejs View engine</p>
		</div>
	</main>
<% include ./partials/footer %>
error.ejs
<% include ./partials/head %>
	<main>
		<div class="jumbotron">
			<h1><%=message %></h1>
				<h2><%=error.status %><h2>
			<pre><%= error.stack %></pre>
		</div>
	</main>
<% include ./partials/footer %>

Save that file, now our WebApp converted to ejs format. So let’s restart our node server, go to your command prompt, kill your server if it’s still running from way back before. Then type:
(Remember your command prompt must navigate to our WebApp directory if not please do it.)

> npm start

And open url (http://localhost:3000/) in browser
nodeejsapp

Create ArangoDB database

If you not install ArangoDB, you can install from https://www.arangodb.com/download/
Open ArangoDB’s user interface and create database “nodeArangoWebAppDB” with nopassword. (Leave password textbox empty)
DB
Now you can see nodeArangoWebAppDB in database list and open it by clicking on it.
db1
Now we have database. We need to create collection to store our WebApp user data. Click collection on top menu and create collection “User”.
collUser

collUser1
Now our WebApp’s database and collection has been created we need to put some user data in collection. To add collection, we going to use “AQL Editor” tool. Open “AQL Editor” from top menu and type following AQL query and click “Execute”

INSERT { username: ‘ashish’, email:’[email protected]’} IN User RETURN NEW

AQL

AQL1
Now our WebApp backend has been created and ready to use in our WebApp. To use ArangoDB we need to install ArangoDB NodeJS (ArangoJS) package to interact with Database. Let’s install ArangoJS, type the following cmd to your command prompt:
(Kill your server if it’s still running and your command prompt must navigate to our WebApp directory if not please do it.)

> npm install arangojs --save
arangojs 3.8.4 node_modules\arangojs
├── extend 2.0.1
└── linkedlist 1.0.1

It’s always good practice to separate remote service from route or controller so we can call anywhere in our WebApp. Let’s create “service” Folder (nodeArangoWebApp\service) and “DataServices.js” in it. And add following code to DataServices.js

DataServices.js
var Database = require('arangojs');
var db = new Database({url:'http://127.0.0.1:8529'}); 
module.exports = {
	getAllUsers : function()
	{
		return db.database('nodeArangoWebAppDB')
				 .then(function (mydb) {return mydb.query('FOR x IN User RETURN x');})		
				 .then(function (cursor) { return  cursor.all();});		
	}
}

ws
Now our getAllusers service has been created so we can use this into WebApp to display all users. To achieve that we need to create route and view. By default our WebApp has userd.js route so we going to use that and create new view “userlist.ejs”.
Open users.js to editor and add following code in GET user listing.

users.js
var express = require('express');
var router = express.Router();
var service = require('../services/DataServices.js');
/* GET users listing. */
router.get('/', function(req, res, next) {
   console.log("↓↓↓↓ Getting User lists ↓↓↓↓");
  // geting user list from data Service
  service.getAllUsers().then(
    function (list) {
      console.log(list);
      //render userlist view with list if user
      res.render('userlist', { "userlist": list });
    },
    function (err) {
      console.error('Something went wrong:', err);
      res.send("There was a problem adding the information to the database. " + err);
    }
    );
  //res.send('respond with a resource');
});
module.exports = router;

userroute
Next let’s set up our userlist.ejs view to display user listing. Create new file “userlist.ejs” in (nodeArangoWebApp\view) and following html code:

<% include ./partials/head %>
	<main>
   <blockquote>
  <p>Users</p>
</blockquote>	
		<ul class="list-group" style="width:300px;margin:50px;">
            <li class="list-group-item"><a href="users/newuser" class="btn btn-primary btn-lg btn-block">Add New User</a>
            <% for(var i=0; i < userlist.length; i++) { %>
               <li class="list-group-item text-center">
                   <a href="users/<%= userlist[i]._key %>">
                    <h3><span class="label label-default"><%= userlist[i].username %></span></h3>  
                       <%= userlist[i].email %>
                   </a>
               </li>
            <% } %>
    </ul>
	</main>
	<% include ./partials/footer %>

We’re all set. Save that file, and let’s run our WebApp:

> npm start

Now open your browser and head to http://localhost:3000/users
node_arangodb_arangojs

Our WebApp now pulling data from the DB and spitting it out onto a web page. Great!!
Now we can extend our WebApp functionality to create, update and delete users.
To achieve that we need to modify our WebApp services, route and view for each operation.

DataServices.js
var Database = require('arangojs');
var db = new Database({url:'http://127.0.0.1:8529'});
module.exports = {
	getAllUsers : function()
	{
		return db.database('nodeArangoWebAppDB')
				 .then(function (mydb) {return mydb.query('FOR x IN User RETURN x');})		
				 .then(function (cursor) { return  cursor.all();});		
	},
	getUserByKey : function(userKey)
	{
		var bindVars = {'userKey': userKey};
		return db.database('nodeArangoWebAppDB')
				 .then(function (mydb) {return mydb.query('FOR x IN User FILTER x._key == @userKey RETURN x',bindVars);})		
				 .then(function (cursor) { return  cursor.all();});		
	},
	addUser : function(user)
	{
		return db.database('nodeArangoWebAppDB')
			      .then(function (mydb) {return mydb.collection('User');})    
			      .then(function (collection) { return collection.save(user);});
	},
	updateUser : function(user)
	{
		var bindVars = {'key': user.key, 'username': user.username,"email":user.email };
		return db.database('nodeArangoWebAppDB')
				 .then(function (mydb) {return mydb.query('FOR x IN User FILTER x._key == @key UPDATE x WITH { username:@username, email:@email } IN User',bindVars );})    
		      	 .then(function (cursor) { return cursor.all();});			      
	},
	removeUser : function(userKey)
	{
		var bindVars = {'userKey': userKey};
		return db.database('nodeArangoWebAppDB')
			      .then(function (mydb) {return mydb.query('FOR x IN User FILTER x._key == @userKey REMOVE x IN User LET removed = OLD RETURN removed', bindVars);})
			      .then(function (cursor) {return cursor.all();});
	}	
}
users.js
var express = require('express');
var router = express.Router();
var service = require('../services/DataServices.js');
/* GET users listing. */
router.get('/', function(req, res, next) {
   console.log("↓↓↓↓ Getting User lists ↓↓↓↓");
  // geting user list from data Service
  service.getAllUsers().then(
    function (list) {
      console.log(list);
      //render userlist view with list if user
      res.render('userlist', { "userlist": list });
    },
    function (err) {
      console.error('Something went wrong:', err);
      res.send("There was a problem adding the information to the database. " + err);
    }
    );
  //res.send('respond with a resource');
});
/* GET New User page. */
router.get('/newuser', function (req, res) {
  res.render('newuser', { title: 'Add New User' });
});

/* POST to Add User Service */
router.post('/adduser', function (req, res) {
  console.log("↓↓↓↓ Add New User ↓↓↓↓");  
  // Get our form values. These rely on the "name" attributes   
  var user = {
    "username": req.body.username,
    "email": req.body.useremail
  };
  service.addUser(user)
    .then(
      function (result) { console.log(result); res.redirect("/users"); },
      function (err) {
        console.error('Something went wrong:', err);
        res.send("There was a problem adding the information to the database. " + err);
      }
      );
});

/* GET User by key. */
router.get('/:key', function (req, res) {
  console.log("↓↓↓↓ Get User by Key ↓↓↓↓");
  // Get key value form url 
  var userkey = req.params.key;
  service.getUserByKey(userkey)
    .then(function (list) {
      console.log(list);
      res.render('userinfo', { "user": list[0] });
    },
      function (err) {
        console.error('Something went wrong:', err);
        res.send("There was a problem adding the information to the database. " + err);
      }
      );
});
router.get('/:key/delete', function (req, res) {
  console.log("↓↓↓↓ Delete User ↓↓↓↓");
  var userkey = req.params.key;
  service.removeUser(userkey)
    .then(function (list) {
      console.log(list);
      res.redirect("/users");
    },
      function (err) {
        console.error('Something went wrong:', err);
        res.send("There was a problem adding the information to the database. " + err);
      }
      );
});

/* GET to Update User */
router.get('/:key/update', function (req, res) {
  console.log("↓↓↓↓ Get User by Key for Update ↓↓↓↓");
  var userkey = req.params.key;
  service.getUserByKey(userkey)
    .then(function (list) {
      console.log(list);
      res.render('userupdate', { "user": list[0] });
    },
      function (err) {
        console.error('Something went wrong:', err);
        res.send("There was a problem adding the information to the database. " + err);
      }
      );
});

/* POST to update User */
router.post('/:key/update', function (req, res) {
  console.log("↓↓↓↓ Update User ↓↓↓↓");
  var user = {
    "key": req.params.key,
    "username": req.body.username,
    "email": req.body.useremail
  };
  service.updateUser(user)
    .then(
      function (result) { console.log(result); res.redirect("/users"); },
      function (err) {
        console.error('Something went wrong:', err);
        res.send("There was a problem adding the information to the database. " + err);
      }
      );
});
module.exports = router;
userinfo.ejs
<% include ./partials/head %>
	<main>
	<blockquote>
  <p>User info</p>
</blockquote>	
		<div class="jumbotron">
			
			<p>Name: <%= user.username %></p>
			<p>Email: <%= user.email %></p>
				<a href="<%= user._key %>/update" class="btn btn-primary">Update User</a>
				<a href="<%= user._key %>/delete" class="btn btn-primary">Delete User</a>
				<a href="/users" class="btn btn-primary">Back User List</a>				
		</div>
	</main>
<% include ./partials/footer %>
newuser.ejs
	<% include ./partials/head %>
	<main>
		<blockquote>
  <p><%= title%></p>
</blockquote>	
		<div class="jumbotron">					
			<form name="adduser" method="post" action="adduser"  style="width:300px;">
				<div class="form-group" >
			    <label for="username">User Name</label>
			   <input type="text" id="username" placeholder="UserName" class="form-control" name="username"  />			    
			  </div>
			  <div class="form-group">
			    <label for="useremail">Email Address</label>
			   <input type="text" id="useremail" placeholder="Email" name="useremail" class="form-control"/>			    
			  </div>								
				 <div class="text-center" >
				<input type="submit" value="Add User" class="btn btn-primary"/>
				</div>
			</form>
		</div>
	</main>
	<% include ./partials/footer %>
userupdate.ejs
	<% include ./partials/head %>
	<main>
		<blockquote>
  <p>Update User</p>
</blockquote>	
		<div class="jumbotron">								
			<form name="updateuser" method="post" action="" style="width:300px;">
			 <div class="form-group" >
			    <label for="username">User Name</label>
			   <input type="text" id="username" placeholder="username" class="form-control" name="username" value="<%= user.username %>" />			    
			  </div>
			  <div class="form-group">
			    <label for="useremail">Email Address</label>
			   <input type="text" id="useremail" placeholder="useremail" name="useremail" class="form-control" value="<%= user.email %>" />			    
			  </div>				
				<input type="hidden" name="key" value="<%= user._key %>" />
				 <div class="text-center" >
				<input type="submit" value="Update User" class="btn btn-primary"/>
				</div>
			</form>
		</div>
	</main>
	<% include ./partials/footer %>

We’re finish. Save that file, and let’s restart our node server. Go to your command prompt, kill your server if it’s still running from way back before. Then type:

> npm start

Now open your browser and head to http://localhost:3000/users
Happy Coding!!

Code

https://github.com/A5hpat/nodeArangoWebApp

Integrating salesforce SOAP API using C# .NET

Salesforce can be integrated with any .NET based application through the salesforce SOAP API. This article will show how to connect to salesforce and consume data within ASP.NET application hosted outside Salesforce.com.
Before we begin, there are a set of prerequisites that you need to get done in order to interact with salesforce API using the C# .NET.

  • Username and Password (salesforce logins)
  • SOAP API (WSDL file)
  • Security Token

Username and Password

You don’t need to use live company data and risk making a mess of things. You can register for a developer license in case you don’t have a user name and password at https://developer.salesforce.com/signup

SOAP API (WSDL file)

To get WSDL SOAP API, need to login salesforce and click “Set up” on right top Corner. Then go Develop > API and right click on “Generate Enterprise WSDL” under Enterprise WSDL (as we using “Enterprise WSDL” web service) and click on “Save Link as….” (Chrome browser) to save (enterprise.wsdl) file to somewhere in your computer.

SalesforceSOAPAPI

Security Token

My Setting > Personal > Reset My Security Token

SaleforceSecurityToken

.NET Application

Let’s start exploring the SOAP API functionality by creating a sample .Net application and connect into Salesforce. Here are the steps that can be taken to setup the Enterprise WSDL:

Create new ASP.NET Empty Web Site
Adding a Web Service Reference to website

Right click on Website root (Solution Exploere) and select “Add Service Reference”.

addsalesforcesoapapi
Click “Advanced..”
12
Click “Add Web Reference…”

123
In Add Web Reference dialog type path of saved “enterprise.wsdl” file in URL: and click “Enter” then change Web reference name to “SFDC” then click “Add Reference” (As show in below image).

1234
Now Salesforce SOAP API added into our website

12345

Now that the base website is created and a reference setup to the Enterprise WSDL, we can transition to writing code that calls the API.

The first step is to have Salesforce authenticate us as a user. Once the authentication with Salesforce is successful, additional authentication information, such as the Session ID and URL will be returned. This information is needed for subsequent API calls. The Session ID can be cached in your application for periods less than the timeout period. Go to “Setup > Security Controls > Session Settings” to see what your timeout is. For this sample, caching was omitted to keep things simple. Here is example code showing how to authenticate against Salesforce

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SFDC;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string userName = "[email protected]";
        string password = "xxxxxx";
        string securityToken = "xxxxxxxxxxxxxxx";
 
        SforceService sfdcBinding = null;
        LoginResult currentLoginResult = null;
        sfdcBinding = new SforceService();
        try
        {
            currentLoginResult = sfdcBinding.login(userName, password+securityToken);
        }
        catch (System.Web.Services.Protocols.SoapException ex)
        {
            // This is likley to be caused by bad username or password
            sfdcBinding = null;
            throw (ex);
        }
        catch (Exception ex)
        {
            // This is something else, probably comminication
            sfdcBinding = null;
            throw (ex);
        }
 
 
        //Change the binding to the new endpoint
        sfdcBinding.Url = currentLoginResult.serverUrl;
 
        //Create a new session header object and set the session id to that returned by the login
        sfdcBinding.SessionHeaderValue = new SessionHeader();
        sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
 
    }
}

That’s it! You have just successfully logged in to the salesforce API and created a valid session to conduct further operations on the salesforce. The sfdcBinding variable now contains the end point URL where further web service interactions will take place, as well as the session. The following code will use this to create, retrieve, update and delete data of product from .NET.

INSERT Product

Product2 insertProduct = new Product2();
        insertProduct.IsActive = true;
        insertProduct.IsActiveSpecified = true;
        insertProduct.Name = "Test Product";
        insertProduct.ProductCode = "Test";
 
        Response.Write("Name:" + insertProduct.Name);
        Response.Write("<br/>ProductCode:" + insertProduct.ProductCode);
 
        SaveResult[] createResults = sfdcBinding.create(new sObject[] { insertProduct });
      
        if (createResults[0].success)
        {
           string id = createResults[0].id;
            Response.Write("<br/>ID:" + id);
            Response.Write("<br/>INSERT Product Successfully!!!");           
        }
        else
        {
            string result = createResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

Query Products


        QueryResult queryResult = null;
        String SOQL = "";
        string productid = "";   
        SOQL = "select Id from Product2 where ProductCode = 'Test'";
        queryResult = sfdcBinding.query(SOQL);
 
        if (queryResult.size > 0)
        {
            //put some code in here to handle the records being returned
            int i = 0;
            Product2 readProduct = (Product2)queryResult.records[i];
            string productName = readProduct.Name;           
            productid = readProduct.Id; // save id show we can use in update and delete product
            Response.Write("Product Found!!<br/>");
            Response.Write("Name:" + readProduct.Name);
            Response.Write("<br/>ProductCode:" + readProduct.ProductCode);
            Response.Write("<br/>ID:" + readProduct.Id);           
        }
        else
        {
            //put some code in here to handle no records being returned
            string message = "No records returned.";
            Response.Write("<br/>" + message);
        }

UPDATE Product


        Product2 updateProduct = new Product2();
        updateProduct.Id = productid;
        updateProduct.Name = "Test Product 2";
 
        SaveResult[] updatedResults = sfdcBinding.update(new sObject[] { updateProduct });
 	
        if (updatedResults[0].success)
        {
            string id = updatedResults[0].id;
            Response.Write("<br/>ID:" + id); 
            Response.Write("Name:<br/>" + updateProduct.Name);          
            Response.Write("<br/>UPDATE Product Successfully!!!");
        }
        else
        { 
           string result = updatedResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

Delete Product


       DeleteResult[] deleteResults = sfdcBinding.delete(new string[] { productid });
 
        if (deleteResults[0].success)
        {
           string id = deleteResults[0].id;
           Response.Write("<br/>ID:" + id); 
            Response.Write("<br/>DELETE Product Successfully!!!");
        }
        else
        {
            string result = deleteResults[0].errors[0].message;
            Response.Write("<br/>ERROR:" + result);
        }

More info on SOAP API data model and method
https://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_calls_upsert.htm|StartTopic=Content%2Fsforce_api_calls_upsert.htm|SkinName=webhelp

Download Code
[wpdm_file id=6]

Thanks

BPAY Payment module for nopCommerce

Payment methods are implemented as plugins in nopCommerce. Payment method is an ordinary plugin which implements an IPaymentMethod interface (Nop.Services.Payments namespace). As you already guessed IPaymentMethod interface is used for creating payment method plugins. It contains some methods which are specific only for payment methods such as ProcessPayment() or GetAdditionalHandlingFee().

I has developed a free BPAY payment module which enables your customers to pay online for their orders in your nopCommerce solution. BPAY CRN number can be generate by OrderId or CustomerId, can be change from plugin admin configuration.

How to create BPAY CRN http://www.ashishblog.com/bpay-ref-number-bpay-crn-using-c/

Install Plugin

      1. Clone or download the source code (https://github.com/A5hpat/Nop.Plugin.Payments.BPay)
      2. Add the plugin source code to your nopCommerce solution (.sln) file
      3. Re-compile the solution file, run the website, and install the plugin
      4. Configure a BPAY info in the plugin configuration page (Biller Code, CRN Ref number, handling fee etc…)
      Config
      5. Enable BPAY plugin.
      Capture
      6. Create test order with BPAY payment and see order details (Note)
      onReceipt

Code

source code (https://github.com/A5hpat/Nop.Plugin.Payments.BPay)

Ref: http://docs.nopcommerce.com/display/nc/How+to+code+my+own+payment+method