I am trying to delete set of records under my ASP.NET Application - API Controller. Here is my code from API Controller:
public JsonResult Delete([FromBody]ICollection<ShoppingItemViewModel> vm)
{
if (ModelState.IsValid)
{
try
{
var items = Mapper.Map<IEnumerable<ShoppingItem>>(vm);
_repository.DeleteValues(items, User.Identity.Name);
return Json(null);
}
catch (Exception Ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
And here is my AngularJS Controller part taking care of this:
$scope.RemoveItems = function () {
$scope.isBusy = true;
$http.delete("/api/items", $scope.items)
.then(function (response) {
if (response.statusText == "OK" && response.status == 200) {
//passed
for (var i = $scope.items.length - 1; i > -1; i--) {
if ($scope.items[i].toRemove == true) {
$scope.items.splice(i, 1);
}
}
}
}, function (err) {
$scope.errorMessage = "Error occured: " + err;
}).finally(function () {
$scope.isBusy = false;
});
}
For unknown reason, this works like a charm in my POST method but not in the Delete Method. I believe that the problem might be caused by the fact, that DELETE method only accepts Integer ID?
If that is the case, what is the correct way how to delete multiple items with one call?
Related
enter image description hereHi Thanks in advance i have facing a problem in my xamarin forms ios. Problem is that when i want to purchase product it thrown an exception that cannot to connect to itune store my same code in working fine on xamarin forms android.My code for restore purchases is working fine.
Here is my code for make purchases
private async Task<bool> MakePurchase(string ProductId, string Payload)
{
if (!CrossInAppBilling.IsSupported)
{
return false;
}
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)//Couldn't connect to billing, could be offline,
alert user
{
DependencyService.Get<IToast>().Show("Something went
wrong or you may not connected with the internet!");
return false;
}
//try to purchase item
var purchase = await billing.PurchaseAsync(ProductId,
ItemType.InAppPurchase, Payload);
if (purchase == null)
{
return false;
}
else
{
//Purchased, save this information
var responseId = purchase.Id;
var responseToken = purchase.PurchaseToken;
var state = purchase.State;
return true;
}
}
catch (InAppBillingPurchaseException ex)
{
if (ex.PurchaseError == PurchaseError.DeveloperError)
{
DependencyService.Get<IToast>().Show("DeveloperError");
ex.Message.ToString();
}
else if (ex.PurchaseError == PurchaseError.AlreadyOwned)
{
DependencyService.Get<IToast>().Show("AlreadyOwned");
return true;
}
else if(ex.PurchaseError == PurchaseError.BillingUnavailable)
{
DependencyService.Get<IToast>
().Show("BillingUnavailable");
return false;
}
else if(ex.PurchaseError == PurchaseError.InvalidProduct)
{
DependencyService.Get<IToast>().Show("InvalidProduct");
return false;
}
else if(ex.PurchaseError == PurchaseError.ItemUnavailable)
{
DependencyService.Get<IToast>().Show("ItemUnavailable");
return false;
}
else if(ex.PurchaseError == PurchaseError.GeneralError)
{
DependencyService.Get<IToast>().Show("General Error");
return false;
}
//Something bad has occurred, alert user
}
finally
{
//Disconnect, it is okay if we never connected
await billing.DisconnectAsync();
}
return false;
}
I have an app that is using an http server to serve files to a Web View. The web viewers are caching image links which is causing broken images when their paths changes.
I can delete the web store on Android and UWP but I cannot figure out how to properly with iOS.
Android:
Android.Webkit.WebStorage.Instance.DeleteAllData();
UWP:
Windows.UI.Xaml.Controls.WebView.ClearTemporaryWebDataAsync();
I have tried the following with no luck:
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(
websiteDataTypes: record.DataTypes,
date: new[] { record },
completionHandler: ()=> { });
}
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
NSUrlCache.SharedCache.DiskCapacity = 0;
NSUrlCache.SharedCache.MemoryCapacity = 0;
Found the answer at: https://gochannel.org/links/link/snapshot/640
Rewrote to Xamarin IOS
private void DeleteCachedFiles()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
NSHttpCookieStorage.SharedStorage.RemoveCookiesSinceDate(NSDate.DistantPast);
WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes(WKWebsiteDataStore.AllWebsiteDataTypes, (NSArray records) =>
{
for (nuint i = 0; i < records.Count; i++)
{
var record = records.GetItem<WKWebsiteDataRecord>(i);
WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes(record.DataTypes,
new[] { record }, () => { Console.Write($"deleted: {record.DisplayName}"); });
}
});
NSUrlCache.SharedCache.RemoveAllCachedResponses();
}
else
{
// Remove the basic cache.
NSUrlCache.SharedCache.RemoveAllCachedResponses();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies;
foreach (var c in cookies)
{
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
}
try
{
// Clear web cache
DeleteLibraryFolderContents("Caches");
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
DeleteLibraryFolderContents("Cookies");
// Removes all app cache storage.
DeleteLibraryFolder("WebKit");
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting cache {ex.Message}");
}
}
private void DeleteLibraryFolder(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
manager.Remove(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
private void DeleteLibraryFolderContents(string folderName)
{
var manager = NSFileManager.DefaultManager;
var library = manager.GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User).First();
var dir = Path.Combine(library.Path, folderName);
var contents = manager.GetDirectoryContent(dir, out NSError error);
if (error != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
foreach (var c in contents)
{
try
{
manager.Remove(Path.Combine(dir, c), out NSError errorRemove);
if (errorRemove != null)
{
App.UnhandledException(new Exception(error.Description), error.Description);
}
}
catch (Exception ex)
{
App.UnhandledException(ex, $"Error deleting folder contents: {folderName}{Environment.NewLine}{ex.Message}");
}
}
}
I am implementing CoinPayments IPN in my application and I have trouble with passing data to the method that take their Callback. I have tried like everything I could find: TempData, SessionVariables, tried to implement it somewhere in forms and maybe Request it but that didn`t work for me. So I also tried to implement it with Global static variables. And it worked! But then came another issue: if more than one user were to buy something from website at the same time or even in between any callbacks their data will get mixed. So here I am, trying again to make Session Variables work and have no clue why they are not working as I used them before. Probably what I can think of is that because its a callback from CoinPayments and I handle something wrongly.
Here is the code I have right now: Tho I tried different variations like implementing Session in Get Payment method. Now I ended up with it and it still comes out as null in POST METHOD.
Class for handling Session Variables:
public static class MyGlobalVariables
{
public static int TokenChoice
{
get
{
if (System.Web.HttpContext.Current.Session["TokenChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["TokenChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["TokenChoice"] = value;
}
}
public static int PaymentChoice
{
get
{
if (System.Web.HttpContext.Current.Session["PaymentChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["PaymentChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["PaymentChoice"] = value;
}
}
public static string CurrentUser
{
get
{
System.Web.HttpContext.Current.Session["CurrentUser"] = System.Web.HttpContext.Current.User.Identity.Name;
return (string)System.Web.HttpContext.Current.Session["CurrentUser"];
}
}
}
Class that returns view where you click on CoinPayments button:
public ActionResult Payment(int tokenChoice, int paymentChoice)
{
ViewBag.Payment = paymentChoice;
MyGlobalVariables.PaymentChoice = paymentChoice;
MyGlobalVariables.TokenChoice = tokenChoice;
return View();
}
Callback class that handles Callback from CoinPayments:
[HttpPost]
public ActionResult Payment()
{
NameValueCollection nvc = Request.Form;
var merchant_id = id;
var ipn_secret = secret;
var order_total = MyGlobalVariables.PaymentChoice;
if (String.IsNullOrEmpty(nvc["ipn_mode"]) || nvc["ipn_mode"] != "hmac")
{
Trace.WriteLine("IPN Mode is not HMAC");
return View();
}
if (String.IsNullOrEmpty(HTTP_HMAC))
{
Trace.WriteLine("No HMAC signature sent");
return View();
}
if (String.IsNullOrEmpty(nvc["merchant"]) || nvc["merchant"] != merchant_id.Trim())
{
Trace.WriteLine("No or incorrect Merchant ID passed");
return View();
}
//var hmac = hash_hmac("sha512", request, ipn_secret.Trim());
var txn_id = nvc["txn_id"];
var item_name = nvc["item_name"];
var item_number = nvc["item_number"];
var amount1 = nvc["amount1"];
var amount2 = float.Parse(nvc["amount2"], CultureInfo.InvariantCulture.NumberFormat);
var currency1 = nvc["currency1"];
var currency2 = nvc["currency2"];
var status = Convert.ToInt32(nvc["status"]);
var status_text = nvc["status_text"];
Trace.WriteLine(status);
if (currency1 != "USD") {
Trace.WriteLine("Original currency mismatch!");
return View();
}
if (Convert.ToInt32(amount1) < Convert.ToInt32(order_total))
{
Trace.WriteLine("Amount is less than order total!");
return View();
}
if (status >= 100 || status == 2) {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null && account.Paid == 0)
{
Trace.WriteLine("Payment Completed");
Trace.WriteLine("Tokens to add: " + MyGlobalVariables.TokenChoice);
account.Tokens += MyGlobalVariables.TokenChoice;
account.Paid = 1;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
} else if (status < 0)
{
Trace.WriteLine(
"payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent");
} else {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null)
{
account.Paid = 0;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
Trace.WriteLine("Payment is pending");
}
return View();
}
As you can see there are only 3 variables I need to handle.
Also someone might ask why I use Session Variable for Current.User?
Well for some reason Callback method can not read Current.User as it return null. And well... nothing really changed as for now.
If you have ever experienced something like that or can find an issue I would be so thankful since I wasted already over 2 days on that issue.
EDIT:
After some testing I found out variables works fine if I run Post method on my own. So the problem is with handling callback from CoinPayments. Is there a specific way to deal with this?
i am saving data through Model. SaveChanges not saving new record in database.
and not throwing any exception. kindly help anyone to get me out this situation.
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
AMmodel.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(AMmodel);
db.SaveChanges();
}
}
catch (Exception e )
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}
I would suggest making changes to your ActionMethod as shown below; basis this accepted Stackoverflow answer.
Note that this example is not tested though; and I might be wrong...
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
Ambulance_Position ambulance_position = new Ambulance_Position();
ambulance_position = AMmodel;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
//AMmodel.Date_Time = System.DateTime.Now;
ambulance_position.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(ambulance_position);
db.SaveChanges();
}
}
catch (Exception e)
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}
I am using asp.net core RoleManager to perform roleClaim(permission) based authorization. The below code work fine but it take too much time execute because i delete the roleclaim each at a time. but i want to delete roleclaims(permission) at one shot delete query , Can anyone help me ? thank's in advance.
//my controller code
public async Task<IActionResult> SaveRolePermission([FromBody] RoleClaimVM model)
{
try
{
if (string.IsNullOrEmpty(model.RoleId) || model.ClaimValues.Length <= 0) return Json(new { status = false });
var role = await _roleManager.FindByIdAsync(model.RoleId);
if (role == null) return null;
var roleClaims = _roleManager.GetClaimsAsync(role).Result.ToList();
if (roleClaims.Any())
{
foreach (var item in roleClaims)
{
await _roleManager.RemoveClaimAsync(role, item);
}
}
foreach (var item in model.ClaimValues)
{
await _roleManager.AddClaimAsync(role, new Claim(CustomClaimtypes.Permission, item.ToLower()));
}
return Json(new { status = true });
}
catch (Exception)
{
return Json(new { status = false });
}
}