Thursday 13 February 2014

Handling array in javascript

The Array object lets you store multiple values in a single variable. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


var arr = new Array( "Jon", "XXX", "Kit" );

The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array.

You can retrive array using indexs like arr[0], arr[1].
 
Splice Method:
Javascript array slice() method extracts a section of an array and returns a new array. It returns the extracted array based on the passed parameters.
 
Array.splice(startIndex,ItemToRemove,items);

It will add or remove to or from array as per requirement.
var fruits = ["Chair", "Table", "Mat"];
fruits.splice(2,0,"Glass","Bottle");

Output will be:["Chair", "Table", "Glass","Bottle","Mat"]

Unshift method: 

Javascript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

syntex:
array.unshift( element1, ..., elementN );

 You can find below example to get it more clearly:

<html>
   <head>
      <title>JavaScript Array unshift Method</title>
   </head>
   
   <body>
   
      <script type="text/javascript">
         var arr = new Array("orange", "mango", "banana", "sugar");
         
         var length = arr.unshift("water");
         document.write("Returned array is : " + arr );
         document.write("<br /> Length of the array is : " + length );
      </script>
      
   </body>
</html>

Hope it helps you.  I will come up with more ideas in future.

 

Sunday 2 February 2014

Email validation





Validate email address with the help of regex. Hope it helps you. Use it in your code and enjoy. Please let me know if it is wrong.

function validateEmail() {
    var errMessage;
   if (!validateMultipleEmailsCommaSeparated(document.getElementById("txtEmail").value)) {
            errMessage = 'Please enter valid email';
    }
  
}

function validateMultipleEmailsCommaSeparated(value) {
    var result = value.split( /[,;]+/ );
    for (var i = 0; i < result.length; i++)
    {
        if (!validateEmail(result[i]))
            return false;
    }
    return true;
}

function validateEmail(field) {
    var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    return (regex.test(field)) ? true : false;
}

Wednesday 11 December 2013

Some SQL tips

Hi,

Many times I stacked into my work when I start using SQL. So here are some SQL tips and solutions. Read it and enjoy.

What is SQL?

SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in relational database.
SQL is the standard language for Relation Database System. All relational database management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL as standard database language.

Why SQL?

  • Allows users to access data in relational database management systems.
  • Allows users to describe the data.
  • Allows users to define the data in database and manipulate that data.
  • Allows to embed within other languages using SQL modules, libraries & pre-compilers.
  • Allows users to create and drop databases and tables.
  • Allows users to create view, stored procedure, functions in a database.
  • Allows users to set permissions on tables, procedures, and views

SQL Commands:

The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified into groups based on their nature:

DDL - Data Definition Language:

CommandDescription
CREATECreates a new table, a view of a table, or other object in database
ALTERModifies an existing database object, such as a table.
DROPDeletes an entire table, a view of a table or other object in the database.

DML - Data Manipulation Language:

CommandDescription
SELECTRetrieves certain records from one or more tables
INSERTCreates a record
UPDATEModifies records
DELETEDeletes records

DCL - Data Control Language:

CommandDescription
GRANTGives a privilege to user
REVOKETakes back privileges granted from user

I will add more content to this in upcoming days. Till then keep reading.
 

Tuesday 3 December 2013

Decimal place

Hi,
 
Whenever we implement payment related things and we are using decimal values,
it happens that we need to allow 2 digit or three digit after decimal place.
Here is the code for the same. Below you can see two set of code.
 
One is for general use and other we can use at the place where we are using 
culture base implementation.
 
Simple:
 
This is the simple code to allow only two digit after decimal.
This will auto correct the value to two decimal place.
 
 function validNum(ctrl) {
        $(ctrl).val(parseFloat($(ctrl).val(), 10).toFixed(2));
    }
 
Culture based:

 Below code will show to use this when playing with multiple cultures.
 
var DecimalSeperator=',';  //This is for sweden culture 
   function roundDecimalValue(ctrl, roundedValue) {
        var value = $(ctrl).val().trim();
        if (value.length>0) {
            value = value.replace(DecimalSeperator, ".");
            value = parseFloat(value, 10).toFixed(roundedValue);
            // alert(val + "|" + $(ctrl).val());
            value = value.replace(".", DecimalSeperator);
            $(ctrl).val(value);
        }
    } 
 
 
Hope this can help you.
 

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

Friday 26 April 2013

Javascript/Jquery tricks

Apply below tricks in your code and see the results.  

1. Calling  server side function from javascript


        function CallServerSideFuncFromJavascript(name, sender) {
        var url = "/testfolder/myfunc";

        var data = "value=" + name;
        $.ajax({
            url: url,
            data: data,
            type: "POST",
            success: function (value) {
                if (value != "Null") {
                    sender.SetText(value);
                }
            }
        });
    }


2. Validating SSN through javascript


    function ValidateSSN(s, e) {
        var value = s.GetValue();

        if (value != null && value.trim().length > 0) {
            len = 10 - value.trim().length;

            value = len > 0 ? new Array(len).join('0') + value : value

            s.SetValue(value.toUpperCase());
        }

    }


3. Restrict user entering specific values:

<input type="text" onkeypress="return  ValidateText(event);" />

    function ValidateText(evt)
{
var value = String.fromCharCode(evt.which ? evt.which : evt.keyCode);
if(value=="^" || value=="<" || value=="*")
{
return false;
}
return true;
}

4. Enable/ Disable button through jquery


To disable a button:

$("input[type=submit]").attr("disabled", "disabled");
or
$("#btnSubmit").attr("disabled", "disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").attr("disabled", "disabled");
});


To enable a button:

$("input[type=submit]").removeAttr("disabled");
or
$("#btnSubmit").removeAttr("disabled");

Implementation:
$(document).ready(function(){
  $("#btnSubmit").removeAttr("disabled");
});

We can use it with any html control. functionality will be same.


5. Check if text in  textbox is selected or not.

 function CheckTextSelectionInTextBox(ctrl) {
        if (document.selection != undefined) {
            var sel = document.selection.createRange();
            selectedText = sel.text;
            if (selectedText != "") {
                return true;
            }
        }
        // Mozilla version
        else if (ctrl.selectionStart != undefined) {
            if (ctrl.selectionStart != ctrl.selectionEnd) {
                return true;
            }
        }
        return false;
    }

<input type="text" onkeypress="return CheckTextSelectionInTextBox(this); " />




I will get back soon with more solutions and tricks.