Tuesday 23 July 2013

Implementing credit card payment in your app

Introduction:

Hi Everyone, Here I am putting sample code for card payment. You can use it in your code and can implement the payment module in your project. API that I am using it will return the response in XML format. Use your API and enjoy. Hope it can help you.

Card payment sample code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Net;
using System.IO;
using System.Xml;

using System.Text;
using System.Data;
using System.Configuration;

using ModelLayer;
using DataAccessLayer;

namespace BusinessLayer
{
    public class AccountInfo:IDisposable
    {
        XmlDocument objXmlDocument;//declare XmlDocument to store xml document
        //default constructor
        public AccountInfo()
        {
            //code
        }
        //parametric constructor accepting LoginDetail class from model layer as a signature
        public AccountInfo(LoginDetails objLogin)
        {
            //Calling GetAccntInfo() method
            GetAccntInfo(objLogin);
        }


        void GetInfo(LoginClass objLogin)
        {
           
                //url containing the web service api which will return document in the xml format
                string uri = objLogin.BaseURL + string.Format(@"/accntinfo?apikey={0}&accntID={1}", objLogin.APIKey, objLogin.AccountID);

                //We are creating new url and sending to HttpWebRequest
                HttpWebRequest objHttpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
                //Getting response from HttpWebRequest
                HttpWebResponse objHttpWebResponse = objHttpWebRequest.GetResponse() as HttpWebResponse;
                //Putting response in the form of stream to the StreamReader
                using (StreamReader objStreamReader = new StreamReader(objHttpWebResponse.GetResponseStream()))
                {
                    objXmlDocument = new XmlDocument();
                    //reading the stream
                    using (XmlTextReader objXmlTextReader = new XmlTextReader(objStreamReader))
                    {
                        objXmlTextReader.Namespaces = false;
                        //Loading xml document with the data got from the stream
                        objXmlDocument.Load(objXmlTextReader);
                    }
                }
  
        }


        public DataTable FetchData(AccDetails objAccInfo)
        {
                //declaring the data columns name and their types for the table to store data in it
                DataColumn[] dcGuarantor = new DataColumn[8];
                dcGuarantor[0] = new DataColumn("FirstName", typeof(string));
                dcGuarantor[1] = new DataColumn("LastName", typeof(string));
                dcGuarantor[2] = new DataColumn("Addr1", typeof(string));
                dcGuarantor[3] = new DataColumn("Addr2", typeof(string));
                dcGuarantor[4] = new DataColumn("City", typeof(string));
                dcGuarantor[5] = new DataColumn("StateProvinceRegion", typeof(string));
                dcGuarantor[6] = new DataColumn("ZipPostalCode", typeof(string));
                dcGuarantor[7] = new DataColumn("AccntRef", typeof(string));
               
                dtGuarantor.Columns.AddRange(dcGuarantor);//Add columns into table
                //selecting a perticular node from the xml document to read data from its nodes
                XmlNodeList nodes = objXmlDocument.SelectNodes("/Account/Guarantor");
                foreach (XmlNode node in nodes)
                {
                    objAccountInfo.GuarantorFirstName = node.SelectSingleNode("FirstName").InnerText;
                    objAccountInfo.GuarantorLastName = node.SelectSingleNode("LastName").InnerText;
                    objAccountInfo.GuarantorAddress1 = node.SelectSingleNode("Addr1").InnerText;
                    objAccountInfo.GuarantorAddress2 = node.SelectSingleNode("Addr2").InnerText;
                    objAccountInfo.GuarantorCity = node.SelectSingleNode("City").InnerText;
                    objAccountInfo.GuarantorStateProvinceRegion = node.SelectSingleNode("StateProvinceRegion").InnerText;
                    objAccountInfo.GuarantorZipPostalCode = node.SelectSingleNode("ZipPostalCode").InnerText;
                    objAccountInfo.GuarantorAccountRef = node.SelectSingleNode("AccntRef").InnerText;
                    //loading data into the datarow
                    dtGuarantor.LoadDataRow(new object[]{ objAccountInfo.GuarantorFirstName, objAccountInfo.GuarantorLastName, objAccountInfo.GuarantorAddress1,
                    objAccountInfo.GuarantorAddress2, objAccountInfo.GuarantorCity,objAccountInfo.GuarantorStateProvinceRegion,
                objAccountInfo.GuarantorZipPostalCode,objAccountInfo.GuarantorAccountRef}, false);
                }

            }
            return dtGuarantor;//returns table object
        }


  
        string PostPaymentResponse(GetDetails objGetDetails)
        {
            string refkey = "";
            //creating instance of the string builder class to hold the tracing data
            StringBuilder objStringBuilder = new StringBuilder();
            //append tracing into string builder
            objStringBuilder.Append("Entered into the function :PostPaymentResponse ");
            try
            {
                //objGetDetails.AccountID = "testing invalid account abcd";
               
                string uri = objGetDetails.BaseURL + string.Format(@"/pymt?apikey={0}&accntID={1}", objGetDetails.APIKey, objGetDetails.AccountID);

                // build XML body to POST
                XmlDocument objXmlDocument = CreatePostPaymentXMLDoc(objGetDetails);

                // POST xml to webservice
                byte[] bytes = System.Text.Encoding.Default.GetBytes(objXmlDocument.OuterXml);

                WebClient objWebClient = new WebClient();
               
                objWebClient.Headers.Add("Content-Type", "application/xml");        //Adding header to webclient
                byte[] response = objWebClient.UploadData(uri, "POST", bytes);      //uploading data

                Stream objStream = new MemoryStream(response);                      //getting response from POST

                DataContractSerializer obj = new DataContractSerializer(typeof(string));

                refkey = obj.ReadObject(objStream).ToString();                      // email reference ID to user

                objWebClient.Dispose();
                objStream.Dispose();
                //append tracing into string builder
                objStringBuilder.Append("Exited from the function :PostPaymentResponse ");
                //writing trace log into the log file
                LogManager.WriteTraceLog(objStringBuilder);
            }
            catch (Exception ex)
            {
                //Write error log into log file.
                LogManager.WriteErrorLog(ex);
                throw;
            }
            finally
            {
                //nullify the string builder object.
                objStringBuilder = null;
            }
            return refkey;
        }

        public XmlDocument CreatePostPaymentXMLDoc(GetDetails objGetDetails)
        {
            // new XML doc
            XmlDocument xmlDoc = new XmlDocument();

                XmlElement pymt = xmlDoc.CreateElement("Payment");
                xmlDoc.AppendChild(pymt);
                pymt.Attributes.Append(pymt.OwnerDocument.CreateAttribute("xmlns"));
                //pymt.Attributes["xmlns"].Value = @"http://schemas.datacontract.org/2004/07/testAPI";
                pymt.Attributes["xmlns"].Value = objGetDetails.PostXMLSchema;

                // RefID - passed to TransFirst as the User Unique Order Number
                // this is the "RefID" element found Account
                //
                XmlElement refID = xmlDoc.CreateElement("RefID");
                refID.InnerText = objGetDetails.RefID;
                pymt.AppendChild(refID);

                // TransactionID - ID return from TransFirst
                XmlElement transID = xmlDoc.CreateElement("TransactionID");
                transID.InnerText = objGetDetails.TransactionID;
                pymt.AppendChild(transID);

                // masked pattern Credit Card Num
                XmlElement ccNum = xmlDoc.CreateElement("CCNum");
                ccNum.InnerText = objGetDetails.CardNumber;
                pymt.AppendChild(ccNum);

                // Credit Card Code: MC, VI, AX, DC
                // Codes from Account
                XmlElement ccCode = xmlDoc.CreateElement("CCCode");
                ccCode.InnerText = objGetDetails.CardCode;
                pymt.AppendChild(ccCode);

                // Credit Card holder name
                XmlElement ccName = xmlDoc.CreateElement("CCName");
                ccName.InnerText = objGetDetails.FirstName + " " + objGetDetails.LastName;
                pymt.AppendChild(ccName);

                // Authorization Number return from TransFirst
                XmlElement authNum = xmlDoc.CreateElement("AuthorizationNum");
                authNum.InnerText = objGetDetails.AuthorizationNumber;
                pymt.AppendChild(authNum);

                // Total Amount paid
                XmlElement amt = xmlDoc.CreateElement("Amount");
                amt.InnerText = objGetDetails.TotalAmount;
                pymt.AppendChild(amt);

                // individual payments on invoice(s)
                XmlElement invPymts = xmlDoc.CreateElement("InvoicePymts");

                IDictionaryEnumerator objIDictionaryEnumerator =
                            objGetDetails.TransactionAmountPerInvoice.GetEnumerator();   //retreiving values from hashtable into IDictionaryEnumerator
                while (objIDictionaryEnumerator.MoveNext())                             //checking if IDictionaryEnumerator has records
                {
                    XmlElement invoice = xmlDoc.CreateElement("InvoicePymt");
                    invPymts.AppendChild(invoice);

                    // invoice number
                    XmlElement invNum = xmlDoc.CreateElement("InvoiceNum");
                    invNum.InnerText = objIDictionaryEnumerator.Key.ToString();
                    invoice.AppendChild(invNum);

                    // amount paid on invoice num
                    XmlElement invAmt = xmlDoc.CreateElement("InvoiceAmt");
                    invAmt.InnerText = objIDictionaryEnumerator.Value.ToString();
                    invoice.AppendChild(invAmt);
                }

                pymt.AppendChild(invPymts);
               
                // Email confirmation
                XmlElement emailcnfrm = xmlDoc.CreateElement("EmailConfirm");
                emailcnfrm.InnerText = objGetDetails.EmailConfirmation;
                pymt.AppendChild(emailcnfrm);

            return xmlDoc;
        }

}

Thursday 4 July 2013

Insert/update using more than one database placed on different servers


Introduction:


Most of the time it needs to connect more than one database to perform DML queries. We can insert or update records from our database to another database. But sometime these database can be on different servers too. In that case we need to first establish communication between these servers. Please follow the below steps:

Code:


sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
set IDENTITY_INSERT [table name] off
insert into [table name](col1,col2,col3)
SELECT mycol1,mycol2,ycol3 from OpenDataSource('SQLNCLI', 'Data Source=192.168.0.0;User ID=username;Password=pass').[database].[tablename] v
 WHERE v.id>12


update v
set col1=v1.mycol
from [table1] v
inner join OpenDataSource('SQLNCLI', 'Data Source=192.168.0.0;User ID=username;Password=pass').[database].[tablename] v1
on v.id=v1.id