How to integrate citrus Payment gateway Enquiry API code in Asp.net - asp.net

I have implemented Citrus Payment gatway request/Response pages I am struck with Enquiry API integration,Where i have to implement it in code ?what is the page name i have to give ?
this is the guide given to me by citrus to implement enquiry api ..
http://developers.citruspay.com/api/miscellaneous/Enquiry.html#/
Request.aspx page code -
{
string formPostUrl = "https://sandbox.citruspay.com/sslperf/xyzdoman";
string secret_key = "xxxxxxxxxxxxxxx";
//Need to change with your Vanity URL Key from the citrus panel
string vanityUrl = "xxxxxyy";
//Should be unique for every transaction
string merchantTxnId = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
//Need to change with your Order Amount
string orderAmount = "10";
string currency = "INR";
string data = vanityUrl + orderAmount + merchantTxnId + currency;
//Need to change with your Return URL
string returnURL = "http://www.xxxxxyy.com/Response.aspx";
//Need to change with your Notify URL
string notifyUrl = "http://www.xxxxxyy.com/Response.aspx";
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string securitySignature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
%>
Response.aspx page code
{
string secret_key = "xxxxxxxxxxxxxxxxxxxxx";
string data="";
string txnId=Request["TxId"];
string txnStatus=Request["TxStatus"];
string amount=Request["amount"];
string pgTxnId=Request["pgTxnNo"];
string issuerRefNo=Request["issuerRefNo"];
string authIdCode=Request["authIdCode"];
string firstName=Request["firstName"];
string lastName=Request["lastName"];
string pgRespCode=Request["pgRespCode"];
string zipCode=Request["addressZip"];
string resSignature=Request["signature"];
bool flag = true;
if (txnId != null) {
data += txnId;
}
if (txnStatus != null) {
data += txnStatus;
}
if (amount != null) {
data += amount;
}
if (pgTxnId != null) {
data += pgTxnId;
}
if (issuerRefNo != null) {
data += issuerRefNo;
}
if (authIdCode != null) {
data += authIdCode;
}
if (firstName != null) {
data += firstName;
}
if (lastName != null) {
data += lastName;
}
if (pgRespCode != null) {
data += pgRespCode;
}
if (zipCode != null) {
data += zipCode;
}
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
if(resSignature !=null && !signature.Equals(resSignature)) {
flag = false;
}
if (flag) {
%>
Your Unique Transaction/Order Id : <%=txnId%><br/>
Transaction Status : <%=txnStatus%><br/>
<% } else { %>
<label width="125px;">Citrus Response Signature and Our (Merchant) Signature Mis-Mactch</label>
<% } %>

Related

How to send image file along with other parameter in asp.net?

I want to send image files to SQL Server using C#.
The below code is working and saving files and their paths into the database. I need the same data in my API endpoint's response. I've created a custom response class, called RegistrationResponse.
I'm beginner in this so I'm looking for help.
public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
{
object data = "";
NameValueCollection col = HttpContext.Current.Request.Form;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
//read file data
foreach (MultipartFileData dataItem in provider.FileData)
{
try
{
string description = string.Empty;
string userId = string.Empty;
String fileName = string.Empty;
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.ToString().ToLower() == "userid")
{
userId = val;
}
else if (key.ToString().ToLower() == "description")
{
description = val;
}
}
}
String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
fileName = userId + Path.GetExtension(name);
File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));
using (var db = new AlumniDBEntities())
{
//saving path and data in database table
Post userPost = new Post();
userPost.Files = fileName;
userPost.Description = description;
userPost.UserID = Convert.ToInt32(userId);
userPost.CreatedDate = DateTime.Now;
db.Posts.Add(userPost);
db.SaveChanges();
data = db.Posts.Where(x => x.PostID ==
userPost.PostID).FirstOrDefault();
string output = JsonConvert.SerializeObject(data);
}
}
catch (Exception ex)
{
return Request.CreateResponse(ex);
}
}
return Request.CreateResponse(HttpStatusCode.Created);
});
var response = new RegistrationResponse
{
success = true,
status = HttpStatusCode.OK,
message = "Success",
data = data
};
return response;
}

Sending email on the loop Per Customer ASP.NET MVC

I have the following code that loops around and is supposed to send a single email per requested order list. So it sends multiple separated order emails for each customer rather than just the one email order list.
public ActionResult SaveOrder(string name, Order[] order)
{
string result = "Error! Order Is Not Complete!";
if (name != null && address != null && email != null && order != null)
{
var cutomerId = Guid.NewGuid();
Customer model = new Customer();
model.CustomerId = cutomerId;
model.Name = name;
model.Address = address;
model.OrderDate = DateTime.Now;
model.Email = email;
db.Customers.Add(model);
foreach (var item in order)
{
var orderId = Guid.NewGuid();
Order O = new Order();
O.OrderId = orderId;
O.ProductName = item.ProductName;
O.Quantity = item.Quantity;
O.Price = item.Price;
O.Amount = item.Amount;
O.CustomerId = cutomerId;
db.Orders.Add(O);
var customername = model.Name;
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
}
db.SaveChanges()
result = "Success! Order Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
[NonAction]
public void SendVerificationLinkEmail(string email, string name, string productname)
{
var fromEmail = new MailAddress("test#test.com", "Laundry");
var toEmail = new MailAddress(email);
var fromEmailPassword = "xxxxx"; // Replace with actual password
string subject = "Your " + productname + " order request has been scheduled ";
string body = "";
using (StreamReader reader = new StreamReader(Server.MapPath("~/HtmlPage1.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{name}", name);
body = body.Replace("{emailID}", email);
body = body.Replace("{productname}", productname);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
Changing this:
foreach (var item in order)
{
var orderId = Guid.NewGuid();
... // code removed for clarity
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
}
to this: (take the if statement out of the foreach loop)
foreach (var item in order)
{
var orderId = Guid.NewGuid();
... // code removed for clarity
}
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
will send one email per customer order, instead of one email per order item. (Although you're passing o.ProductName to the SendVerificationLinkEmail method, so the email will presumably only contain the last ProductName since that appears to be different for each line item.)

'Invalid cast from 'System.DateTime' to 'System.TimeSpan'.'

I'm using a stored procedure to import an Excel data into SQL Server in an ASP.NET MVC application. The problem is when I run the application and upload the file, I got the above error and the cursor point on foreach (var a in empDetails).
This is my controller:
public ActionResult ExcelUpload()
{
return View();
}
[HttpPost]
public ActionResult UploadExcel(Réception_camions objEmpDetail, HttpPostedFileBase FileUpload)
{
Réception_phosphateEntities objEntity = new Réception_phosphateEntities();
string data = "";
if (FileUpload != null)
{
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
if (filename.EndsWith(".xlsx"))
{
string targetpath = Server.MapPath("~/DetailFormatInExcel/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var empDetails = from a in excelFile.Worksheet<Réception_camions>(sheetName) select a;
// The error occurs in this line:
// Invalid cast from 'System.DateTime' to 'System.TimeSpan'
foreach (var a in empDetails)
{
if (a.Date_d_arrivée != null )
{
DateTime Date_d_arrivée = (a.Date_d_arrivée);
int Id_qualité = Convert.ToInt32(a.Id_qualité);
int result = PostExcelData(a.Date_d_arrivée, a.heure_d_arrivée, a.Poids_cam,/* myBirthdate,*/ a.Id_cam, a.Id_qualité /*a.PostelCode, a.EmailId*/);
if (result <= 0)
{
data = "Hello User, Found some duplicate values! Only unique employee number has inserted and duplicate values(s) are not inserted";
ViewBag.Message = data;
continue;
}
else
{
data = "Successful upload records";
ViewBag.Message = data;
}
}
else
{
data = a.Date_d_arrivée + "Some fields are null, Please check your excel sheet";
ViewBag.Message = data;
return View("ExcelUpload");
}
}
}
else
{
data = "This file is not valid format";
ViewBag.Message = data;
}
return View("ExcelUpload");
}
else
{
data = "Only Excel file format is allowed";
ViewBag.Message = data;
return View("ExcelUpload");
}
}
else
{
if (FileUpload == null)
{
data = "Please choose Excel file";
}
ViewBag.Message = data;
return View("ExcelUpload");
}
}
public int PostExcelData(DateTime Date_d_arrivée, TimeSpan heure_d_arrivée, Decimal Poids_cam, int Id_cam, int Id_qualité)
{
Réception_phosphateEntities DbEntity = new Réception_phosphateEntities();
var InsertExcelData = DbEntity.usp_InsertNewEmployeeDetails(Date_d_arrivée, heure_d_arrivée, Poids_cam, Id_cam, Id_qualité );
return InsertExcelData;
}
And this is my stored procedure for the table Réception_camions:
ALTER PROCEDURE [dbo].[usp_InsertNewEmployeeDetails]
(#Date_d_arrivée DATETIME = NULL,
#heure_d_arrivée TIME(7) = NULL,
#Poids_cam DECIMAL(18, 2) = null,
#Id_cam INT = NULL,
#Id_qualité INT = NULL)
AS
BEGIN
INSERT INTO Réception_camions([Date d'arrivée], [heure d'arrivée], Poids_cam,
Id_cam, Id_qualité)
VALUES (#Date_d_arrivée, #heure_d_arrivée, #Poids_cam,
#Id_cam, #Id_qualité)
END
I'm blocked please if someone can help me.

MVC Action not returning csv file. ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION

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.

ASP.NET website hacked -> login problem

I have a problem with my ASP.NET website, it got hacked. One hacker found a bug in my login system and he can login with every account he wants, even if the account is normal user, moderator or administrator. He can delete everything he wants.
Please can anyone help me, tell me if there is any vulnerable function or something
P.S. I'm not myself an ASP.NET programmer, I know only PHP, so please tell me exactly what I need to edit in the code, because I don't know ASP.NET at all.
ThanksAS
public void loginButton_Click(object sender, EventArgs e)
{
string username = nicknameTextBox.Text;
string password = passwordTextBox.Text;
string returnUrl = Request.QueryString["returnUrl"];
if (returnUrl == null) returnUrl = Convert.ToBase64String(Encoding.ASCII.GetBytes(Request.Url.ToString()));
string message = CurrentPlayer.LoginRequest(username, password, returnUrl);
if(message != null)
Response.Redirect("AccountLogin.aspx?returnUrl=" + returnUrl);
}
LoginRequest:
public static string LoginRequest(string username, string password, string returnUrl)
{
Player player = null;
string message = InputValidator.CheckLoginRequest(username, password, out player);
if (message != null) return message;
message = LoginCookie.CheckLoginRequest(player);
if (message != null) return message;
SessionPlayer sessionPlayer = new SessionPlayer(
player.ID, player.ActivationGuid, (PlayerRole)player.IdRole,
player.Nickname, player.CreationDate);
SessionMessages sessionMessages = new SessionMessages(player.ID);
SessionOwnedCounts ownedCounts = new SessionOwnedCounts(player.ID);
SessionGuestCounts guestCounts = new SessionGuestCounts(player.ID);
SessionMatchCounts matchCounts = new SessionMatchCounts(player.ID);
CurrentPlayer.Login(sessionPlayer, sessionMessages, ownedCounts, guestCounts, matchCounts);
Player.UpdateLastLogin(player.ID);
returnUrl = Encoding.ASCII.GetString(Convert.FromBase64String(returnUrl));
HttpContext.Current.Response.Redirect(returnUrl);
return null;
}[/code]
Login:
private static void Login(SessionPlayer player, SessionMessages messages, SessionOwnedCounts ownedCounts, SessionGuestCounts guestCounts, SessionMatchCounts matchCounts)
{
HttpContext.Current.Session["player"] = player;
HttpContext.Current.Session["messages"] = messages;
HttpContext.Current.Session["ownedCounts"] = ownedCounts;
HttpContext.Current.Session["guestCounts"] = guestCounts;
HttpContext.Current.Session["matchCounts"] = matchCounts;
if (LoginCookie.Exists() == false)
LoginCookie.AddForFirstTime(player.Nickname, player.Guid);
else
LoginCookie.SetToLoginAction();
}
And checkloginrequest:
public static string CheckLoginRequest(string username, string password, out Player player)
{
player = null;
object lastLoginTryDateObj = HttpContext.Current.Session["lastLoginTryDate"];
if (lastLoginTryDateObj == null)
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
else
{
DateTime lastLoginTryDate = (DateTime)HttpContext.Current.Session["lastLoginTryDate"];
int lastLoginTryCount = (int)HttpContext.Current.Session["lastLoginTryCount"];
TimeSpan ts = DateTime.Now - lastLoginTryDate;
if (ts.TotalSeconds < 60)
{
if (lastLoginTryCount >= Settings.AllowedLoginTriesPerMinute)
{
return "Ai depasit numarul maxim de incercari pe minut .<br/>Vino inapoi dupa " + (60 - (int)ts.TotalSeconds).ToString() + " secunde.";
}
else
{
HttpContext.Current.Session["lastLoginTryCount"] = lastLoginTryCount + 1;
}
}
else
{
HttpContext.Current.Session["lastLoginTryDate"] = DateTime.Now;
HttpContext.Current.Session["lastLoginTryCount"] = 1;
}
}
player = Player.GetPlayer(username, password);
if (player == null)
{
return "Usernameul si parola nu se potrivesc.";
}
if (player != null && player.IsActive == false)
{
return "Contul a fost creat dar nu e activat.<br/> Verifica mailul " + player.Email + " si activeaza-ti contul.";
}
PlayerSuspended ps = BLL.PlayerSuspended.SuspendedGet(player.ID);
if (ps != null)
{
return "Contul tau e suspendat pana in data de " + ps.SuspendedEndDate.ToString("dd-MM-yyyy") + ".<br/>Motivul: " + ps.SuspendedReason;
}
return null;
}
GetPlayer:
public static Player GetPlayer(string nickname, string password)
{
Player player = null;
object[] values = DAL.Player.GetPlayer(nickname, password);
if (values != null)
{
player = new Player();
player.SetFromValues(values);
}
return player;
}
DAL.Player.GetPlayer:
public static object[] GetPlayer(string nickname, string password)
{
password = Convert.ToBase64String(Encoding.ASCII.GetBytes(password));
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("#Nickname", nickname));
sqlParams.Add(new SqlParameter("#Password", password));
return DataBase.GetFirstRow("[spPlayer.Get]", sqlParams);
}
Your site is vulnerable to session fixation
Why are you not using asp.net forms authentication and membership?

Resources