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); 
    }     
 
}

Select navigation menu base on page url in AngularJS

AngularJS-Navigation-Menu
I come across a scenario in my current angular project where I need to select navigation menu base on page url.

Here is my menu

 <div class="well sidebar-nav" ng-app="app">
   <ul class="nav nav-list" ng-controller="navCtrl">
     <li ng-class="navClass('home')"><a href='#/home'>Home</a></li>
     <li ng-class="navClass('about')"><a href='#/about'>About Us</a></li>
     <li ng-class="navClass('contact')"><a href='#/contact'>Contact Us</a></li>
   </ul>
 </div>

Using $location.path() we get the current route. The substring operation removes the leading slash (/) and converts /home to home
[ad#post]

 var app = angular.module('app', []);
  app.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
            $scope.navClass = function (page) {
                var currentRoute = $location.path().substring(1) || 'home';
                return page === currentRoute ? 'active' : '';
            };
        }]);

Code

https://github.com/A5hpat/AngularJS-Navigation-Menu

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

How to set focus on first textbox of the page

Below I have given the complete sample code where the cursor will be placed on first textbox when the page loads.

Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Ashish's Blog</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('form input:text:enabled:first').focus();
        }); 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server" />
 
    <asp:TextBox ID="TextBox2" runat="server" />
 
    <asp:TextBox ID="TextBox3" runat="server" />
 
    <asp:TextBox ID="TextBox4" runat="server" />
 
    </form>
</body>
</html>

UPDATE:

If you first textbox is disabled

$(document).ready(function() {
    $('input[type=text]:enabled:first').focus();
});

If you first textbox is not visible

$(document).ready(function() {
    $('input[type=text]:visible:first').focus();
});

Thanks.

Read Excel file using c#.Net

In this article, I am going to show how to read Excel file using c#. To achieve that we are going to use
Excel Data Reader (http://exceldatareader.codeplex.com/) DLL.
To get Excel Data Reader DLL to your project use NuGet
readexcel
Code:

public void BtnUploadClick(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            uploadPath = Server.MapPath("~/Excel/");            
                if (FileUpload1.HasFile)
                {
                    String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                    String validExt = sAllowedExt;
                    if (validExt.IndexOf("," + fileExtension + ",") != -1)
                    { 
                        if (FileUpload1.FileBytes.Length <= maxsize)
                        {
                            filePath = uploadPath + FileUpload1.FileName; 
                            FileUpload1.PostedFile.SaveAs(filePath); 
                            Response.Write("File uploaded successfully.");
 
                            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                            IExcelDataReader excelReader;
                            if (filePath.Contains(".xlsx"))
                            {
                                //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
                                excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
 
                            }  //...
                            else
                            {
                                //1. Reading from a binary Excel file ('97-2003 format; *.xls)
                                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                            } //...
                            //3. DataSet - The result of each spreadsheet will be created in the result.Tables
                            //DataSet result = excelReader.AsDataSet();
                            //...
                            //4. DataSet - Create column names from first row
                            excelReader.IsFirstRowAsColumnNames = true;
                            DataSet result = excelReader.AsDataSet();
                            //5. Data Reader methods
                            //foreach (DataRow item in result.Tables[0].Rows)
                            //{
                            //    //item[1].ToString();
                            //}
                            GridView1.DataSource = result;
                            GridView1.DataBind();
                        }
                        else
                        {
                            Response.Write("File size exceeded the permitted limit.");
                            return;
                        }
                    }
                    else
                    {
                        Response.Write("This file type is not accepted.");
                        return;
                    }      
                }
        }

Thanks

Download

[wpdm_file id=4]