I am a little embarrassed asking this question here since for anyone who has done this the answer will be real simple. I have tried several times asking Stripe Support but they simply keep referring me to the documentation (which is incomplete). I am building my first integration to the Stripe Billing Portal https://stripe.com/docs/billing/subscriptions/integrating-customer-portal using .Net
The code snippet below is taken from their site and it references the class SessionCreateOptions. My simple question is "what is the fully qualified namespace to this class in Stripe" as Visual Studio Cannot find it.
StripeConfiguration.ApiKey = "sk_test_47ZQVRjCoUpDACp40ICpzZKA00qYqRydc0";
[HttpPost("create-customer-portal-session")]
public async Task<IActionResult> CustomerPortal()
{
// Authenticate your user.
var options = **new SessionCreateOptions**
{
Customer = "{{ CUSTOMER_ID }}",
ReturnUrl = "https://example.com/account",
};
var service = new SessionService();
var session = service.Create(options);
return Response.Redirect(session.Url);
}
Many thanks in advance for any help
Related
My setup:
ASP.NET 4.5 web api (on Azure) saving data to SQL db (also on Azure)
AngularJS web front end (another Azure web site)
When a user first signs up, I show them a "getting started intro". The intro is only supposed to run once - I log the timestamp of the intro launch date as a custom field in the ASP.NET user table.
Imagine my surprise when I log in (as a user would) and see the intro TWICE.
The AngularJS front end is properly sending the "intro viewed" message to the ASP.NET api, and the api responds with a success message. However, when I look at the raw data in the db, the timestamp is most definitely NOT updated. Consequently, the user will see the intro a second time (at which point the timestamp gets recorded in the db properly).
I have a crappy workaround. After the client requests an OAuth Bearer token from my server, the client then requests user information (to decide whether or not to show the tour). Waiting 100ms and then sending the "tour viewed" message back to the server masks the issue.
I've not seen ANY other issues storing data at any point. Because our db is on Azure, I can't hook up Profiler and the built in auditing doesn't give me any clues.
Is there something about requesting the token that leaves ASP.NET identity in a funny state? And it takes a brief wait before you can write to the table? Are custom fields that extend the base Identity setup prone to problems like this? Is the UserManager possibly doing something weird in its black box?
Does anyone have suggestions for how to continue debugging this problem? Or ever hear of anything like it?
Here's the relevant code that should be updating the "tour viewed" timestamp in the db:
[HttpPost, Route("UserInfo")]
public async Task<IHttpActionResult> UpdateUserInfo(UpdateBindingModel model)
{
var currentUser = UserManager.FindById(User.Identity.GetUserId());
if (model.FirstName != null)
{
currentUser.FirstName = model.FirstName;
}
if (model.LastName != null)
{
currentUser.LastName = model.LastName;
}
if (model.SetIntroViewCompleteDate)
{
currentUser.IntroViewCompleteDate = DateTime.UtcNow;
}
if (model.SetIntroViewLaunchDate)
{
currentUser.IntroViewLaunchDate = DateTime.UtcNow;
}
if (model.SetTipTourCompleteDate)
{
currentUser.TipTourCompleteDate = DateTime.UtcNow;
}
if (model.SetTipTourLaunchDate)
{
currentUser.TipTourLaunchDate = DateTime.UtcNow;
}
IdentityResult result = await UserManager.UpdateAsync(currentUser);
if (result.Succeeded)
{
var data = new UserInfoViewModel
{
FirstName = currentUser.FirstName,
LastName = currentUser.LastName,
IntroViewLaunchDate = currentUser.IntroViewLaunchDate
};
return Ok(data);
}
return InternalServerError();
}
UPDATE ********* 4/18
I've also tried to move completely away from UserManager stuff. I've tried the following modifications (pulling the user data from a table like I would access any other data), but it still behaves the same. I'm starting to think that putting custom fields on the ApplicationUser object is a bad idea...
New db retrieve and save looks like this:
ApplicationDbContext newContext = new ApplicationDbContext();
var currentUser = await (from c in newContext.Users
where c.Email == User.Identity.Name
select c).SingleOrDefaultAsync();
//update some values
await newContext.SaveChangesAsync();
Basically the problem might be with initialization of the `UserManager' and the fact that this class works on the db context so you need to persist changes to that context. Here is an example:
var userStore = new UserStore<ApplicationUser>(new MyDbContext());
var userManager = new UserManager(userStore);
That way you remember both manager and context. Then in your method you would normally call:
IdentityResult result = await userManager.UpdateAsync(currentUser);
followed by persisting this change to db context:
var dbContext = userStore.context;
dbContext.saveChanges();
Based on your comment that waiting 100ms masks the issue, I think you may have a problem with the multiple async await calls. Try running the calls synchronously and see if you still have the same issue. My guess is that the problem might go away. My experience has been that using async await can be tricky when you have calls to asynchronous methods that call other asynchronous methods. You may have code that is executing without the proper results returned.
Well, here's what I did to solve the problem. I totally de-coupled my custom user data from the built in ASP.NET identity stuff. I've now got a separate object (and therefore separate SQL table) that stores things like FirstName, LastName, LastActiveDate, etc, etc.
This has solved my problem entirely, though it has introduced another call to the database in certain situations. I've deemed it to be not a big enough performance issue to worry about. I'm left thinking that this was some sort of weird race condition involving the generation of a token for an ASP.NET identity user then quickly writing to an Azure SQL database - lord knows what it was exactly in my code that caused the problem.
If you've got a problem that's hard to solve, often the best plan is to change the problem.
Now I need to find a meta thread discussing what to do with bounty points when you've blown up the problem...
I'm trying to develop a program that handles POST and GET requests.
I've spent countless hours searching around the web for a tutorial that doesn't depend on ASP.NET I do not want to use ASP.NET just standard C#.
How can I achieve this? The furthest I've gotten to is this:
if (HttpMethod.ContentType == "POST") {
// Code here
}
I've made a function HttpListen server on http://localhost:8080/ which sends a response.
What I'm looking for is you do http://localhost:8080/?method=val1&results=val2.
Thanks, Brown.
You're looking for an HTTP server library that is not ASP.NET?
Awkwardly bypassing the question "What's wrong with ASP.NET?"....
Nancy is an awesome lightweight open source library. You can find some samples on github, although the samples are a bit on the heavy side. If you're looking for an extremely basic setup you can get away with a couple dozen lines of code. A good example is the console-based self-hosted sample.
// add such a module class to your assembly, Nancy should find it automagically
public class ResourceModule : NancyModule
{
public ResourceModule() : base("/products")
{
// would capture routes to /products/list sent as a GET request
Get["/list"] = parameters => {
return "The list of products";
};
}
}
// then start the host
using (var host = new NancyHost(new Uri("http://localhost:1234")))
{
host.Start();
// do whatever other work needed here because once the host is disposed of the server is gone
Console.ReadLine();
}
I followed this asp.net tutorial by Mike Wasson, and managed to set up the related entities just fine, but when I applied this logic to my project the more complex entity relations (in that there are more of them; that's the only difference) wouldn't succeed in an OData call, I got a 404 with this payload:
{
"error": {
"code": "",
"message": "No HTTP resource was found that matches the request URI 'http://localhost:19215/Menus(c94f7f98-6987-e411-8119-984be10349a2)/MenuPermissions'.",
"innererror": {
"message": "No routing convention was found to select an action for the OData path with template '~/entityset/key/unresolved'.",
"type": "",
"stacktrace": ""
}
}
}
The tutorial doesn't mention having to set up EdmModel navigations and Mike Wasson makes a point of pointing out that "asp.net is official documentation :-)"; so, I have spent a while trying to get these related entities working, thinking I had set up the project incorrectly.
I thought it might have something to do with the version of ASP.NET OData libraries that NuGet was installing (the NuGet Console installs 6.9.x, whereas the NuGet Dialog installs 6.5.x). I also wondered if it was because I set the project up as a completely empty project and then use OWIN, so I tried it with a pure ASP.NET templated solution. I also tried a couple of other possible solutions: OData-route-attributes on my controller methods; and including my data layer and models all in the same library (I have them separated out to keep DRY); I even attempted to use the WebApi route debugger by Rick Anderson - I wouldn't attempt to use this again!
All to no avail.
There was a brief moment when they worked, but I don't know why; they ceased to work on the next build/run - I guess I changed something in between, but it was very minor and I was losing confidence at every step.
Then I decided that Mike Wasson must've just taken the path of least resistance in his tutorial and so I reverted to this SO question/answer and modified it for use with ODataConventionModelBuilder and reuse, as I will explain in my answer below.
If anyone knows of a simpler way of getting this to work, please let me know, otherwise I recommend just biting the bullet and writing those EdmModel-Navigations in my answer below.
As I mention in the question, I tried many solutions to get this to work, but none were consistent in actually solving the problem and I kept avoiding the solution laid out in this SO question/answer because the tutorial is specifically for v4 and I figured that answer must be for an older version (how unwise).
So that answer does solve the problem, but requires some work to fit directly into OData v4 and an ODataConventionModelBuilder; this is why I have posted this question and answer; to provide a solution, specifically for OData v4 and ODataConventionModelBuilder, in the hope that others won't lose the time I have looking into this.
First, set up your EdmModel:
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();
builder.EntitySet<Menu>("Menus");
builder.EntitySet<MenuPermission>("MenuPermissions");
var edmModel = builder.GetEdmModel();
AddNavigations(edmModel); //see below for this method
return edmModel;
}
Second AddNavigations:
private static void AddNavigations(IEdmModel edmModel)
{
AddMenuPermissionsNavigation(edmModel);
}
private static void AddMenuPermissionsNavigation(IEdmModel edmModel)
{
var menus = (EdmEntitySet) edmModel.EntityContainer.FindEntitySet("Menus");
var menuPermissions = (EdmEntitySet)edmModel.EntityContainer.FindEntitySet("MenuPermissions");
var menuType = (EdmEntityType) edmModel.FindDeclaredType("iiid8.cms.data.models.Menu"); //"iiid8.cms.data.models" is the C# namespace
var menuPermissionType = (EdmEntityType)edmModel.FindDeclaredType("iiid8.cms.data.models.MenuPermission"); //as above, "iiid8.cms.data.models" is the C# namespace
AddOneToManyNavigation("MenuPermissions", menus, menuPermissions, menuType, menuPermissionType);
AddManyToOneNavigation("Menu", menus, menuPermissions, menuType, menuPermissionType);
}
private static void AddOneToManyNavigation(string navTargetName, EdmEntitySet oneEntitySet, EdmEntitySet manyEntitySet,
EdmEntityType oneEntityType, EdmEntityType manyEntityType)
{
var navPropertyInfo = new EdmNavigationPropertyInfo
{
TargetMultiplicity = EdmMultiplicity.Many,
Target = manyEntityType,
ContainsTarget = false,
OnDelete = EdmOnDeleteAction.None,
Name = navTargetName
};
oneEntitySet.AddNavigationTarget(oneEntityType.AddUnidirectionalNavigation(navPropertyInfo), manyEntitySet);
}
private static void AddManyToOneNavigation(string navTargetName, EdmEntitySet oneEntitySet, EdmEntitySet manyEntitySet,
EdmEntityType oneEntityType, EdmEntityType manyEntityType) {
var navPropertyInfo = new EdmNavigationPropertyInfo {
TargetMultiplicity = EdmMultiplicity.One,
Target = oneEntityType,
ContainsTarget = false,
OnDelete = EdmOnDeleteAction.None,
Name = navTargetName
};
manyEntitySet.AddNavigationTarget(manyEntityType.AddUnidirectionalNavigation(navPropertyInfo), oneEntitySet);
}
Finally, call GetEdmModel from WebApiConfig.Register
config.MapODataServiceRoute("odata", null, GetEdmModel());
Now call your OData service's one-to-many and many-to-one navigations from your client and all should be good with your world. In my case the calls look like this:
One-to-many:
http://localhost:19215/Menus(c94f7f98-6987-e411-8119-984be10349a2)/MenuPermissions
Many-to-one:
http://localhost:19215/MenuPermissions(ba0da52a-6c87-e411-8119-984be10349a2)/Menu
This answer assumes you set up the rest of your project just like Mike Wasson suggests in the tutorial linked in the question (that link is to Part 3 - you will need to follow Part 1 first!).
I am using ASP.NET 5, Web API 2.2, and Entity Framework.
Another developer and I have also spent hours trying to figure out why, after following that same tutorial to a T, we couldn't get a relational route like the following to return anything other than a 404:
/odata/Supplier(1)/Products
We also tried the route debugger referenced in the OP, and it failed to produce anything other than a blank screen.
Luckily, for our needs, one of our random experiments worked, and that was to use the ODataRoute attribute like such:
[EnableQuery]
[ODataRoute("Suppliers({key})/Products")]
public IQueryable<Product> GetProductsForSupplier([FromODataUri] int key)
{
...
}
I'm rewriting some old application, written in ASP.NET MVC. It used authentication by LDAP, but now it is necessary to rewrite it to OAuth2. I've decided to use DotNetOpenAuth library as it looked like best choice, but I'm stuck on auth response.
Currently, I have one controller class called AccountController, containing some methods, but most important are RedirectToIS and PostAuth (which is an redirect uri):
public ActionResult RedirectToIS()
{
DotNetOpenAuth.OAuth2.AuthorizationServerDescription asd = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription();
String site = ConfigurationManager.AppSettings["oauth:site"];
asd.AuthorizationEndpoint = new Uri(site + "/oauth/authorize");
asd.TokenEndpoint = new Uri(site + "/oaut/token");
asd.ProtocolVersion = DotNetOpenAuth.OAuth2.ProtocolVersion.V20;
this.oaclient = new DotNetOpenAuth.OAuth2.WebServerClient(asd, ConfigurationManager.AppSettings["oauth:appid"], ConfigurationManager.AppSettings["oauth:secret"]);
this.oaclient.RequestUserAuthorization(null, new Uri("http://localhost/Account/PostAuth"));
return View();
}
The PostAuth method is what I am trying to make to work correctly. It is page, where the OAuth2 server redirect user after successful authorization with code and state GET parameters. Because I'm trying to utilize library and not (re)write it, I've stuck here - I don't know what to do now.
I tried, as I've seen in one example, use DotNetOpenAuth.OAuth2.IAuthorizationState st = this.oaclient.ProcessUserAuthorization(); in PostAuth, but it don't work. In example author had original WebServerClient instance, but I can't achieve it with Session nor using AccountControler data item.
So, finally, my question: How to transfer object oaclient from RedirectToIS method to PostAuth method (some kind of session?) or how to start using OAuth?
PS: I'm not new to C#, but I've never used ASP.NET.
Hi again stackoverflow,
I am following a tutorial on how to build an Android application in Xamarin and I have encountered an error I cannot resolve on my own.
Hoping anyone of you might shed some light on how to proceed from here:
This code is copied from the tutorial itself (source: pluralsight)
private JsonServiceClient client;
private IList<User> users;
void PopulateSelectUsers ()
{
var response = client.Get(new Users());
users = response.Users.ToList ();
var names = users.Select (u => u.Name);
var usersSpinner = FindViewById<Spinner> (Resource.Id.usersSpinner);
usersSpinner.Adapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1, names.ToArray ());
}
Where "Users" is a request:
public object Get(Users request)
{
return new UsersResponse { Users = Repository.GetUsers() };
}
[Route("/users", "GET")]
public class Users : IReturn<UsersResponse>
{
}
public class UsersResponse
{
public IEnumerable<User> Users { get; set; }
}
HOWEVER once Xamarin read this line of code:
var response = client.Get(new Users());
then the application in the emulator just crashes and Xamarin leaves me no information on what happened or how to fix it..
It seems that this code works in the tutorial and as I mentioned before, Xamarin leaves me no information on what happened or how to fix it, so my question would be if perhaps one of you know what Is happening or perhaps a way to fix it.
Also perhaps worth mentioning is that I'm using redis to store users.
IF you want to view the userservice it is available here:
http://shan13alwo.cloudapp.net/api/metadata
You can check if code works by sending JSON GET to http://shan13alwo.cloudapp.net/api/users
Thank you in advance,
UPDATE:
I realize I might have been unclear of what I wanted to do but to simplify. What I want to do Is get my users(ienumerable) from my redis database and store them in a List. Using the this code in Xamarin does not work:
var response = client.Get(new Users());
users = response.Users.ToList ();
As Scott previously pointed out to me In another topic made here on Stackoverflow:
ServiceStack v4 was JUST released and using different versions of the servicestack library in Xamarin and Visual Studio resulted in this strange behavior.
Reverting back to V3 of ServiceStack solved my issues.
I would like to thank Scott for your assistance and would like to ask one last thing:
Where can I download the VERSION 3, free license version of the ServiceStack libraries for Android?
(Think its called "AndroidIndie")
Downloading and compiling the solution with the libraries from the lib folder of ServiceStack results in "evaluation software, build valid for 24 hours".
Thank you in advance.