Tuesday, August 10, 2010

Data Exchange between SQL server & Excel

Data Exchange between SQL server & Excel


  Sometime we need to pass data to & fro from excel sheet and SQL server. To accomplish this task we can write two functions that one that import data from excel sheet to your table in database here we can use bulk copy class. We could Column mapping to map column from excel sheet to column from database.
  Many time we have Identity on First column we should not include that column in our excel sheet which we are going to import into database table. We need to have fair understanding of constraint on column like unique key constraint, check constraint that should not get violated by data in excel sheet.
     We will try out our trick on country table which can be created as follows

CREATE TABLE [dbo].[Country](
    [CountryId] [int] IDENTITY(1,1) NOT NULL,
    [CountryName] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [CountryCapital] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [CountryCurrency] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [CountryCurrencySymbol] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [CreatedDatetime] [datetime] NULL,
    [LastAccessDatetime] [datetime] NULL,
    [Deleted] [char](1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_Country_Deleted]  DEFAULT ('N'),
    [CountryLongDesc] [varchar](500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
)

Here CountryId has identity & primary key,Delete has check constraint for value between ‘Y’ & ‘N’.

Function To Import Excel-sheet to sql server may look like

Code:

    public static void ImportExcelToDb(String FilePath,string TableName)
        {
          string strMappedPath = System.Web.HttpContext.Current.Server.MapPath(FilePath);
          string ExcelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strMappedPath + @";Extended Properties=""Excel 8.0;HDR=YES;""";
          string destinationConnectionString = ConfigurationManager.ConnectionStrings["MSSQL"].ConnectionString;
          OleDbConnection ExcelConnection = new OleDbConnection(ExcelConnectionString);
         
          ExcelConnection.Open();
          OleDbCommand Excelcommand = new OleDbCommand("Select * FROM [Country$]", ExcelConnection);
          OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(Excelcommand);
          ExcelAdapter.SelectCommand = Excelcommand;
          DataSet dsExcel = new DataSet();
          ExcelAdapter.Fill(dsExcel);
          ExcelConnection.Close();
          SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnectionString);
          bulkCopy.DestinationTableName = TableName;

          bulkCopy.ColumnMappings.Add("CountryName", "CountryName");
          bulkCopy.ColumnMappings.Add("CountryCapital", "CountryCapital");
          bulkCopy.ColumnMappings.Add("CountryCurrency", "CountryCurrency");
          bulkCopy.ColumnMappings.Add("CountryCurrencySymbol", "CountryCurrencySymbol");
          bulkCopy.ColumnMappings.Add("CreatedDatetime", "CreatedDatetime");
          bulkCopy.ColumnMappings.Add("LastAccessDatetime", "LastAccessDatetime");
          bulkCopy.ColumnMappings.Add("Deleted", "Deleted");
          bulkCopy.ColumnMappings.Add("CountryLongDesc", "CountryLongDesc");

          bulkCopy.WriteToServer(dsExcel.Tables[0]);
        }

    In this function I am passing ‘FilePath’ as first param which is relative path of our .xls(say book.xls) file.This file has one sheet Named Country which will act as source for data

How book.xls look like:

CountryName    CountryCapital    CountryCurrency    CountryCurrencySymbol    CreatedDatetime    LastAccessDatetime    Deleted    CountryLongDesc
Indiana    Delhi    Rupee    Rs    2010-08-03    2010-08-03    N    India
Pokistan    Islamabad    Rupee    Rs    2010-08-03    2010-08-03    N    Pakistan
Nopel    Kathmandoo    Rupee    Rs    2010-08-03    2010-08-04    N    Nepal
UZA    Washington D.C.    Dollar    $    2010-08-03    2010-08-03    N    USA
UL    London    Pound    P    2010-08-04    2010-08-04    N    England

Now Time to Export Data from Sql Server to Excel sheet.

Here are useful functions that I am using for this purpose

Code:
public static void ExportFromDbToExcel(string TableName)
        {
            DataSet ds;
            string StrConnectionString = ConfigurationManager.ConnectionStrings["MSSQL"].ConnectionString;
            IDBManager dbManager = new DBManager(DataProvider.MSSQL, StrConnectionString);
            dbManager.Open();
            string strCmd = "select CountryName,CountryCapital,CountryCurrency,CountryCurrencySymbol,CONVERT(datetime,CreatedDatetime,120)CreatedDatetime,CONVERT(datetime,LastAccessDatetime,120) LastAccessDatetime from " + TableName;
            ds = dbManager.ExecuteDataSet(CommandType.Text, strCmd);
            dbManager.Close();
            MSSQLHelper.ExportDataSetToExcel(ds, TableName);
        }

        public static void ExportDataSetToExcel(DataSet ds, string filename)
        {
            HttpResponse response = HttpContext.Current.Response;
            filename = filename + ".xls";
            response.Clear();
            response.Charset = "";

            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

            using (StringWriter stringwriter = new StringWriter())
            {
                using (HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter))
                {
                    GridView gv = new GridView();
                    gv.DataSource = ds.Tables[0];
                    gv.DataBind();
                    gv.RenderControl(htmlwriter);
                    response.Write(stringwriter.ToString());
                    response.End();
                }
            }
        }

The second function ‘ExportDataSetToExcel’ actually convert dataset to excel sheet,first function query the table from database read the required data in dataset & pass this dataset to second function which do needfull

Saturday, August 7, 2010

Integrating HDFC Payment Gateway in ASP.NET

Integrating HDFC Payment Gateway in ASP.NET

      Last time when I was trying to integrated in hdfc payment gateway I searched online
But little help was available reading long manual learning terms used is no doubt essential but some time you want to know you are following right path. From by personal experience I can now help someone caught in similar situation like mine.
  Code provided bellow is not elegant though it works fine. I am showing bellow the simplest way to get work done then in your comfort zone do the modification.
  I hope this will be helpful to at least one guy scratching his head.

When merchant buys hdfc payment gateway he will be provided with files for integration those file include resource.cgn .The dll provided in kit
“e24PaymentPipe.dl” needs to be registered using regsvr32 command.

   Then you will have a folder named trans which contain the asp files namely
a)Buy.asp
b)Success.asp
c)TransFailure.asp
d) redirect.asp
e)Pay.asp
f)index.asp

it will contain a merchant.config file you need to modify the file

The Content Is as Follows

tran.currency=356’currency INR
consumer.language=USA’prefered language
tran.action=4
merchant.receiptURL=http://www.yoursite.com/Trans/redirect.asp
merchant.errorURL=http://www.yoursite.com/Trans/tranfailure.asp
gateway.headerCount=1
gateway.header=1
gateway.resource.path=yourpathto/resource/
gateway.terminal.alias=yourAlias
gateway.Institute.alias=HDFC
gateway.InstituteDesc.alias=HDFC VISA Payment Mode

From your ASPX page do response.redirect to Buy.asp with releveant information

How Buy.asp looks like

<HTML><HEAD><TITLE>YourSite</TITLE>
<%
Dim MyObj
Dim vargatewayheader
Dim id
Dim StartRecord
dim inc
inc = 0
dim gatevalues
dim TranCurrency,ConsumerLanguage,TranAction,MerchantReceiptURL,MerchantErrorURL
Dim ResourcePath,TerminalAlias
Dim Headcount

'Creating the object of e24PaymentPipe(DLL registered)
Set MyObj = Server.CreateObject("e24PaymentPipe.e24PaymentPipe.1")
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("Merchant.config"), 1)
StartRecord = "FALSE"
id = request.form("InstituteID")
Response.write("Institute ID : "& id) & "<br>"
do  while f.AtEndOfLine <> true
vargatewayheader = f.readline
splitline = split(vargatewayheader,"=")
if splitline(0) = "tran.currency" then
    TranCurrency = splitline(1)
elseif splitline(0) = "consumer.language" then
    ConsumerLanguage= splitline(1)
elseif splitline(0) = "tran.action" then
    TranAction = splitline(1)
elseif splitline(0) = "merchant.receiptURL" then
    MerchantReceiptURL= splitline(1)
elseif splitline(0) = "merchant.errorURL" then
    MerchantErrorURL= splitline(1)
elseif splitline(0) = "gateway.headerCount" then
    Headcount = splitline(1)
    Response.write("Header Count : "& Headcount) & "<br>"
elseif splitline(0) = "gateway.header" then
    if HeadCount = 1 then
            id = splitline(1)
            Response.write("One Institute ID : "& id) & "<br>"
    end if
  
end if

if vargatewayheader = "gateway.header=" & id  then
        StartRecord = "TRUE"
else
        if StartRecord = "TRUE" then
            if inc = 0  then
                gatevalues = split(vargatewayheader,"=")
                ResourcePath = gatevalues(1)
                'response.write(ResourcePath) &"<br>"
              
                inc =1
            elseif inc = 1  then
                'Response.write(vargatewayheader) & "<BR>"
                gatevalues = split(vargatewayheader,"=")
                TerminalAlias = gatevalues(1)
                response.write(TerminalAlias) &"<br>"
                inc = 2
            elseif inc = 2  then
                'Response.write(vargatewayheader) & "<BR>"
                inc =3
            elseif inc = 3  then
                'Response.write(vargatewayheader) & "<BR>"
                inc =0
                StartRecord = "FALSE"
            end if
        end if
end if
loop


MyObj.ResourcePath = ResourcePath
MyObj.Alias = TerminalAlias
response.write(ResourcePath) &"<br>"
response.write(TerminalAlias) &"<br>"
MyObj.Action = 4
MyObj.Amt = Request.QueryString("Amt")
MyObj.Currency = TranCurrency
MyObj.ResponseURL = MerchantReceiptURL
MyObj.ErrorURL = MerchantErrorURL
trackid     = cstr(session.sessionid) + cstr(second(now)) + cstr(minute(now)) 'Generating Merchant Track ID
MyObj.TrackId = trackid

response.write("trackid : " &MyObj.TrackId) &"<br>" 'trackid
response.write("TranAction : " &MyObj.Action) &"<br>" 'TranAction
response.write("session amt --:"&MyObj.Amt) &"<br>"
response.write("Currency :"&TranCurrency) &"<br>" '
response.write("Consumer Language: "&ConsumerLanguage) &"<br>"
response.write("MerchantReceiptURL : " &MyObj.ResponseURL) &"<br>" ' MerchantReceiptURL
response.write("MerchantErrorURL: " &MyObj.ErrorURL) &"<br>"
MyObj.Udf1 = Request.QueryString("ordno")
MyObj.Udf2 = Request.QueryString("Email")
MyObj.Udf3 = Request.QueryString("phone")
MyObj.Udf4 = Request.QueryString("Area")
MyObj.Udf5 = Request.QueryString("Pincode")
response.write("UDF1 =" &MyObj.Udf1) &"<br>"
response.write("UDF2 =" &MyObj.Udf2) &"<br>"
response.write("UDF3 =" &MyObj.Udf3) &"<br>"
response.write("UDF4 =" &MyObj.Udf4) &"<br>"
response.write("UDF5 =" &MyObj.Udf5) &"<br>"



Dim TransVal,varPaymentId, varPaymentPage,varErrorMsg,varRawResponse

'perform the transaction
TransVal = MyObj.PerformInitTransaction 'returns 0 for succes AND  -1 for failure

response.write("tranval--:"&TransVal) &"<br>"

varRawResponse = MyObj.RawResponse
varPaymentId = MyObj.PaymentId
varPaymentPage = MyObj.PaymentPage
varErrorMsg = MyObj.ErrorMsg

response.write("varRawResponse : " &varRawResponse) &"<br>"
response.write("varErrorMsg : " &varErrorMsg) &"<br>"
response.write("url--:"&varPaymentPage) &"<br>"

Response.write(varPaymentPage & "?PaymentID=" & varPaymentId )

if(Transval=0) Then
    Response.redirect(varPaymentPage & "?PaymentID=" & varPaymentId)
else
    Response.write("REDIRECT=http://YourSite.com/Trans/tranfailure.asp?PaymentID="& varPaymentid)
end If


%>
</HEAD> </HTML>


How Redirect.asp looks Like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD></head>
<body bgcolor="#FFFFFF">
<%

Dim ErrorTx,ErrorResult,payID,result,tranid,trackid,postdate,auth,ref,amt,udf1,udf2,udf3,udf4,udf5,s

ErrorTx = request("Error")
ErrorResult = request("ErrorText")
payID = request("paymentid")
result   = request("result")
tranid  = request("tranid")
trackid  = request("trackid")
postdate = request("postdate")
auth     = request("auth")
ref=request("ref")
amt=request("amt")
udf1 = request("udf1")
udf2 = request("udf2")
udf3 = request("udf3")
udf4 = request("udf4")
udf5 = request("udf5")
s=""


if result="CANCELED" then

  

response.write("REDIRECT=http://YourSite.com/Trans/tranfailure.asp?paymentid="&payID&"&auth="&auth&"&amt="&amt&"&ref="&ref&"&tranid="&tranid&"&trackid="&trackid&"&postdate="&postdate&"&result="&result&"&Udf1="&udf1&"&Udf2="&udf2&"&Udf3="&udf3&"&Udf4="&udf4&"&Udf5="&udf5)

ElseIf errorTx <> Null Then

response.write("REDIRECT=http://YourSite.com.com/Trans/tranfailure.asp?paymentid="&payID&"&auth="&auth&"&amt="&amt&"&ref="&ref&"&tranid="&tranid&"&trackid="&trackid&"&postdate="&postdate&"&result="&result&"&Udf1="&udf1&"&Udf2="&udf2&"&Udf3="&udf3&"&Udf4="&udf4&"&Udf5="&udf5&"&ErrorResult="&ErrorResult)

Else


response.write("REDIRECT=http://YourSite.com/Trans/success.asp?paymentid="&payID&"&auth="&auth&"&amt="&amt&"&ref="&ref&"&tranid="&tranid&"&trackid="&trackid&"&postdate="&postdate&"&result="&result&"&Udf1="&udf1&"&Udf2="&udf2&"&Udf3="&udf3&"&Udf4="&udf4&"&Udf5="&udf5&"&ErrorResult="&ErrorResult)

End If

%>
</body>
</HTML>


How Success.asp look like

<%
Dim s,postdate,tranid,auth,trackid,payID,udf1,amt,ref

s=request("result")
postdate=request("postdate")
tranid=request("tranid")
auth=request("auth")
trackid=request("trackid")
payID = request("paymentid")
udf1 = request("udf1")
amt=request("amt")
ref=request("ref")

ErrorResult=request("ErrorResult")
%>
<HTML>
<HEAD>
<TITLE>Himalaya Fine Art: Transaction Result</TITLE>
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<META name="GENERATOR" content="Microsoft FrontPage 6.0">
</HEAD>
<BODY bgcolor="#FFFFFF">
<CENTER>
<div align="center">
  <br>
    <table>
      <tr>
           <TD height="25">
                <strong>Your transaction was &nbsp;<b><font color="blue"><%=s%><%=ErrorResult%></font></b></strong>
            </TD>
       </tr>
      </table>
  <br>
</div>
<div align="center">
  <center>
<TABLE border=1  bordercolor=black width="306" bgcolor="#F0F2FF" style="border-collapse: collapse; border: 1px outset #999999" cellpadding="0" cellspacing="0"><tr>
  <td width="296">
<div align="center">
  <center>
<TABLE border=1  bordercolor=#FFFFFF width="90%" style="border-collapse: collapse" cellpadding="3"><tr><td>
        <TR>
            <TD colspan="2" align="center" height="25" valign="bottom">
                <FONT size="4"><B>Transaction Details  </B></FONT>
            </TD>
        </TR>

      
      
        <TR>
            <TD colspan="2" align="center" height="25">
                <HR>
            </TD>
        </TR>

        <TR>
            <TD width="40%" bgcolor="#FFFFFF" height="25"><b>
            <font size="2" face="Arial">Track ID</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=trackid%></TD>
        </TR>

        <TR>
            <TD height="25"><b><font size="2" face="Arial">Result</font></b></TD>
            <TD height="25"><font color="blue"><b><%=s%><%=ErrorResult%></b></TD>
        </TR>
      
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">Payment ID</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=payID%></TD>
        </TR>
      
        <TR>
            <TD height="25"><b><font size="2" face="Arial">Transaction ID</font></b></TD>
            <TD height="25"><%=tranid%></TD>
        </TR>
      
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">Post Date</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=postdate%></TD>
        </TR>

        <TR>
             <TD height="25"><b><font size="2" face="Arial">Amount</font></b></TD>
              <TD height="25"><%=amt%></TD>
        </TR>
  
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">Auth Code</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=auth%></TD>
        </TR>
        <TR>
            <TD height="25"><b><font size="2" face="Arial">Reference ID</font></b></TD>
            <td height="25"><%=ref%></td>
      
        </TR>
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">
            Order No.</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=udf1%></TD>
        </TR>
        <TR>
            <TD height="25"><b><font size="2" face="Arial">E-mail</font></b></TD>
            <TD height="25"><%=request("udf2")%></TD>
        </TR>
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">Tel
            No.</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=request("udf3")%></TD>
        </TR>
        <TR>
            <TD height="25"><b><font size="2" face="Arial">Address</font></b></TD>
            <TD height="25"><%=request("udf4")%></TD>
        </TR>
        <TR>
            <TD bgcolor="#FFFFFF" height="25"><b><font size="2" face="Arial">
            City, PIN</font></b></TD>
            <TD bgcolor="#FFFFFF" height="25"><%=request("udf5")%></TD>
        </TR>
  
        </td></tr></table></center>
</div>
  </td></tr></table>
        </center>
</div>
        <div align="center" style="font-size:20px;"><br><br>
            <p>
            <% if ErrorResult <> "APPROVED" then %>
                <a href="http://www.YourSite.com/yourpage.aspx" >Select another payment option</a>
            <% End if %>
            </p>
            <a href="http://www.YourSite.com/yourpage.aspx">Close</a>
        </div>
</BODY>
</HTML>

How transfailure.asp looks like

<HTML>
<HEAD>
<TITLE>Transaction Failure Page</TITLE>
</HEAD>
<BODY>
<center>
<div align="center"><br>
  <strong>OOPS!</strong> There was some problem. Your transaction was <strong>NOT</strong> successful<br>
  <br>
<%
dim tranID
tranID=request("tranid")
dim result,canResult,errortx


canResult=request("result")
ErrorResult=request("ErrorResult")


If canResult <> null and canResult="CANCELED" then
%>
 
</div>
<div align="center">

<TABLE border=1  bordercolor=black width="437" bgcolor="#E8F3FF"><tr><td>
<div align="center">
<TABLE border=0  bordercolor=black cellspacing="6" cellpadding="3" width="362"><tr><td>

        <TR>
            <TD colspan="2" align="center">
                <FONT size="4"><B>Transaction Details</B></FONT>
            </TD>
        </TR>
        <TR>
            <TD colspan="2" align="center">
                <HR>
            </TD>
        </TR>
        <TR>
            <TD bgcolor="#F9FCFF">Result </TD>
            <TD bgcolor="#F9FCFF"><font color="blue"><b><%=canResult%><%=ErrorResult%></b></TD>
        </TR>

        <TR>
            <TD>Payment ID</TD>
            <TD><%=request("paymentid")%></TD>
        </TR>


        <TR>
            <TD width="40%" bgcolor="#F9FCFF">Track ID</TD>
            <TD bgcolor="#F9FCFF"><%=request("trackid")%></TD>
           </TR>
        <TR>
            <TD>Order No.</TD>
            <TD><%=request("udf1")%></TD>
        </TR>
        <TR>
            <TD bgcolor="#F9FCFF">Email</TD>
            <TD bgcolor="#F9FCFF"><%=request("udf2")%></TD>
        </TR>
        <TR>
            <TD>Tel</TD>
            <TD><%=request("udf3")%></TD>
            <TR>
            <TD bgcolor="#F9FCFF">Address</TD>
            <TD bgcolor="#F9FCFF"><%=request("udf4")%></TD>
        </TR>
        <TR>
            <TD>Pin</TD>
            <TD><%=request("udf5")%></TD>
        </TR>
        </td></tr></table></div>
    </td></tr></table>

</div>

<% else%>
<div align="center">
<TABLE border=1  bordercolor=black width="437" bgcolor="#E8F3FF"><tr><td>
<div align="center">
<TABLE border=0  bordercolor=black cellspacing="6" cellpadding="3" width="360"><tr><td>

        <TR>
            <TD colspan="2" align="center">
                <FONT size="4"><B>Transaction Details  </B></FONT>
            </TD>
        </TR>
        <TR>
            <TD colspan="2" align="center">
                <HR>
            </TD>
        </TR>
            <TR>
            <TD bgcolor="#F9FCFF">Result </TD>
            <TD bgcolor="#F9FCFF"><font color="red"><b><%=canresult%><%=ErrorResult%></b></TD>
           </TR>
           <TR>
            <TD width="40%">Payment ID</TD>
            <TD><%=request("paymentid")%></TD>
           </TR>
         
        <TR>
            <TD bgcolor="#F9FCFF">Order No.</TD>
            <TD bgcolor="#F9FCFF"><%=request("udf1")%></TD>
        </TR>
        <TR>
            <TD>Email</TD>
            <TD><%=request("udf2")%></TD>
        </TR>
        <TR>
            <TD bgcolor="#F9FCFF">Tel</TD>
            <TD bgcolor="#F9FCFF"><%=request("udf3")%></TD>
        </TR>


      <TR>
            <TD>Address</TD>
            <TD><%=request("udf4")%></TD>
        </TR>
        <TR>
            <TD bgcolor="#F9FCFF">Pin</TD>
            <TD bgcolor="#F9FCFF"><%=request("udf5")%></TD>
        </TR>
        </td></tr></table></div>
    </td></tr></table>

</div>

<%End if%>

<br>
    <center>
<p><a href="http://www.YourSite.com/done.aspx">Quit</a></p>
<p><a href="http://www.YourSite.com/payment.aspx">Select another payment
option</a></p>
</center>
</HTML> 

How Pay.asp look like
<%@ Page Language="VB" AspCompat="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Protected Sub page_load(ByVal sender As Object, ByVal e As EventArgs)
        If (Not Page.IsPostBack) Then
            Dim MyObj
            Dim vargatewayheader
            Dim id
            Dim StartRecord
            Dim inc
            inc = 0
            Dim gatevalues
            Dim TranCurrency, ConsumerLanguage, TranAction, MerchantReceiptURL, MerchantErrorURL, Amt
            Dim ResourcePath, TerminalAlias
            Dim Headcount
            MyObj = Server.CreateObject("e24PaymentPipe.e24PaymentPipe.1")
            Dim fs = Server.CreateObject("Scripting.FileSystemObject")
            ResourcePath = "YourPath/Trans/Merchant.config"
            TerminalAlias = "Term1"
            TranAction = "4"
            Amt = "1000"
            MerchantReceiptURL = "http://YourSite.com/Trans/success.asp"
            MerchantErrorURL = "http://YourSite.com/Trans/tranfailure.asp"
            'Response.Redirect("https://securepgtest.fssnet.co.in:443/pgway/gateway/payment/payment.jsp?PaymentID=XXXXXXXXXX")
            StartRecord = "FALSE"
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Response.Redirect("Buy.asp?Amt=123000.00")
    End Sub
</script>

Create a trans & resource folder on your site in same folder where you have aspx files lies

Caution:
 Make sure that you do not play with resource.cgn, out of curiosity if you open this file it become useless.

When you are redirecting from your aspx page you can use query string as follows

Trans/Buy.asp?Amt=100&OrdNo=666&Email=sangram2681@gmail.com&phone=986786687&
Area=address&Pincode=Mumbai 400074

The gateway let us to pass 5 custom field with udf1, udf2, udf3, udf4 & udf5.I am here using ufd1 for order-no,udf2 for emailed,udf3 for contact number,udf4 for address and udf5 for city & pin separated by space. The url passed from aspx page to buy.asp is parsed to get values for order,address,phone number,emailid and get assigned to corresponding udf field.
  In buy.asp we retrieve data from merchant.config file and using asp file file handling read file line by line ,split each line on “=” sign the second part in array in required value while 1st part is key to it.


Now try your luck!

Wednesday, August 4, 2010

Checking The Folder Right Permission With C#

    During Search for almost 2-3 hours reading msdn,finding how access rights on particular folder be found out before uploading I come across one class on codeproject that has done it pretty well.With Due Credit to him for such good work as there is little help available on internet regarding System.Security,
System.Security.AccessControl,System.Security.Principal namespace.
I am Listing The class below.

The class Bellow:

using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;

namespace Conflux.BLL
{
 class UserFileAccessRights
    {
        private string _path;
        private System.Security.Principal.WindowsIdentity _principal;

        private bool _denyAppendData = false;
        private bool _denyChangePermissions = false;
        private bool _denyCreateDirectories = false;
        private bool _denyCreateFiles = false;
        private bool _denyDelete = false;
        private bool _denyDeleteSubdirectoriesAndFiles = false;
        private bool _denyExecuteFile = false;
        private bool _denyFullControl = false;
        private bool _denyListDirectory = false;
        private bool _denyModify = false;
        private bool _denyRead = false;
        private bool _denyReadAndExecute = false;
        private bool _denyReadAttributes = false;
        private bool _denyReadData = false;
        private bool _denyReadExtendedAttributes = false;
        private bool _denyReadPermissions = false;
        private bool _denySynchronize = false;
        private bool _denyTakeOwnership = false;
        private bool _denyTraverse = false;
        private bool _denyWrite = false;
        private bool _denyWriteAttributes = false;
        private bool _denyWriteData = false;
        private bool _denyWriteExtendedAttributes = false;

        private bool _allowAppendData = false;
        private bool _allowChangePermissions = false;
        private bool _allowCreateDirectories = false;
        private bool _allowCreateFiles = false;
        private bool _allowDelete = false;
        private bool _allowDeleteSubdirectoriesAndFiles = false;
        private bool _allowExecuteFile = false;
        private bool _allowFullControl = false;
        private bool _allowListDirectory = false;
        private bool _allowModify = false;
        private bool _allowRead = false;
        private bool _allowReadAndExecute = false;
        private bool _allowReadAttributes = false;
        private bool _allowReadData = false;
        private bool _allowReadExtendedAttributes = false;
        private bool _allowReadPermissions = false;
        private bool _allowSynchronize = false;
        private bool _allowTakeOwnership = false;
        private bool _allowTraverse = false;
        private bool _allowWrite = false;
        private bool _allowWriteAttributes = false;
        private bool _allowWriteData = false;
        private bool _allowWriteExtendedAttributes = false;

        public bool canAppendData()
        {
            return !_denyAppendData&&_allowAppendData;
        }
       
        public bool canChangePermissions()
        {
            return !_denyChangePermissions&&_allowChangePermissions;
        }

        public bool canCreateDirectories()
        {
            return !_denyCreateDirectories&&_allowCreateDirectories;
        }
       
        public bool canCreateFiles()
        {
            return !_denyCreateFiles&&_allowCreateFiles;
        }
       
        public bool canDelete()
        {
            return !_denyDelete && _allowDelete;
        }
       
        public bool canDeleteSubdirectoriesAndFiles()
        {
            return !_denyDeleteSubdirectoriesAndFiles && _allowDeleteSubdirectoriesAndFiles;
        }
       
        public bool canExecuteFile()
        {
            return !_denyExecuteFile && _allowExecuteFile;
        }

        public bool canFullControl()
        {
            return !_denyFullControl && _allowFullControl;
        }
       
        public bool canListDirectory()
        {
            return !_denyListDirectory && _allowListDirectory;
        }
       
        public bool canModify()
        {
            return !_denyModify && _allowModify;
        }
       
        public bool canRead()
        {
            return !_denyRead && _allowRead;
        }
       
        public bool canReadAndExecute()
        {
            return !_denyReadAndExecute && _allowReadAndExecute;
        }
       
        public bool canReadAttributes()
        {
            return !_denyReadAttributes && _allowReadAttributes;
        }
       
        public bool canReadData()
        {
            return !_denyReadData && _allowReadData;
        }
       
        public bool canReadExtendedAttributes()
        {
            return !_denyReadExtendedAttributes && _allowReadExtendedAttributes;
        }
       
        public bool canReadPermissions()
        {
            return !_denyReadPermissions && _allowReadPermissions;
        }
       
        public bool canSynchronize()
        {
            return !_denySynchronize && _allowSynchronize;
        }

        public bool canTakeOwnership()
        {
            return !_denyTakeOwnership && _allowTakeOwnership;
        }
       
        public bool canTraverse()
        {
            return !_denyTraverse && _allowTraverse;
        }

        public bool canWrite()
        {
            return !_denyWrite && _allowWrite;
        }

        public bool canWriteAttributes()
        {
            return !_denyWriteAttributes && _allowWriteAttributes;
        }
       
        public bool canWriteData()
        {
            return !_denyWriteData && _allowWriteData;
        }

        public bool canWriteExtendedAttributes()
        {
            return !_denyWriteExtendedAttributes && _allowWriteExtendedAttributes;
        }

        /// <summary>
        /// Simple accessor
        /// </summary>
        /// <returns></returns>
        public System.Security.Principal.WindowsIdentity getWindowsIdentity()
        {
            return _principal;
        }
        /// <summary>
        /// Simple accessor
        /// </summary>
        /// <returns></returns>
        public String getPath()
        {
            return _path;
        }

        /// <summary>
        /// Convenience constructor assumes the current user
        /// </summary>
        /// <param name="path"></param>
        public UserFileAccessRights(string path) :this(path, System.Security.Principal.WindowsIdentity.GetCurrent())
        {
        }


        /// <summary>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// </summary>
        /// <param name="path"></param>
        /// <param name="principal"></param>
        public UserFileAccessRights(string path,System.Security.Principal.WindowsIdentity principal)
        {
            this._path = path;
            this._principal = principal;
                       
            try
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (_principal.User.Equals(rule.IdentityReference))
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals(rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData,rule)) _denyAppendData = true;
                            if (contains(FileSystemRights.ChangePermissions,rule)) _denyChangePermissions = true;
                            if (contains(FileSystemRights.CreateDirectories,rule)) _denyCreateDirectories = true;
                            if (contains(FileSystemRights.CreateFiles,rule))       _denyCreateFiles = true;
                            if (contains(FileSystemRights.Delete,rule))            _denyDelete = true;
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,rule)) _denyDeleteSubdirectoriesAndFiles = true;
                            if (contains(FileSystemRights.ExecuteFile,rule)) _denyExecuteFile = true;
                            if (contains(FileSystemRights.FullControl,rule)) _denyFullControl = true;
                            if (contains(FileSystemRights.ListDirectory,rule))_denyListDirectory = true;
                            if (contains(FileSystemRights.Modify,rule))_denyModify = true;
                            if (contains(FileSystemRights.Read,rule)) _denyRead = true;
                            if (contains(FileSystemRights.ReadAndExecute,rule))_denyReadAndExecute = true;
                            if (contains(FileSystemRights.ReadAttributes,rule))_denyReadAttributes = true;
                            if (contains(FileSystemRights.ReadData,rule)) _denyReadData = true;
                            if (contains(FileSystemRights.ReadExtendedAttributes,rule))_denyReadExtendedAttributes = true;
                            if (contains(FileSystemRights.ReadPermissions,rule))_denyReadPermissions = true;
                            if (contains(FileSystemRights.Synchronize,rule))_denySynchronize = true;
                            if (contains(FileSystemRights.TakeOwnership,rule))_denyTakeOwnership = true;
                            if (contains(FileSystemRights.Traverse,rule))_denyTraverse = true;
                            if (contains(FileSystemRights.Write,rule)) _denyWrite = true;
                            if (contains(FileSystemRights.WriteAttributes,rule))
                                  _denyWriteAttributes = true;
                            if (contains(FileSystemRights.WriteData,rule))
                                  _denyWriteData = true;
                            if (contains(FileSystemRights.WriteExtendedAttributes,rule))
                                  _denyWriteExtendedAttributes = true;
                        }else if (System.Security.AccessControl.AccessControlType.
                                  Allow.Equals(rule.AccessControlType)) {
                            if (contains(FileSystemRights.AppendData, rule))
                                  _allowAppendData = true;
                            if (contains(FileSystemRights.ChangePermissions, rule))
                                  _allowChangePermissions = true;
                            if (contains(FileSystemRights.CreateDirectories, rule))
                                  _allowCreateDirectories = true;
                            if (contains(FileSystemRights.CreateFiles, rule))
                                  _allowCreateFiles = true;
                            if (contains(FileSystemRights.Delete, rule))
                                  _allowDelete = true;
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                  rule))_allowDeleteSubdirectoriesAndFiles = true;
                            if (contains(FileSystemRights.ExecuteFile, rule))
                                  _allowExecuteFile = true;
                            if (contains(FileSystemRights.FullControl, rule))
                                  _allowFullControl = true;
                            if (contains(FileSystemRights.ListDirectory, rule))
                                  _allowListDirectory = true;
                            if (contains(FileSystemRights.Modify, rule))
                                  _allowModify = true;
                            if (contains(FileSystemRights.Read, rule))_allowRead = true;
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                                  _allowReadAndExecute = true;
                            if (contains(FileSystemRights.ReadAttributes, rule))
                                  _allowReadAttributes = true;
                            if (contains(FileSystemRights.ReadData, rule))
                                  _allowReadData = true;
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                                  _allowReadExtendedAttributes = true;
                            if (contains(FileSystemRights.ReadPermissions, rule))
                                  _allowReadPermissions = true;
                            if (contains(FileSystemRights.Synchronize, rule))
                                  _allowSynchronize = true;
                            if (contains(FileSystemRights.TakeOwnership, rule))
                                  _allowTakeOwnership = true;
                            if (contains(FileSystemRights.Traverse, rule))
                                  _allowTraverse = true;
                            if (contains(FileSystemRights.Write, rule))
                                  _allowWrite = true;
                            if (contains(FileSystemRights.WriteAttributes, rule))
                                  _allowWriteAttributes = true;
                            if (contains(FileSystemRights.WriteData, rule))
                                  _allowWriteData = true;
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                                  _allowWriteExtendedAttributes = true;
                        }
                    }
                }

                IdentityReferenceCollection groups = _principal.Groups;
                for (int j = 0; j < groups.Count; j++) {
                    for (int i = 0; i < acl.Count; i++) {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (groups[j].Equals(rule.IdentityReference)) {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType)) {
                                if (contains(FileSystemRights.AppendData,rule))
                                    _denyAppendData = true;
                                if (contains(FileSystemRights.ChangePermissions,rule))
                                    _denyChangePermissions = true;
                                if (contains(FileSystemRights.CreateDirectories,rule))
                                    _denyCreateDirectories = true;
                                if (contains(FileSystemRights.CreateFiles,rule))
                                    _denyCreateFiles = true;
                                if (contains(FileSystemRights.Delete,rule))
                                    _denyDelete = true;
                                if (contains(FileSystemRights.
                                    DeleteSubdirectoriesAndFiles,rule))
                                    _denyDeleteSubdirectoriesAndFiles = true;
                                if (contains(FileSystemRights.ExecuteFile,rule))
                                    _denyExecuteFile = true;
                                if (contains(FileSystemRights.FullControl,rule))
                                    _denyFullControl = true;
                                if (contains(FileSystemRights.ListDirectory,rule))
                                    _denyListDirectory = true;
                                if (contains(FileSystemRights.Modify,rule))
                                    _denyModify = true;
                                if (contains(FileSystemRights.Read,rule))
                                    _denyRead = true;
                                if (contains(FileSystemRights.ReadAndExecute,rule))
                                    _denyReadAndExecute = true;
                                if (contains(FileSystemRights.ReadAttributes,rule))
                                    _denyReadAttributes = true;
                                if (contains(FileSystemRights.ReadData,rule))
                                    _denyReadData = true;
                                if (contains(FileSystemRights.
                                        ReadExtendedAttributes,rule))
                                    _denyReadExtendedAttributes = true;
                                if (contains(FileSystemRights.ReadPermissions,rule))
                                    _denyReadPermissions = true;
                                if (contains(FileSystemRights.Synchronize,rule))
                                    _denySynchronize = true;
                                if (contains(FileSystemRights.TakeOwnership,rule))
                                    _denyTakeOwnership = true;
                                if (contains(FileSystemRights.Traverse,rule))
                                    _denyTraverse = true;
                                if (contains(FileSystemRights.Write,rule))
                                    _denyWrite = true;
                                if (contains(FileSystemRights.WriteAttributes,rule))
                                    _denyWriteAttributes = true;
                                if (contains(FileSystemRights.WriteData,rule))
                                    _denyWriteData = true;
                                if (contains(FileSystemRights.
                                        WriteExtendedAttributes,rule))
                                    _denyWriteExtendedAttributes = true;
                            }else if (System.Security.AccessControl.AccessControlType.
                                    Allow.Equals(rule.AccessControlType)) {
                                if (contains(FileSystemRights.AppendData, rule))
                                    _allowAppendData = true;
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                    _allowChangePermissions = true;
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                    _allowCreateDirectories = true;
                                if (contains(FileSystemRights.CreateFiles, rule))
                                    _allowCreateFiles = true;
                                if (contains(FileSystemRights.Delete, rule))
                                    _allowDelete = true;
                                if (contains(FileSystemRights.
                                    DeleteSubdirectoriesAndFiles, rule))
                                    _allowDeleteSubdirectoriesAndFiles = true;
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                    _allowExecuteFile = true;
                                if (contains(FileSystemRights.FullControl, rule))
                                    _allowFullControl = true;
                                if (contains(FileSystemRights.ListDirectory, rule))
                                    _allowListDirectory = true;
                                if (contains(FileSystemRights.Modify, rule))
                                    _allowModify = true;
                                if (contains(FileSystemRights.Read, rule))
                                    _allowRead = true;
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                    _allowReadAndExecute = true;
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                    _allowReadAttributes = true;
                                if (contains(FileSystemRights.ReadData, rule))
                                    _allowReadData = true;
                                if (contains(FileSystemRights.
                                    ReadExtendedAttributes, rule))
                                    _allowReadExtendedAttributes = true;
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                    _allowReadPermissions = true;
                                if (contains(FileSystemRights.Synchronize, rule))
                                    _allowSynchronize = true;
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                    _allowTakeOwnership = true;
                                if (contains(FileSystemRights.Traverse, rule))
                                    _allowTraverse = true;
                                if (contains(FileSystemRights.Write, rule))
                                    _allowWrite = true;
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                    _allowWriteAttributes = true;
                                if (contains(FileSystemRights.WriteData, rule))
                                    _allowWriteData = true;
                                if (contains(FileSystemRights.WriteExtendedAttributes,
                                    rule))_allowWriteExtendedAttributes = true;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                //Deal with IO exceptions if you want
                throw e;
            }
        }

        /// <summary>
        /// Simply displays all allowed rights
        ///
        /// Useful if say you want to test for write access and find
        /// it is false;
        /// <xmp>
        /// UserFileAccessRights rights = new UserFileAccessRights(txtLogPath.Text);
        /// System.IO.FileInfo fi = new System.IO.FileInfo(txtLogPath.Text);
        /// if (rights.canWrite() && rights.canRead()) {
        ///     lblLogMsg.Text = "R/W access";
        /// } else {
        ///     if (rights.canWrite()) {
        ///        lblLogMsg.Text = "Only Write access";
        ///     } else if (rights.canRead()) {
        ///         lblLogMsg.Text = "Only Read access";
        ///     } else {
        ///         lblLogMsg.CssClass = "error";
        ///         lblLogMsg.Text = rights.ToString()
        ///     }
        /// }
        ///
        /// </xmp>
        ///
        /// </summary>
        /// <returns></returns>
        public override String ToString() {
            string str = "";
       
            if (canAppendData()) {if(!String.IsNullOrEmpty(str)) str+=
                ",";str+="AppendData";}
            if (canChangePermissions()) {if(!String.IsNullOrEmpty(str)) str+=
                ",";str+="ChangePermissions";}
            if (canCreateDirectories()) {if(!String.IsNullOrEmpty(str)) str+=
                ",";str+="CreateDirectories";}
            if (canCreateFiles()) {if(!String.IsNullOrEmpty(str)) str+=
                ",";str+="CreateFiles";}
            if (canDelete()) {if(!String.IsNullOrEmpty(str)) str+=
                ",";str+="Delete";}
            if (canDeleteSubdirectoriesAndFiles()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "DeleteSubdirectoriesAndFiles"; }
            if (canExecuteFile()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ExecuteFile"; }
            if (canFullControl()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "FullControl"; }
            if (canListDirectory()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ListDirectory"; }
            if (canModify()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "Modify"; }
            if (canRead()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "Read"; }
            if (canReadAndExecute()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ReadAndExecute"; }
            if (canReadAttributes()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ReadAttributes"; }
            if (canReadData()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ReadData"; }
            if (canReadExtendedAttributes()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ReadExtendedAttributes"; }
            if (canReadPermissions()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "ReadPermissions"; }
            if (canSynchronize()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "Synchronize"; }
            if (canTakeOwnership()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "TakeOwnership"; }
            if (canTraverse()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "Traverse"; }
            if (canWrite()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "Write"; }
            if (canWriteAttributes()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "WriteAttributes"; }
            if (canWriteData()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "WriteData"; }
            if (canWriteExtendedAttributes()) { if (!String.IsNullOrEmpty(str))
                str += ","; str += "WriteExtendedAttributes"; }
            if (String.IsNullOrEmpty(str))
                str = "None";
            return str;
        }

        /// <summary>
        /// Convenience method to test if the right exists within the given rights
        /// </summary>
        /// <param name="right"></param>
        /// <param name="rule"></param>
        /// <returns></returns>
        public bool contains(System.Security.AccessControl.FileSystemRights right,
            System.Security.AccessControl.FileSystemAccessRule rule ) {
            return (((int)right & (int)rule.FileSystemRights) == (int)right);
        }   
    }
}