Swagger getting struck when returning Microsoft.Graph.User return type - asp.net-web-api

I have a default .NET 6 WebAPI project generated by VisualStudio to which I have added Microsoft.Graph nuget package
Here is my program.cs
and finally my controller
When I run this project and try to test the Get endpoint, the swagger UI is getting struck and there is no error being thrown
If I change the return type to either dynamic or object, it works as expected. Maybe I overlooking something basic but I couldn't figure out this issue. Any help is appreciated.

You can speedup rendering for complex types like Microsoft.Graph.User by disabling syntax highlight.
app.UseSwaggerUI(config =>
{
config.ConfigObject.AdditionalItems["syntaxHighlight"] = new Dictionary<string, object>
{
["activated"] = false
};
});
With this setting UI gets stuck only for 10-15 seconds.

Related

ASP.NET Core 6 MVC : adding identity failing

I'm using VS 2022, ASP.NET Core 6 MVC and Microsoft SQL Server 2019 (v15).
Git project: [https://github.com/Wizmi24/MVC_BookStore]
I'm trying to add --> new scaffolded item --> identity.
Default layout page, override all files and mine Data context
when I click add, I get this error:
There was an error running the selected code generator:
'Package restore failed. Rolling back package changes for 'MyProjectName'
I cleared NuGet Package cache as I saw it may help, but all it do is just prolong and this same error is visible after trying to install Microsoft.EntityFrameworkCore.SqlServer, which is installed. I checked the packages and made sure they are the same version (6.0.11).
I cloned your project to test, and the problem you mentioned did appear. Not sure why, but I finally got it working by updating the NuGet package:
I updated the two packages Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Relational to version 7.0.1 (you need to pay attention to the sequence when updating), then add scaffolded Identity, and I succeeded.
You can try my method, if the Identity is successfully added, but the following exception is encountered at runtime:
You need to add builder.Services.AddDbContext<MyBookContext>(); before
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<MyBookContext>();
MyBookContext is the Data context class selected when you add Identity:
In addition, if there is a 404 error in your area routing, you can refer to this document to modify it.
Hope this can help you.
Edit1:
I think it might be a problem caused by naming duplication. Please try to change the name of the context generated by Identity.
As you can see, the ApplicationDbContext generated by Identity is consistent with the ApplicationDbContext namespace in your MyBook.DataAccess:
So naming the same will cause conflict:
So you need to change the naming to avoid conflicts. For example:
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
builder.Services.AddDbContext<ApplicationDbContextIdentity>();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContextIdentity>();
Edit2:
As I mentioned in the original answer, if you get a 404 error, you can try to refer to this link to fix the area routing.
The easiest way is to directly change the routing settings in Program.cs:
app.MapAreaControllerRoute(
name: "Customer",
areaName: "Customer",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
Then add the Area property to the controller:
[Area("Customer")]
public class HomeController : Controller{}
There seems to be a problem with your Repository.cs, so I changed the Index to only output a string to test the result.
public string Index()
{
return "success";
}
Test Result:
If your Repository.cs also has problems when you test it, you can make a new post for everyone to help you fix this problem(Because this question strays so far from your original question, one post is better off addressing only one question).
Good Luck.

How to load plugins when updating to MvvmCross 6.4.2 from 5.6.2

I've been tasked with maintaining a Xamarin native project using MvvmCross 5.6.2. Not knowing exactly how to approach this, I've decided to update to one major version at a time (6 first, then 7 and 8). I'm not sure why I specifically have chosen 6.4.2, but it was maybe because this was the latest version of the majority of the plugins I was using on Nuget.
So far, the update has been a success and I have been able to fix all build errors. However, when running the application, I've been getting a null reference exception which I can't fully trace.
Based on the limited application output, I've been able to determine that the problem lies somewhere in my Android's setup.cs class (I think). I've been following Nick's .NET Travels advice on MvvmCross debugging. From viewing the MvvmCross 6.4.2. source and pasting in the following code in my own overrides:
public virtual void LoadPlugins(IMvxPluginManager pluginManager)
{
Type pluginAttribute = typeof(MvxPluginAttribute);
IEnumerable<Assembly> pluginAssemblies = GetPluginAssemblies();
foreach (Assembly item in pluginAssemblies)
{
IEnumerable<Type> enumerable = item.ExceptionSafeGetTypes();
foreach (Type item2 in enumerable)
{
if (TypeContainsPluginAttribute(item2))
{
pluginManager.EnsurePluginLoaded(item2);
}
}
}
bool TypeContainsPluginAttribute(Type type)
{
object[] customAttributes = type.GetCustomAttributes(pluginAttribute, inherit: false);
return ((customAttributes != null && customAttributes.Length != 0) ? 1 : 0) > (false ? 1 : 0);
}
}
public virtual IEnumerable<Assembly> GetPluginAssemblies()
{
string mvvmCrossAssemblyName = typeof(MvxPluginAttribute).Assembly.GetName().Name;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
var test = from asmb in assemblies.AsParallel()
where AssemblyReferencesMvvmCross(asmb, mvvmCrossAssemblyName)
select asmb;
return test;
}
I'm able to see that GetPluginAssemblies doesn't return any enumerable, and the LoadPlugins method then produces the NullReferenceException. But I can't see what this NullReference actually is.
I followed the upgrading from 5 to 6 guide https://www.mvvmcross.com/documentation/upgrading/upgrade-to-mvvmcross-60.
I looked at the MvvmCross 6 and 6.4.0 release pages:
https://www.mvvmcross.com/mvvmcross-6.0.0-release/
https://www.mvvmcross.com/mvvmcross-6.4.0-release/
And I followed Benjamin Mayrargue's guide: https://medium.com/#bigoudi/upgrading-from-mvvmcross-5-to-mvvmcross-6-7ded83ecb69d
But I have been unable to load my plugins (previously they were bootstraps, but most of the guides say these can be discarded now and that loading plugins is easier).
I also attempted the answer suggested in this question How to use an mvvmcross plugin such as the file plugin.
But to no avail.
So I am asking if anyone knows a good guide or how to use plugins in MvvmCross 6.4.2.
Thank you.
Plugins are just a way to register things in the IoC Container. This is done by MvvmCross during startup using the LoadPlugins method in your Setup file.
Most of the time it should just work. However, there are some caveats.
If the Linker has gone ahead and linked away some of the plugins code, you will have a bad time. What you can do about that is to hint the mono linker to not strip the code away.
Add a LinkerPleaseInclude class and add a Include method in it that looks something like:
new MvvmCross.Plugin.Color.Platforms.Ios.Plugin().Load();
You can do that for every plugin you may want to use.
If LoadPlugins doesn't find the entry Assembly, sometimes it also does not register the plugins. You can override LoadPlugins in your Setup class and just call EnsurePluginLoaded:
public override void LoadPlugins(IMvxPluginManager pluginManager)
{
base.LoadPlugins(pluginManager);
pluginManager.EnsurePluginLoaded<MvvmCross.Plugin.Color.Platforms.Ios.Plugin>();
}
I want to thank Cheesebaron for his plugin support. I think I've fixed my issue and as it turned out, I don't think there is a plugin issue after all (yet).
Thanks to Toolmakersteve also. His suggestion for using a try catch in the OnCreate of my overridden MvxSplashScreenAppCompatActivity surfaced an issue with setting a theme for this activity. In actuality, this class was initially a MvxSplashScreenActivity.
Reverting this line, I then started getting NullReferenceExceptions on specific lines, all relating to IoC and lazy construction of singletons. The class Mvx seemed to be throwing up this error. On a sort of hunch from previous experience with my updating, I removed the MvvmCross.Platform using statement and checked what suggestions Mvx had available to it. It suggested MvvmCross and MvvmCross.Platform, so I tried the former instead. Sure enough, this moved my execution further, throwing up more Null Reference Exceptions. I also encountered one instance of failing to resolve IMvxResourceLoader from MvvmCross.Platform.Platform. Switching that to MvvmCross.Base did the trick.
This was only a chance fix through a bit of guess work. #CheeseBaron, should I add this as a note to this bit of documentation https://www.mvvmcross.com/documentation/upgrading/upgrade-to-mvvmcross-60? As mentioned, I'm as far as 6.4.2 now, so I'm not certain this is the right place for it.
I've got a few bugs with embedded resources to fix now, but if I encounter any more that are relevant to my question, I'll list them here.

Error trying to scaffold a view in ASP.NET Core 6.0 MVC

I'm trying to scaffold a new razor view using Visual Studio. I select a template, my model and my DbContext, then I get the error message shown below.
Things to note. My models, my DbContext and my website are all in different projects. From the message below I am using AddDbContext and I have a constructor that accepts a DbContextOptions<TContext> parameter.
I read a comment on a blog post that the issue is because my context is in another project. The comment referenced something about the need to inject the Configuration into the DbContext to get the connection string and manually add it in the OnConfiguring override.
I can't find any examples if this is correct or how to set it up. Any help would be appreciated.
EDIT:
Testing out the theory from the blog comment I mentioned above, I added this section into my DbContext. ConnectionString is a hardcoded string constant with my connection information. This does work and allow me to scaffold, so the question still remains. How can I inject this connection string into my DbContext to allow the scaffolding to work?
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(ConnectionString);
}
else
{
base.OnConfiguring(optionsBuilder);
}
}
EDIT: So after making this change, I checked in the code and had another developer pick it up. It appears this section above just needs to be there to allow scaffolding to work. He never changed the connection string to point to his environment. He no longer got the error above it just worked.
I am not sure about what is the actual problem but it seems like we were having problems creating DbContext at design time. I manually added the code below and it's working now. It's just a temporary solution tho.
public AppDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=JwtTemplate;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
return new AppDbContext(optionsBuilder.Options);
}
Reference: https://stackoverflow.com/a/70559350

Vuepress oidc-client preventing build

It looks like Vuepress is made for public docs, but we decided to add client and server security to protect some of the doc pages. But unfortunately although oidc-client (https://github.com/IdentityModel/oidc-client-js/wiki) works during dev, it throws exception when build.
I get ReferenceError: window is not defined and when I try to trick the compiler with const window = window || { location: {} }; I get TypeError: Cannot read property 'getItem' of undefined
Any idea how to make this work?
This was driving me nuts also. I discovered the component I was trying to add was looking at window.location in its code - this was triggering the error.
My understanding is that the build process has not access to Browser things like window etc.
As soon as I removed the window.location bit from my code things built just fine and all is well.

MVC WebAPI returning 500 error with no information

I've been having this problem for several days (now fixed and solution noted for anyone that comes across this issue and is pulling their hair out).
After my latest round of code changes to my Silverlight application which uses MVC4 WebAPI for data, I was having a problem with one of my HttpGet Actions which was returning IQueryable<oneofmyclasses>. Using Fiddler2 to watch the request, I could see I was getting an internal server error (500), with no body text to explain why. I received no errors thrown in my Action.
Check 1: I verified that my Action was indeed getting to the return collection.AsQueryable(); line with no errors. It was
Check 2: I verified that my data was serializing to JSON with no errors using this code (g is my collection):
var json = new JsonMediaTypeFormatter();
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
ObjectContent<IEnumerable<Model.MenuGroup>> responseContent = new ObjectContent<IEnumerable<Model.MenuGroup>>(g, json);
MemoryStream ms = new MemoryStream();
responseContent.CopyToAsync(ms).Wait();
ms.Position = 0;
var sr = new StreamReader(ms);
var str = sr.ReadToEnd();
This also worked. I also tested it using XML formatter even though I was pretty sure it only ever used JSON (can't be too careful).
Check 3: Enabled .Net Framework debugging. This time when the error occured (in HttpApplication.cs) VS 2012 caught it.
My error:
Despite having marked the property with these attributes,
[XmlIgnore]
[IgnoreDataMember]
[JsonIgnore]
the .Net Source was calling a get on one of my properties. The catch, it was a write-only property. I simply added
get { return null; }
and the problem was solved.
I probably should have just done Check 3 first, but my previous experience with this error has shown it to usually be an error trying to serialize my objects, which was why I had a bit of a head scratcher when they did serialize properly and the error persisted.
How I solved it:
Enabled .Net Framework debugging. Tools -> Options -> Debugging -> Check 'Enable .NET Framework source stepping'
This time when the error occured (in HttpApplication.cs) VS 2012 caught it.

Resources