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

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

BPAY Ref Number (BPAY CRN) using C#

In this article, I am going to show how to create BPay Ref number (CRN) using c# based on the mod10 version 5 algorithm (MOD10V5).

protected void Page_Load(object sender, EventArgs e)
    {
       BPAYRefNumber bpay = new BPAYRefNumber();
 
       string BPAYYref = bpay.generateValidMOD10V5Number("45895624");
 
       Response.Write("MOD10V5 Number =" + BPAYYref);
       Response.Write("<br/>The number is valid =" + bpay.isNumberValidMOD10V5(BPAYYref));       
 
    }

public class BPAYRefNumber
{ 
    int checkDigit = 0;
    int digit = 0;
    Boolean result = false;
    String response = null;
    /**
     * Returns the checkbit for a number as per Luhn Mod 10 Version 5
     * 
     * @param number
     * @return
     */
    public int getCheckDigitMod10V5(String number)
    {
        checkDigit = 0;
        digit = 0; 
        try
        {   for (int i = 0; i < number.Length; i++)
            { 
                digit = int.Parse(number.Substring(i, 1));
                checkDigit += digit * (i + 1);
             }
             checkDigit = checkDigit % 10;
        }
        catch 
        { 
        }
        return checkDigit; 
    }
 
     /**
     * Checks if a number is valid per Luhn Mod 10 Version 5
     * 
     * @param number
     * @return
     */
    public Boolean isNumberValidMOD10V5(String number)
    { 
        try
        {
            result = ("" + getCheckDigitMod10V5(number.Substring(0, number.Length - 1))
                ).Equals(number.Substring(number.Length - 1, 1));
        }
        catch 
        { 
            result = false; 
        }
 
        return result;
    }
    /**
     * Generates a valid MOD10V5 number
     * 
     * @param number
     * @return
     */
    public String generateValidMOD10V5Number(String number)
    { 
        return number + this.getCheckDigitMod10V5(number); 
    }     
 
}

Integrating salesforce Using the DeveloperForce Toolkit for .NET

Salesforce can be integrated with any .NET based application through the salesforce DeveloperForce Toolkits for .NET. This article will show how to connect to salesforce and manipulate data within ASP.NET application hosted outside Salesforce.com.

Salesforce SOAP base API

Salesforce can be integrated through the salesforce SOAP API (http://www.ashishblog.com/integrating-salesforce-soap-api-using-c-net/)

[ad#post]
Before we begin, there are a set of prerequisites that you need to get done in order to interact with salesforce using the DeveloperForce Toolkits for .NET.

Username and Password (salesforce logins)
Security Token
ConsumerKey and ConsumerSecret
DeveloperForce Toolkits for .NET

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
Security Token:
My Setting > Personal > Reset My Security Token

SaleforceSecurityToken

ConsumerKey and ConsumerSecret

The Consumer Key and Consumer Secret are available on the Connected App Details page.
Setup > Create > Apps > Connected Apps > New

connectedapps

Now fill Basic Information and API (Enable OAuth Setting) then Click ”SAVE

Salesforce ConsumerKey and ConsumerSecret

Salesforce Consumer Key Token page

DeveloperForce Toolkits for .NET

This Toolkit is open source and available on GitHub (https://github.com/developerforce/Force.com-Toolkit-for-NET). The easiest way to get this toolkit is to use the NuGet packages.

Install-Package DeveloperForce.Common
Install-Package DeveloperForce.Force

.NET Web Application

Let’s start exploring the DeveloperForce Toolkits for .NET functionality by creating a sample .Net web application.

Create new Project and select ASP.NET Empty Web Application in Visual Studio

To add DeveloperForce Toolkits for .NET, open up NuGet packages dialog and search “DeveloperForce”.

Saleforce_DeveloerForce.Force

Install “DeveloperForce.Force” as show in above image and “DeveloperForce.Common” will automatically install in our website as well.

Saleforce_DeveloerForce.Force_NuGet

Now that the base web Application is created and a reference setup to salesforce, we can transition to writing code that calls Salesforce data.

Here is example code showing how to authenticate using DeveloperForce Toolkits for .NET
[ad#post]

using System;
using System.Linq;
using System.Text;
using Salesforce.Common;
using Salesforce.Force; 
using System.Dynamic;
 
namespace AB_SalesForce_NET_Toolkits
{ 
public partial class Default : System.Web.UI.Page
{
    private static readonly string SecurityToken = "xxxxxxxxxxxxxxxxxxxxxxxx";
    private static readonly string ConsumerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    private static readonly string ConsumerSecret = "xxxxxxxxxxxxxxxxxxx";
    private static readonly string Username = "[email protected]";
    private static readonly string Password = "xxxxxxxxxxxxx";
    private static readonly string IsSandboxUser = "false";

    protected async void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            var auth = new AuthenticationClient();
 
             // Authenticate with Salesforce              
                sb.Append("Authenticating with Salesforce");
                var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                    ? "https://test.salesforce.com/services/oauth2/token"
                    : "https://login.salesforce.com/services/oauth2/token";

                await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password + SecurityToken, ".net-api-client", url);
                sb.Append("<br/>"); sb.Append("Connected to Salesforce");

                var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);     
 
        }
        catch (Exception ex)
        {
            sb.Append("<br/>"); sb.Append(ex.Message);
                sb.Append("<br/>"); sb.Append(ex.StackTrace);

                var innerException = ex.InnerException;
                while (innerException != null)
                {
                    sb.Append("<br/>"); sb.Append(innerException.Message);
                    sb.Append("<br/>"); sb.Append(innerException.StackTrace);

                    innerException = innerException.InnerException;
                }
        } 
            Response.Write(sb.ToString());
    } 
}
}

That’s it! You have just successfully logged in to the salesforce and create ForceClient to conduct further operations on the salesforce. The following code will use this to create, retrieve, update and delete data of product from .NET.

Product Class:

public class Product2
    {
        public const String SObjectTypeName = "Product2"; 
        public String Id { get; set; }
        public String Name { get; set; }
        public String ProductCode { get; set; }
        public String Description { get; set; }
        public bool? IsActive { get; set; }
    }

More information on Salesforce object https://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_objects_product2.htm|StartTopic=Content%2Fsforce_api_objects_product2.htm|SkinName=webhelp

INSERT Product

Product2 insertProduct = new Product2();
insertProduct.IsActive = true;
insertProduct.Name = "Test Product x";
insertProduct.Description = "Test Product x";
insertProduct.ProductCode = "Testx"; 
insertProduct.Id = await client.CreateAsync(Product2.SObjectTypeName, insertProduct);
if (insertProduct.Id == null)
{
    sb.Append("<br/>"); sb.Append("Failed to create product record.");
 }
 else
 {
    sb.Append("<br/>Insert Product Successfully!!!");
 }

You can also use the dynamic ExpandoObject to build up an object.

  dynamic c = new ExpandoObject();
c.IsActive = true;
c.Name = "Test Product x";
c.Description = "Test Product x";
c.ProductCode = "Testx";
c.Id = await client.CreateAsync("Product2", insertProduct);

Query Products

var readProducts = await client.QueryAsync<Product2>("SELECT ID, Name,Description,ProductCode,IsActive FROM Product2 where ProductCode='Testx'");
  if (readProducts.totalSize > 0)
  {
      Product2 readProduct = readProducts.records[0];
      productid = readProduct.Id; // save id show we can use in update and delete product
      sb.Append("Product Found!!<br/>");
      sb.Append("Name:" + readProduct.Name);
      sb.Append("<br/>ProductCode:" + readProduct.ProductCode);
      sb.Append("<br/>ID:" + readProduct.Id);
   }
   else
   {
      //put some code in here to handle no records being returned
       string message = "No records returned.";
       sb.Append("<br/>" + message);
   }

UPDATE Product

var success = await client.UpdateAsync(Product2.SObjectTypeName, productid, new { Name = "Test Product 1" });
 if (!success)
 {
     sb.Append("<br/>"); sb.Append("Failed to update product!");
 }
 else
 {
     sb.Append("<br/>UPDATE Product Successfully!!!");
 }

Delete Product

success = await client.DeleteAsync(Product2.SObjectTypeName, productid);
  if (!success)
  {
      sb.Append("<br/>"); sb.Append("Failed to delete the product by ID!");   
   }
   else
   {
       sb.Append("<br/>DELETE Product Successfully!!!");
   }

[ad#post]

Error:

If you see below screen of death

error

Then Add Async =”True” on Design page.

error_Solution

Download Code:

[wpdm_file id=7]

Thanks