Check against an Entire list to validate user information - c#

I'm just not getting this.
So I have a list from my API
Of Customers called a
I need to validate weather the fields correlate to any of the 100+ Logins that I'm suppose to receive from the Resposne
How I'm Going about it At the moment
foreach (var c in Users.a)
{
if (Email == c.email && Password == c.password)
{
await App.Current.MainPage.DisplayAlert("Login Success", "", "Ok");
Application.Current.Properties["Email"] = c.email;
Application.Current.Properties["Userid"] = c.id;
Users.Loggedin = true;
await Application.Current.SavePropertiesAsync();
await App.Current.MainPage.Navigation.PushAsync(new Home(c.email));
}
else
{
await App.Current.MainPage.DisplayAlert("Login Fail", "Please enter correct Email and Password", "OK");
}
}
Am I doing this wrong? Is there a better way of doing this.
The Call
RestAPI rest = new RestAPI("http://Site/wp-json/wc/v3/",
"ck_a25f******************dcd0",
"cs_8f247c22************05c");
WCObject wc = new WCObject(rest);
var x = await wc.Customer.GetAll();
Users.a = x;

I Came to the Conclusion that my best way forward with this was to Fetch => Add => Combine Until My list was empty.
RestAPI rest = new RestAPI("http://Yoursite/wp-json/wc/v3/", "Customer Key", "Customer Secret");
WCObject wc = new WCObject(rest);
int pageNum = 1;
var isNull = false;
List<Customer> oldlist;
while (!isNull)
{
var page = pageNum.ToString();
x = await wc.Customer.GetAll(new Dictionary<string, string>() {
{
"page", page
}, {
"per_page", "100"
}
});
oldlist = FetchCustomers.customers ?? new List<Customer>();
if (x.Count == 0) {
break;
}
else
{
pageNum++;
FetchCustomers.customers = oldlist.Union(x).ToList();
}
}
How i'm Validating
var list = FetchCustomers.customers.ToList();
foreach (var user in list)
{
if (user.username == Usernamelabel.Text)
{
Application.Current.Properties["CId"] = user.id;
Application.Current.Properties["CEmail"] = user.email;
Application.Current.Properties["CUsername"] = user.username;
Users.Loggedin = true;
Application.Current.SavePropertiesAsync();
App.Current.MainPage.DisplayAlert("Empty Values", "Phase 2 Done your logged in ", "OK");
}
}
User is Validated From username I'm busy with another Process to Validate the user by The Wordpress API and getting a JWT token then Sending it to this Method to validate and Fetch the Customer and then Persisting the User.
Here's that Extra Method I mentioned
var client = new WordPressClient("http://Youtsite/wp-json/");
client.AuthMethod = AuthMethod.JWT;
await client.RequestJWToken(USername, Password);
var x = client;
var isValidToken = await client.IsValidJWToken();
WpApiCredentials.token = client.GetToken();
if (isValidToken)
{
Login_Phase2();
}
else
{
await App.Current.MainPage.DisplayAlert("Empty Values", "Token not Found", "OK");
}
#endregion

Related

Chain Email Display Broken by Updating Subject Exchange Online Service in C#

I have read emails from exchnage online and in convesation emails i want to show only last email from its chain messages i have successfully doing that but in desktop outlook application i changed the subject then the Convesation chain mail is not working properly and chain is broken.
First I Have Group by ConvesationId.Then In-reply-to check for mail is convesation email or not.If Convesation email then find it in other way and simple mail then find it another way
It's ConvesationId And ConvesationIndex also changed.
public async Task<IActionResult> TrackEmail()
{
var cca = ConfidentialClientApplicationBuilder
.Create(Clientid)
.WithClientSecret(Clientsecret)
.WithTenantId(Tenantid)
.Build();
var scopes = new string[] { $"{_emailConfiguration.ScopeUrl}" };
var aquireToken = await cca.AcquireTokenForClient(scopes).ExecuteAsync();
aquireToken.ExpiresOn.UtcDateTime.AddMinutes(-5);
ExchangeService ewsClient = new(ExchangeVersion.Exchange2013_SP1);
ewsClient.Url = new Uri($"{_emailConfiguration.ExchangeUrl}");
ewsClient.Credentials = new OAuthCredentials(aquireToken.AccessToken);
ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, $"{email}");
ewsClient.TraceEnabled = false;
ewsClient.TraceFlags = TraceFlags.None;
ewsClient.Timeout = 9000000;
if (ewsClient != null)
{
List<ProjectsDataModel>? projectsDataModel = (from p in _db.Projects
where p.Userid== userId
select new ProjectsDataModel
{
Id = p.Id,
ProjectName = p.Projectname,
ProjectDomain = p.Projectdomain,
CreatedDate = p.Createddate
}).ToList();
if (projectsDataModel != null)
{
foreach (var projectData in projectsDataModel)
{
EmailAddress sender = new(projectData.ProjectDomain);
ItemView view = new ItemView(int.MaxValue);
//SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(EmailMessageSchema.Sender, sender);
ExtendedPropertyDefinition PidTagSenderSmtpAddress = new(0x5D01, MapiPropertyType.String);
SearchFilter sf = new SearchFilter.ContainsSubstring(PidTagSenderSmtpAddress, $"{projectData.ProjectDomain}");
var folderItems = ewsClient.FindItems(WellKnownFolderName.Inbox, sf, view);
var conversationItems = from element in folderItems
group element by element.ConversationId
into groups
select groups.OrderByDescending(p => p.DateTimeReceived).FirstOrDefault();
foreach (Item item in conversationItems)
{
EmailMessage messageToCheck = EmailMessage.Bind(ewsClient, item.Id);
if (messageToCheck.InReplyTo != null) //Chain Email or not
{
PropertySet properties = new(BasePropertySet.FirstClassProperties);
// Identify the folders to ignore.
Collection<FolderId> foldersToIgnore = new Collection<FolderId>()
{ WellKnownFolderName.DeletedItems, WellKnownFolderName.Drafts };
// Request the conversation items.
ConversationResponse convesationResponse = ewsClient.GetConversationItems(messageToCheck.ConversationId,
properties,
null,
foldersToIgnore,
ConversationSortOrder.TreeOrderDescending);
//foreach (ConversationNode node in convesationResponse.ConversationNodes)
//{
// // Process each item in the conversation node.
// foreach (Item chainItem in node.Items)
// {
var chainItem = convesationResponse.ConversationNodes.FirstOrDefault()?.Items.FirstOrDefault();
if (chainItem != null)
{
List<EmailInfo> emailInfosList = projectData.EmailInfos.Where(p => p.ConversationId == chainItem.ConversationId).ToList();
if (emailInfosList == null || emailInfosList.Count == 0)
{
EmailMessage chainMessage = EmailMessage.Bind(ewsClient, chainItem.Id);
EmailInfo emailInfo = new();
emailInfo.Subject = chainMessage.Subject;
emailInfo.From = chainMessage.From.ToString();
emailInfo.Body = chainMessage.Body.ToString();
emailInfo.DateTimeCreated = chainMessage.DateTimeCreated;
emailInfo.DateTimeSent = chainMessage.DateTimeSent;
emailInfo.DateTimeReceived = chainMessage.DateTimeReceived;
emailInfo.ConversationId = chainMessage.ConversationId;
projectData.EmailInfos.Add(emailInfo);
}
}
// }
//}
}
else
{
List<EmailInfo> emailInfosList = projectData.EmailInfos.Where(p => p.ConversationId == messageToCheck.ConversationId).ToList();
if (emailInfosList == null || emailInfosList.Count == 0)
{
EmailInfo emailInfo = new();
emailInfo.Subject = messageToCheck.Subject;
emailInfo.From = messageToCheck.From.ToString();
emailInfo.Body = messageToCheck.Body.ToString();
emailInfo.DateTimeCreated = messageToCheck.DateTimeCreated;
emailInfo.DateTimeSent = messageToCheck.DateTimeSent;
emailInfo.DateTimeReceived = messageToCheck.DateTimeReceived;
emailInfo.ConversationId = messageToCheck.ConversationId;
projectData.EmailInfos.Add(emailInfo);
}
}
}
response.Data = projectsDataModel;
}
}
else
{
response.StatusCode = (int)HttpStatusCode.NotFound;
response.Message = ATEmailClientLibrary.Models.ResponseMessage.NoRecordFound;
}
}
else
{
response.StatusCode = (int)HttpStatusCode.NotFound;
response.Message = ATEmailClientLibrary.Models.ResponseMessage.NoRecordFound;
}
}
Why this email chain is broken i want to get only last email from this chain email messages but don't know how to do when subject change then this chain message broken

Sign in with Apple in .Net MAUI

I am currently working on an dotnet maui app and I need to integrate Sign in With Apple. But when I click the sign in button, It shows "invalid_request invalid web redirect url"
Tried solutions
I tried the solutions available here, but it is not working.
Other than that I have also read the documentation, also got help from tutorials such as this, this and this
Code
Initializing request:
//Initiating apple sign in request
WebAuthenticatorResult result = null;
if (scheme.Equals(Constants.apple, StringComparison.Ordinal)
&& DeviceInfo.Platform == DevicePlatform.iOS
&& DeviceInfo.Version.Major >= 13)
{
// Make sure to enable Apple Sign In in both the
// entitlements and the provisioning profile.
var options = new AppleSignInAuthenticator.Options
{
IncludeEmailScope = true,
IncludeFullNameScope = true,
};
result = await AppleSignInAuthenticator.AuthenticateAsync(options);
}
else
{
var authUrl = new Uri(Constants.authenticationUrl + scheme);
var callbackUrl = new Uri(Constants.callbackUrl);
result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);
}
AuthToken = string.Empty;
// Get Name and Email from callback url
//if (result.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
// AuthToken += $"Name: {name}{Environment.NewLine}";
//if (result.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
// AuthToken += $"Email: {email}{Environment.NewLine}";
AuthToken += result?.AccessToken ?? result?.IdToken;
AuthCredential credential = null;
Handling results:
// WebAuthenticator Endpoint - use for social login e.g. Google, Facebook, Apple etc.
const string callbackScheme = "socialloginauthenticator";
[HttpGet("{scheme}")]
public async Task Get([FromRoute] string scheme)
{
var auth = await Request.HttpContext.AuthenticateAsync(scheme);
if (!auth.Succeeded
|| auth?.Principal == null
|| !auth.Principal.Identities.Any(id => id.IsAuthenticated)
|| string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
{
// Not authenticated, challenge
await Request.HttpContext.ChallengeAsync(scheme);
}
else
{
var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
var email = string.Empty;
email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
// Get parameters to send back to the callback
var qs = new Dictionary<string, string>
{
{ "access_token", auth.Properties.GetTokenValue("access_token") },
{ "refresh_token", auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },
{ "expires_in", (auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },
{ "email", email }
};
// Build the result url
var url = callbackScheme + "://#" + string.Join(
"&",
qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
// Redirect to final url
Request.HttpContext.Response.Redirect(url);
}
}
I have resolved the issue. The issue was with redirect uri in apple service I made.
The required uri was of format "www.example.com/signin-apple" while I was following "www.example.com/path/to/endpoints"

C# MVC Allow Update Of Re-edited field

I have a form on a mvc view that contains Name, Username, email address, drop down list for branch and department. There are 2 stored procedures that is checking for duplicate Username and Email address. An error will be shown if the user clicks the update button.
Scenario 1
If the user deletes the username and enters a unique one the form will not submit because email address is still existent in the database.
How can I allow the update to continue if the user puts back the original Username
[HttpPost]
public async Task<IActionResult> Update(ApplicationUserModel model)
{
var appmodel = new ApplicationUserModel();
appmodel.UserDetails = await ClaimsService.GetApplicationUserByID(model.Users.UserID);
appmodel.Users = await ClaimsService.GetUserNameByID(model.Users.UserName);
appmodel.User = await ClaimsService.GetEmailAddressIfExists(model.Users.EmailAddress);
if (!appmodel.UserDetails.Name.Equals(model.Users.Name) || appmodel.UserDetails.BranchID != model.Users.BranchID || appmodel.UserDetails.DepartmentID != model.Users.DepartmentID )
{
if(!appmodel.UserDetails.UserName.Equals(model.Users.UserName) || !appmodel.UserDetails.EmailAddress.Equals(model.Users.EmailAddress))
{
model.UserNameErrorMessage = "Username already exists";
model.EmailAddressErrorMessage = "Email address already exists";
model.Username = appmodel.Users.UserName;
model.EmailAddress = appmodel.User.EmailAddress;
model.Users = new Model.Applications.Tables.tblUsers() { Archive_User = "0", StatusID = 1 };
model.BranchSelectList = new SelectList(await BranchServices.GetBranchByCompanyID(1), "BranchID", "BranchFullName");
model.DepartmentSelectList = new SelectList(await DepartmentService.GetAllActiveDepartments(1), "DepartmentID", "Department");
return View(model);
}
}
await ClaimsService.UpdateUserAsync(model.Users);
string redirectUrl = string.Format("/ApplicationUsers/Users");
return RedirectToAction("Message", "Home", new { type = Service.Utils.StringHelper.Types.UpdateSuccess, url = redirectUrl });
}
Compare the old value (of username alone then email) with the new value if they are the same then don't check if it exists before. if they are different then check if the new is unique
If email was 'user1#example.com' , username = 'user1'
and the he entered email = 'user1#eample.com' but username = 'user1updated'
You first check old email and new email (both are 'user1#example') then it is ok.
then check the old username with the new username (here are different) so I check the existence of new username ('user1updated') in the database if it not there I update otherwise don't update
[HttpPost]
public async Task<IActionResult> Update(ApplicationUserModel model)
{
string redirectUrl;
var appmodel = new ApplicationUserModel();
appmodel.UserDetails = await ClaimsService.GetApplicationUserByID(model.Users.UserID);
appmodel.Users = await ClaimsService.GetUserNameByID(model.Users.UserName);
appmodel.User = await ClaimsService.GetEmailAddressIfExists(model.Users.EmailAddress);
if(appmodel.UserDetails.EmailAddress == model.Users.EmailAddress || appmodel.UserDetails.UserName == model.Users.UserName)
{
if (!appmodel.UserDetails.Name.Equals(model.Users.Name) || appmodel.UserDetails.BranchID != model.Users.BranchID || appmodel.UserDetails.DepartmentID != model.Users.DepartmentID)
{
await ClaimsService.UpdateUserAsync(model.Users);
redirectUrl = string.Format("/ApplicationUsers/Users");
return RedirectToAction("Message", "Home", new { type = Service.Utils.StringHelper.Types.UpdateSuccess, url = redirectUrl });
}
else if (appmodel.UserDetails.EmailAddress != model.Users.EmailAddress || appmodel.UserDetails.UserName != model.Users.UserName)
{
if (!appmodel.UserDetails.Name.Equals(model.Users.Name) || appmodel.UserDetails.BranchID != model.Users.BranchID || appmodel.UserDetails.DepartmentID != model.Users.DepartmentID)
{
await ClaimsService.UpdateUserAsync(model.Users);
redirectUrl = string.Format("/ApplicationUsers/Users");
return RedirectToAction("Message", "Home", new { type = Service.Utils.StringHelper.Types.UpdateSuccess, url = redirectUrl });
}
if(appmodel.UserDetails.EmailAddress == model.Users.EmailAddress)
{
model.EmailAddressErrorMessage = "";
}
if(appmodel.UserDetails.EmailAddress != model.Users.EmailAddress)
{
model.EmailAddressErrorMessage = "Email address already exists";
}
if(appmodel.UserDetails.UserName == model.Users.UserName)
{
model.UserNameErrorMessage = "";
}
if (appmodel.UserDetails.UserName != model.Users.UserName)
{
model.UserNameErrorMessage = "Username already exists";
}
model.Username = appmodel.Users.UserName;
model.EmailAddress = appmodel.User.EmailAddress;
model.Users = new Model.Applications.Tables.tblUsers() { Archive_User = "0", StatusID = 1 };
model.BranchSelectList = new SelectList(await BranchServices.GetBranchByCompanyID(1), "BranchID", "BranchFullName");
model.DepartmentSelectList = new SelectList(await DepartmentService.GetAllActiveDepartments(1), "DepartmentID", "Department");
return View(model);
}
await ClaimsService.UpdateUserAsync(model.Users);
redirectUrl = string.Format("/ApplicationUsers/Users");
return RedirectToAction("Message", "Home", new { type = Service.Utils.StringHelper.Types.UpdateSuccess, url = redirectUrl });
}
if (appmodel.UserDetails.EmailAddress == model.Users.EmailAddress)
{
model.EmailAddressErrorMessage = "";
}
if (appmodel.UserDetails.EmailAddress != model.Users.EmailAddress)
{
model.EmailAddressErrorMessage = "Email address already exists";
}
if (appmodel.UserDetails.UserName == model.Users.UserName)
{
model.UserNameErrorMessage = "";
}
if (appmodel.UserDetails.UserName != model.Users.UserName)
{
model.UserNameErrorMessage = "Username already exists";
}
model.Username = appmodel.Users.UserName;
model.EmailAddress = appmodel.User.EmailAddress;
model.Users = new Model.Applications.Tables.tblUsers() { Archive_User = "0", StatusID = 1 };
model.BranchSelectList = new SelectList(await BranchServices.GetBranchByCompanyID(1), "BranchID", "BranchFullName");
model.DepartmentSelectList = new SelectList(await DepartmentService.GetAllActiveDepartments(1), "DepartmentID", "Department");
return View(model);
}

Discord.net issues creating, adding and removing roles

so I'm working on a mute and unmute command and what I want it to do is find if there is a role called "Muted" in the server if there is then give the user that role if there isn't then create the role with the necessary permissions. I've tried messing with bot permissions, role permissions, and hierarchy and it just doesn't do anything. There is no error given to me via Console nor is there an error generated in the text, it just simply seems to do nothing no matter what I try, can anyone see what I'm doing wrong? I created a pre-existing role called "Muted" and even with the role pre-applied it didn't add it. It also doesn't work while trying to remove the role if I manually added it to the user. This is what I've got:
[Command("mute")]
[Remarks("Mutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Mute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = true);
var muteRole = await GetMuteRole(user.Guild);
if (!user.Roles.Any(r => r.Id == muteRole.Id))
await user.AddRoleAsync(muteRole);//.ConfigureAwait(false);
}
}
[Command("unmute")]
[Remarks("Unmutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Unmute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = false).ConfigureAwait(false);
try { await user.ModifyAsync(x => x.Mute = false);/*.ConfigureAwait(false); */} catch { ReplyAsync("no"); }
try { await user.RemoveRoleAsync(await GetMuteRole(user.Guild));/*.ConfigureAwait(false); */} catch { ReplyAsync("No lmao"); }
}
}
public async Task<IRole> GetMuteRole(IGuild guild)
{
const string defaultMuteRoleName = "Muted";
var muteRoleName = "Muted";
var muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName);
if (muteRole == null)
{
try
{
muteRole = await guild.CreateRoleAsync(muteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
catch
{
muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName) ?? await guild.CreateRoleAsync(defaultMuteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
}
foreach (var toOverwrite in (await guild.GetTextChannelsAsync()))
{
try
{
if (!toOverwrite.PermissionOverwrites.Any(x => x.TargetId == muteRole.Id && x.TargetType == PermissionTarget.Role))
{
await toOverwrite.AddPermissionOverwriteAsync(muteRole, denyOverwrite);//.ConfigureAwait(false);
await Task.Delay(200);//.ConfigureAwait(false);
}
}
catch
{
}
}
return muteRole;
}
If anyone can help me that would be great, cheers!

Bug in order program in which payment can be bypassed

This project makes the customer first create an order and them has to pay for said order via Braintree, However the issue that I am getting is that a customer can create an order and them close the application. This will cause the order to still exist however the customer did not have to pay for their order. If any one knows of a work around for this their help would be thanked. (The orders and payments work. Its just this bug that I'm worried about)
Orders Controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FirstClassCreate(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
var customer = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
var cart = ShoppingCart.GetCart(this.HttpContext);
try
{
Sets the order attributes
order.DeliveryDate = DateTime.Now.AddDays(1);
order.DeliveryMethod = "First Class";
order.FirstName = customer.FirstName;
order.LastName = customer.LastName;
order.PostalCode = customer.PostalCode;
order.State = customer.State;
order.City = customer.City;
order.Email = customer.Email;
order.Country = customer.Country;
order.Phone = customer.PhoneNumber;
order.Address = customer.Address;
order.Username = customer.Email;
order.OrderDate = DateTime.Now;
var currentUserId = User.Identity.GetUserId();
order.Total = cart.GetFirstClass();
if (order.SaveInfo && !order.Username.Equals("guest#guest.com"))
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var ctx = store.Context;
var currentUser = manager.FindById(User.Identity.GetUserId());
//Save this back
//http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity
//var result = await UserManager.UpdateAsync(currentUser);
await ctx.SaveChangesAsync();
await storeDB.SaveChangesAsync();
}
Saves the order to the database
//Save Order
storeDB.Orders.Add(order);
await storeDB.SaveChangesAsync();
//Process the order
cart = ShoppingCart.GetCart(this.HttpContext);
order.Total = cart.GetFirstClass();
order = cart.CreateOrder(order);
return RedirectToAction("FirstClass", "Checkouts");
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
Checkouts controller
public ActionResult CreateFirstClass(FormCollection collection)
{
var gateway = config.GetGateway();
Decimal amount;
//Need to get the amount
try
{
amount = Convert.ToDecimal(Request["amount"]);
}
catch (FormatException e)
{
TempData["Flash"] = "Error: 81503: Amount is an invalid format.";
return RedirectToAction("New");
}
string nonceFromTheClient = collection["payment_method_nonce"];
var cart = ShoppingCart.GetCart(this.HttpContext);
//if (id == null)
//{
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
//}
//order = Orders.FindAsync(id);
Gets the necessary payment methods
var request = new TransactionRequest
{
Amount = cart.GetFirstClass(),
PaymentMethodNonce = nonceFromTheClient,
Options = new TransactionOptionsRequest
{
SubmitForSettlement = true
}
};
cart.EmptyCart();
Result<Transaction> result = gateway.Transaction.Sale(request);
if (result.IsSuccess())
{
Transaction transaction = result.Target;
return RedirectToAction("Show", new { id = transaction.Id });
}
else if (result.Transaction != null)
{
return RedirectToAction("Show", new { id = result.Transaction.Id });
}
else
{
string errorMessages = "";
foreach (ValidationError error in result.Errors.DeepAll())
{
errorMessages += "Error: " + (int)error.Code + " - " + error.Message + "\n";
}
TempData["Flash"] = errorMessages;
return RedirectToAction("New");
}
}
#

Categories