I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/
i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.
Code here
<pre><code>
protected void Button2_Click(object sender, EventArgs e){
string ver = "0001";
string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string amount = "1000";
string refer = "2432324";
string message = "hi";
string language = "FI";
string returnurl = "domain.com/return.aspx";
string cancelurl = "domain.com/cancel.aspx";
string reject = "2";
string delaye = "";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "3";
string delivery_date = "20171207";
string firstname = "Tarun";
string family = "Parmar";
string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
string postcode = "33100";
string postoffice = "Tampere";
string MERCHANT="375917";
string SECRET_KEY= "SAIPPUAKAUPPIAS";
string macnew = encryptionMD5(ver, stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();
string email = "support#checkout.fi";
string phone = "0800552010";
string status = "1";
string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);
NameValueCollection collections = new NameValueCollection();
collections.Add("VERSION", ver);
collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
collections.Add("AMOUNT", amount);
collections.Add("REFERENCE", refer);
collections.Add("MESSAGE", message);
collections.Add("LANGUAGE", language);
collections.Add("RETURN", "domain.com/return.aspx");
collections.Add("CANCEL", "domain.com/cancel.aspx");
collections.Add("REJECT", reject);
collections.Add("DELAYED", delaye);
collections.Add("COUNTRY", country);
collections.Add("CURRENCY", currency);
collections.Add("DEVICE", device);
collections.Add("CONTENT", content);
collections.Add("TYPE", type);
collections.Add("ALGORITHM", algorithms);
collections.Add("DELIVERY_DATE", delivery_date);
collections.Add("FIRSTNAME", firstname);
collections.Add("FAMILYNAME", family);
collections.Add("ADDRESS",address);
collections.Add("POSTCODE", postcode);
collections.Add("POSTOFFIC", postoffice);
collections.Add("MAC", macnew);
collections.Add("EMAIL", email);
collections.Add("PHONE", phone);
collections.Add("MERCHANT",MERCHANT);
collections.Add("SECRET_KEY", SECRET_KEY);
string remoteUrl = "https://payment.checkout.fi";
string html = "<html><head>";
html += "</head><body onload='document.forms[0].submit()'>";
html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
foreach (string key in collections.Keys)
{
html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
}
html += "</form></body></html>";
Response.Clear();
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.Charset = "ISO-8859-1";
Response.Write(html);
Response.End();
}
Function For encryptionMD5
public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
{
string passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encrypt;
UTF8Encoding encode = new UTF8Encoding();
encrypt = md5.ComputeHash(encode.GetBytes(passwords));
StringBuilder encryptdata = new StringBuilder();
for (int i= 0; i<encrypt.Length; i++) {
encryptdata.Append(encrypt[i].ToString());
}
return encryptdata.ToString();
}
Function For GetHashSha256
<pre><code>
public string GetHashSha256(string VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)
{
string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
byte[] bytes = Encoding.ASCII.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
This above code give below error
Creating a Payment Transaction failed (-24).
Error in field: MAC
Thanks in Advance if anybody help in solving this problem.
Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.
Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.
Below is the correct implementation that I have done for you:
string ver = "0001";
string stamp = "kpjkq1510841290161";
string amount = "1490";
string refer = "12345";
string message = "My custom message";
string language = "FI";
string returnurl = "http://localhost/success";
string cancelurl = "http://localhost/cancel";
string reject = "http://localhost/rejected";
string delaye = "http://localhost/delayed";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "2";
string delivery_date = "20171123";
string firstname = "Tero";
string family = "Testaaja";
string address = "Mystreet 1";
string postcode = "12345";
string postoffice = "Tampere";
string MERCHANT = "375917";
string SECRET_KEY = "SAIPPUAKAUPPIAS";
using (MD5 md5Hash = MD5.Create())
{
string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
string macnew = GetMd5Hash(md5Hash, fromValue);
}
public string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
Output is c84e068fcab5c4dad93a29dd4c567b7f
Verified from finland checkout java github project.
And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.
I want to get data from database and show it in CSV file. Following is my code for getting data from db.
public ActionResult GetTNStateUnemploymentReport(int quarter, int year, int payrollState, long? fromClientId, long? toClientId, string fromClient, string toClient)
{
//if (fromClient == "" && toClient == "")
//{
// fromClientId = 0;
// toClientId = 0;
//}
string quarterMonths = "";
if (quarter == 1)
quarterMonths = "Jan, Feb, Mar";
else if (quarter == 2)
quarterMonths = "Apr, May, Jun";
else if (quarter == 3)
quarterMonths = "Jul, Aug, Sep";
else if (quarter == 4)
quarterMonths = "Oct, Nov, Dec";
var modelList = new PayrollHelper().GetTNStateUnemploymentReport(quarter, year, fromClientId ?? 0, toClientId ?? 0);
var csv = new System.Text.StringBuilder();
foreach (var model in modelList)
{
csv.Append(string.Format("{0}{1}", model.StringData, Environment.NewLine));
}
return new CSVResult
{
FileName = "TN_" + quarterMonths + "_" + year.ToString() + ".csv",
Content = csv.ToString()
};
Following is my CSVResult class which I am using to create the CSV File.
public class CSVResult: ActionResult
{
public string FileName { get; set; }
public string Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Buffer = true;
context.HttpContext.Response.Clear();
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.ContentType = "application/csv;charset=utf-8";
context.HttpContext.Response.Write(Content);
context.HttpContext.Response.End();
}
}
I am getting the following error:
LOCAL HOST SENT INVALID RESPONSE
ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION.
I have another report which creates CSV file using above mentioned ExecuteResult method and is working fine, but the current one is not.
Based on your code "TN_" + quarterMonths + "_" + year.ToString() + ".csv" a file name would look like this
"TN_Jul, Aug, Sep_2016.csv"
which, based on .AddHeader("content-disposition", "attachment; filename=" + FileName) would result in a content disposition that looks like this
"Content-Disposition: attachment; filename=TN_Jul, Aug, Sep_2016.csv"
The commas and spaces in the filename when generating the content disposition will cause issues with some browsers.
Now there are a few ways to fix this.
1) You could change the way you generate the filename to replace spaces and commas (,) with underscores (_)
for example instead of
quarterMonths = "Jan, Feb, Mar";
change them to
quarterMonths = "Jan_Feb_Mar";
resulting in a filename that looks like
"TN_Jul_Aug_Sep_2016.csv"
2) You could also make sure to enclose the filename in "" (double quotes)
So instead of
.AddHeader("content-disposition", "attachment; filename=" + FileName)
change it to
.AddHeader("content-disposition", "attachment; filename=\"" + FileName + "\"");
or
.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", FileName));
UPDATE:
Using ideas from the source code for System.Web.Mvc.FileResult You could rewrite your CsvResult to allow for the suggested changes I mentioned above.
public class CsvResult : ActionResult {
private const string CONTENT_TYPE = "application/csv;charset=utf-8";
private string filename;
public CsvResult() {
System.Net.Http.Headers.MediaTypeHeaderValue headerValue = null;
if (System.Net.Http.Headers.MediaTypeHeaderValue.TryParse(CONTENT_TYPE, out headerValue)) {
ContentType = headerValue.ToString();
}
}
public string ContentType { get; private set; }
public string FileName {
get { return filename ?? String.Empty; }
set { filename = value; }
}
public string Content { get; set; }
public override void ExecuteResult(ControllerContext context) {
HttpResponseBase response = null;
if (context != null
&& context.HttpContext != null
&& ((response = context.HttpContext.Response) != null)) {
response.Buffer = true;
response.Clear();
response.ContentType = ContentType;
if (!String.IsNullOrWhiteSpace(FileName)) {
string headerValue = ContentDispositionUtil.GetHeaderValue(FileName);
response.AppendHeader("Content-Disposition", headerValue);
}
response.Write(Content);
response.End();
}
}
internal static class ContentDispositionUtil {
public static string GetHeaderValue(string filename) {
System.Net.Http.Headers.ContentDispositionHeaderValue contentDisposition = null;
string headerValue = String.Format("attachment; filename=\"{0}\"", filename);
if (System.Net.Http.Headers.ContentDispositionHeaderValue.TryParse(headerValue, out contentDisposition)) {
var result = contentDisposition.ToString();
return result;
} else {
throw new ArgumentException("Content Disposition Header Value not well formatted - " + headerValue, "FileName");
}
}
}
}
Why not use standard result deriving from FileResult instead?
FileResult Class
One of the 3 concrete classes should do what you want. If you write your own ActionResult then it is up to you to write correct code.
currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.
In WCF (System.Net.WebHeaderCollection) a header value can be retreived using either the System.Net.HttpRequestHeader enum or a header string:
WebOperationContext.Current.IncomingRequest.Headers[httpRequestHeaderEnum]
// or
WebOperationContext.Current.IncomingRequest.Headers.Get(rawHeaderString)
But in ASP.NET, the headers are in a NameValueCollection which only accepts a header string:
HttpContext.Current.Request.Headers[rawHeaderString]
In order to use the Enum's for ASP.NET, where is the map from enum System.Net.HttpRequestHeader to its header string?
How about writing a mapping method? For reference:
HttpRequestHeader enumeration
You could just make a mapping table, or Using code swiped from Binary Worrier's post, you could do something like this:
public static string TranslateToHttpHeaderName(HttpRequestHeader enumToTranslate)
{
const string httpHeaderNameSeparator = "-";
string enumName = enumToTranslate.ToString();
var stringBuilder = new StringBuilder();
// skip first letter
stringBuilder.Append(enumName[0]);
for (int i = 1; i < enumName.Length; i++)
{
if (char.IsUpper(enumName[i])) stringBuilder.Append(httpHeaderNameSeparator);
stringBuilder.Append(enumName[i]);
}
// Cover special case for 2 character enum name "Te" to "TE" header case.
string headerName = stringBuilder.ToString();
if (headerName.Length == 2) headerName = headerName.ToUpper();
return headerName;
}
You can use a default implementation, using a WebHeaderCollection
private static readonly ConcurrentDictionary<HttpRequestHeader, string> ToStringKeyCache = new ConcurrentDictionary<HttpRequestHeader, string>();
public static string ToStringKey(this HttpRequestHeader enumToEvaluate)
{
var str = ToStringKeyCache.GetOrAdd(enumToEvaluate, header =>
{
var nm = new WebHeaderCollection();
nm.Set(header, "X");
return nm.AllKeys.Single();
});
return str;
}
Unless I completely misunderstood your question:
Import the System.Net namespace: using System.Net;
e.g. WebForms:
using System.Net
protected void Page_Load(object sender, EventArgs e)
{
//Single - e.g. Connection
FooLabel.Text = Request.Headers[HttpRequestHeader.Connection.ToString()] + "<hr />";
//Go through all
foreach (var en in Enum.GetNames(typeof(HttpRequestHeader)))
{
FooLabel.Text += en + " : " + Request.Headers[en] + "<br />";
}
}
Hth...
I'm getting results from my rawQuery that duplicate and follow an OR logic as opposed to an AND logic i.e. I will get all the entries that contain "tuxedo" as well as all the entries that contain "hotel" when I only want the ones that contain both.
This is my method:
public ArrayList<Integer> getAdvancedResultIDList(String[] search)
{
ArrayList<String> queryList = new ArrayList<String>();
ArrayList<Integer> resultsList = new ArrayList<Integer>();
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
this.mDB = GamesList.mDBHelper.getDatabase();
Cursor searchCursor = null;
try
{
//TODO:
// for each string in the search array search the whole of searchable table. Check that the results are only of the values that
// contain all the search strings, and add the id of that row to the results ArrayList
for(int i = 0; i < search.length; i++)
{
String query;
String s = '"' + search[i] + '"';
query = "SELECT " + KEY_ID + " FROM "+ SEARCHABLE_TABLE + " WHERE " + SEARCHABLE_TABLE + " MATCH " + s;
queryList.add(query);
}
String[] queryArray = queryList.toArray(new String[queryList.size()]);
String unionQuery = builder.buildUnionQuery(queryArray, KEY_ID + " ASC", null);
searchCursor = this.mDB.rawQuery(unionQuery, null);
int colId = searchCursor.getColumnIndex(KEY_ID);
String resultID;
for(searchCursor.moveToFirst(); !searchCursor.isAfterLast();searchCursor.moveToNext())
{
resultID = searchCursor.getString(colId);
Integer Id = Integer.parseInt(searchCursor.getString(colId));
resultsList.add(Id);
}
searchCursor.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
this.mDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
return resultsList;
}
Thanks in advance and Happy New Year!
The documentation explains how to use multiple search terms:
SELECT id FROM searchTable WHERE searchTable MATCH 'tuxedo hotel'