Update UnitAmount of Stripe Checkout Price - c#

I'm using Stripe Checkout and would like to update the UnitAmount of a Price.
However, the Update Price API doesn't allow UnitPrice. This is the code from Stripe's API Documentation:
StripeConfiguration.ApiKey = "{MY_API_KEY}";
var options = new PriceUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "order_id", "6735" },
},
};
var service = new PriceService();
service.Update("gold", options);
And these are the properties in PriceUpdateOptions:
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("lookup_key")]
public string LookupKey { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
public string Nickname { get; set; }
[JsonProperty("recurring")]
public PriceRecurringOptions Recurring { get; set; }
[JsonProperty("transfer_lookup_key")]
public bool? TransferLookupKey { get; set; }
Looking at the properties, UnitAmount doesn't seem to be editable once Price has been created.
I would like to do something like:
public void UpdateStripePrice(Product updatedProductResponse, ProductViewModel updatedProduct)
{
StripeConfiguration.ApiKey = "{MY_API_KEY}";
var options = new PriceUpdateOptions
{
Product = updatedProductResponse.Id,
UnitAmount = (long)updatedProduct.Price * 100,
};
var service = new PriceService();
service.Update(updatedProduct.StripePriceId, options);
}
I'm also unable to find a way of removing a Price, and "updating" it by recreating it.

Related

How to convert data from mongodb document to List

I Create a web-site and I have a problem. When I'm tring to get datas from mongodb and convert it to list, I have an error "Cannot apply indexing with [] to an expression of type 'CategoryModel'"
this is classes
public class CategoryModel
{
[BsonId]
public ObjectId id { get; set; }
[BsonElement("title")]
[JsonProperty("title")]
public string Name { get; set; }
[BsonElement("slug")]
public string slug { get; set; }
[BsonElement("__v")]
public int __v { get; set; }
}
public class ProductsModel
{
[BsonId]
public ObjectId id { get; set; }
[BsonElement("title")]
public string Name { get; set; }
[BsonElement("desc")]
public string Desc { get; set; }
[BsonElement("price")]
public int price { get; set; }
[BsonElement("category")]
public CategoryModel category { get; set; }
[BsonElement("image")]
public string ImageURL { get; set; }
}
this is my conntroller
public class ProductsController:Controller
{
private readonly IConfiguration _configuration;
List<CategoryModel> categoriesList = new List<CategoryModel>();
List<ProductsModel> productsList = new List<ProductsModel>();
[HttpGet("products")]
public async Task<IActionResult> Product()
{
var client = new MongoClient("mongodb://localhost:27017/");
var database = client.GetDatabase("cmscart");
var collection = database.GetCollection<CategoryModel>("categories");
var result = await collection.Find(new BsonDocument()).ToListAsync();
foreach (var item in result)
{
categoriesList.Add(new CategoryModel() { Name = (string)item["[title]"] }); //here I have an error
}
//products
var client2 = new MongoClient("mongodb://localhost:27017");
var database2 = client2.GetDatabase("cmscart");
var collection2 = database2.GetCollection<ProductsModel>("products");
var result2 = await collection2.Find(new BsonDocument()).ToListAsync();
foreach (var item2 in result2)
{
productsList.Add(new ProductsModel() { Name = (string)item2["title"], Desc = (string)item2["desc"], price = (int)item2["price"], ImageURL = (string)item2["image"] }); // and here I have an error
}
return View(categoryProduct);
}
}
I found a lot of solutions but I don't understand why this error is appear, because if this trick do with SQL then I don't have this error
You should be able to use the deserialized object directly:
var client = new MongoClient("mongodb://localhost:27017/");
var database = client.GetDatabase("cmscart");
var collection = database.GetCollection<CategoryModel>("categories");
List<CategoryModel> categoriesList = await collection.Find(new BsonDocument()).ToListAsync();
//products
var collection2 = database2.GetCollection<ProductsModel>("products");
List<ProductsModel> products = await collection2.Find(new BsonDocument()).ToListAsync();
Also, don't use class properties for local variables, declare everything in the innermost scope possible (in general). Ideally the MongoClient or Database would be injected into the class constructor too. You don't want to be instantiating them in an action method and you definitely don't want configuration values in there.

Should I create the "Id" property when modeling a LINQ cosmos db?

Let's suppose that I want to create the following document
{
"Id": "6a23a5f3-0f77-40a9-b9f9-26e88537a962",
"CarHistory": [
{ "model":"ford", "price": 100, "kilometers": 100 "current": true },
{ "model":"ford", "price": 200, "kilometers": 200, "current": false },
]
}
In Poco I guess that the model could look something among these lines:
public class Document
{
public Guid Id { get; set; }
}
public class Car : Document
{
public string Model {get; set;}
public decimal Price {get; set;}
public int Kilometers {get; set;}
public bool Current {get; set;}
}
So later I create..
public class MasterCar : Document
{
public ICollection<Car> CarHistory { get; set; } = new List<Car>();
}
All seems to work fine while debugging:
I create the Guid programmatically somewhere in a service like:
var masterCar = new MasterCar(){ Id = Guid.NewGuid() }
but when I go to the cosmos db emulator and a SELECT * FROM , and I checkout the Id property its value is:
"id": "00000000-0000-0000-0000-000000000000",
Can someone point me what Im doing wrong? or how this should be accomplished, I read that
you should not provide an Id yourself, BUT how can I access the Id property programmatically then?
For example:
CarService.GetById(Car.Id); //Id property doesnt exist if there is no property in poco
Below is my test code, you can have a try:
Document.cs
public class Document
{
[JsonProperty("id")]
public Guid Id { get; set; }
}
Car.cs
public class Car
{
[JsonProperty("model")]
public string Model { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("kilometers")]
public int Kilometers { get; set; }
[JsonProperty("current")]
public bool Current { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
MasterCar.cs
public class MasterCar : Document
{
public ICollection<Car> CarHistory { get; set; } = new List<Car>();
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
create and search:
var guid = Guid.NewGuid();
var masterCar = new MasterCar() { Id = guid };
var car = new Car() { Model = "ford", Price = 100, Kilometers = 100, Current = true };
var car2 = new Car() { Model = "ford", Price = 200, Kilometers = 200, Current = false };
var carHistory = masterCar.CarHistory;
carHistory.Add(car);
carHistory.Add(car2);
CosmosClient client = new CosmosClient(connection_string);
Container container = client.GetContainer(databaseId, containerName);
await container.CreateItemAsync<MasterCar>(masterCar);
ItemResponse<MasterCar> itemResponse = await container.ReadItemAsync<MasterCar>(guid.ToString("D"), new PartitionKey(guid.ToString("D")));
Console.WriteLine(itemResponse.Resource.ToString());
Result:

Google Calendar API v3 loop with Dictionary saves just 1

Hey all I have the following code below that I am using in order to save each calendar event to a Dictionary.
Dictionary<int, GoogleCalEvents> GEvents;
public class GoogleCalEvents
{
public string timeFrom { get; set; }
public string timeTo { get; set; }
public TimeSpan duration { get; set; }
public string summary { get; set; }
public string description { get; set; }
public string status { get; set; }
public string organizer { get; set; }
public EventAttendee attendees { get; set; }
public int ID { get; set; }
}
public Dictionary<int, GoogleCalEvents> getCalEvents()
{
foreach (var eventItem in events.Items)
{
GEvents = new Dictionary<int, GoogleCalEvents>()
{
{
loopID,
new GoogleCalEvents {
timeFrom = from,
timeTo = to,
duration = duration,
summary = summary,
description = description,
status = status,
organizer = organizer,
attendees = attendees,
ID = loopID
}
}
};
loopID++;
}
return GEvents;
}
And calling that class:
calendarAPI myClass = new calendarAPI();
Dictionary<int, GoogleCalEvents> blah = myClass.getCalEvents();
As its doing the foreach I can see it placing a 0 for the first go-around and then 1 for the second. However, during the loop it only has 1 value for GEvents each go-around. Once it returns GEvents it only has the last inserted item in the dictionary?
How am I setting this up incorrectly?
You are recreating the dictionary in the loop. You should do it once only
public Dictionary<int, GoogleCalEvents> getCalEvents()
{
var loopID=0;
var GEvents = new Dictionary<int, GoogleCalEvents>();
foreach (var eventItem in events.Items)
{
GEvents.Add(loopID, new GoogleCalEvents
{
timeFrom = from,
timeTo = to,
duration = duration,
summary = summary,
description = description,
status = status,
organizer = organizer,
attendees = attendees,
ID = loopID
});
}
loopID++;
return GEvents;
}

Pass list from model class to DbInitliazer

I'm new to C#. I'm working on a web app project. I want to know how to initialize the list in my DbInitializer class. For example, this is the Model:
using System;
using System.Collections.Generic;
namespace Manager.Model
{
public class Vendor
{
public int VendorID { get; set; }
public string CardName { get; set; }
public string WebsiteLink { get; set; }
public DateTime PartnerSince { get; set; }
public List<Rep> Reps { get; set; }
public string SupportNo { get; set; }
public string SupportEmail { get; set; }
public string Rebate { get; set; }
public string Spiff { get; set; }
public string Quote { get; set; }
}
public class Rep
{
public string RepName { get; set; }
public string RepPosition { get; set; }
public string RepNo { get; set; }
public string RepEmail { get; set; }
}
}
How would I pass this list in the Initialize method?
public static void Initialize(ManagementContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Vendors.Any())
{
return; // DB has been seeded
}
var vendors = new Vendor[]
{
new Vendor{CardName="Vendor1", WebsiteLink="www.vendor1.com", PartnerSince=DateTime.Parse("10-10-2012"), SupportNo="521-586-8956", SupportEmail="nikki#vendor1.com"},
};
foreach (Vendor v in vendors)
{
context.Vendors.Add(v);
}
context.SaveChanges();
If you'd like to do everything inline:
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = new List<Rep>()
{
new Rep() // first rep
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
}
// , new Rep(){...} // second rep, etc...
}
}
// , new Vendor(){....} // second vendor, etc...
};
Or simply prepare the Reps first:
List<Rep> Reps1 = new List<Rep>(); // Reps 1 for Vendor 1
Reps1.Add(new Rep()
{
RepName = "name",
RepPosition = "pos",
RepNo = "no",
RepEmail = "email"
});
// you may add more rep
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
Reps = Reps1
}
// , new Vendor(){....} // second vendor, etc...
};
For question if you change into string[] RepNames,
string[] RepNames1 = new string[]
{
"name1",
"name2" // , etc....
}
then assign it in vendor
Vendor[] vendors = new Vendor[]
{
new Vendor() // first vendor
{
CardName="Vendor1",
WebsiteLink="www.vendor1.com",
PartnerSince=DateTime.Parse("10-10-2012"),
SupportNo="521-586-8956",
SupportEmail="nikki#vendor1.com",
RepNames = RepNames1
}
// , new Vendor(){....} // second vendor, etc...
};

cant figure out how to map this json into C# classes

So I have the json below that I want to Deseralize into Classes so I can work with it. But the issues is that the top two fields are a different type to all the rest
"items": {
"averageItemLevel": 718,
"averageItemLevelEquipped": 716,
"head": { ... },
"chest": { ... },
"feet": { ... },
"hands": { ... }
}
Where ... is a the Item class below, but the problem is that 2 of the fields are ints and the rest are Item, there are about 20 fields in total. So what I'd like to do is put them into a Dictionary<string, Item> but the 2 int fields are preventing me from Deseralizing it into that. I'm using JavaScriptSerializer.Deserialize<T>() to do this.
I could have each item as it's own class with the name of the item as the name of the class, but I find that to be very bad, repeating so much each time, also very hard to work with later since I cant iterate over the fields, where as I could a Dictionary. Any idea how I could overcome this?
public class Item
{
public ItemDetails itemDetails { get; set; }
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public TooltipParams tooltipParams { get; set; }
public List<Stat> stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public List<int> bonusLists { get; set; }
}
Update: from the comments I came up with this solution
JObject jsonObject = JObject.Parse(json);
jsonObject["averageItemLevel"] = int.Parse(jsonObject["items"]["averageItemLevel"].ToString());
jsonObject["averageItemLevelEquipped"] = int.Parse(jsonObject["items"]["averageItemLevelEquipped"].ToString());
jsonObject["items"]["averageItemLevel"].Parent.Remove();
jsonObject["items"]["averageItemLevelEquipped"].Parent.Remove();
var finalJson = jsonObject.ToString(Newtonsoft.Json.Formatting.None);
var character = _serializer.Deserialize<Character>(finalJson);
character.progression.raids.RemoveAll(x => x.name != "My House");
return character
If I add these two classes to match your JSON I can serialize and deserialize the objects:
public class root
{
public Items items { get; set; }
}
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Item head {get;set;}
public Item chest {get;set;}
public Item feet {get;set;}
public Item hands {get;set;}
}
Test rig with the WCF Serializer:
var obj = new root();
obj.items = new Items
{
averageItemLevel = 42,
feet = new Item { armor = 4242 },
chest = new Item { name = "super chest" }
};
var ser = new DataContractJsonSerializer(typeof(root));
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine("and deserialize");
ms.Position = 0;
var deserializeObject = (root) ser.ReadObject(ms);
Console.WriteLine(deserializeObject.items.feet.armor);
}
And with the JavaScriptSerializer:
var jsser = new JavaScriptSerializer();
var json = jsser.Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("and deserialize");
var djson = jsser.Deserialize<root>(json);
Console.WriteLine(djson.items.feet.armor);
Both serializers give the same result for your given JSON.

Categories

Resources