JsonApiDotNetCore 4.0 has removed BuildResourceGraph from JsonApiOptions. What is the replacement? - asp.net-core

I am migrating from .NET Core 2.2 to 3.1. In doing so, I have updated the JsonApiDotNetCore package from 3.1 to 4.0.0 alpha 4.
In 2.2, I used JsonApiDotNetCore 3.1 and was using BuildResourceGraph to add any JSON API resources to the resource graph. Code below:
IMvcCoreBuilder objMvcCoreBuilder = null;
objServices.AddJsonApi((objOptions) =>
{
objOptions.BuildResourceGraph((objBuilder) =>
{
objBuilder
.AddResource<Register>("registers")
.AddResource<Client>("clients")
;
});
}, objMvcCoreBuilder);
But, I get the following error:
'JsonApiOptions' does not contain a definition for
'BuildResourceGraph' and no accessible extension method
'BuildResourceGraph' accepting a first argument of type
'JsonApiOptions' could be found (are you missing a using directive or
an assembly reference?)
What is the replacement for BuildResourceGraph?

After digging through the JsonApiOptions.cs commit history on Git, I found the change:
IMvcCoreBuilder objMvcCoreBuilder = null;
objServices.AddJsonApi(
options => options.Namespace = "api/v1",
resources: resources =>
resources
.AddResource<Register>("registers")
.AddResource<Client>("clients")
,
mvcBuilder: objMvcCoreBuilder
);
Go down to the /NoEntityFrameworkExample/Startup.cs file and you will see the diff that shows the change. Other than that, there is only a cryptic mention to renaming BuildResourceManager in the change log notes at the top of the site.
https://github.com/json-api-dotnet/JsonApiDotNetCore/commit/7b8250bf5b9e64b91d8fa0357e915a1121eb6081#diff-d56ca61ff20d8be0b7cb20c9fd106d9f
The revised version of the file is here:
https://github.com/json-api-dotnet/JsonApiDotNetCore/blob/7b8250bf5b9e64b91d8fa0357e915a1121eb6081/src/Examples/NoEntityFrameworkExample/Startup.cs

Related

Microsoft.Graph, c# sdk, trying to get list of driveitems from onedrive root folder: Error "DriveRequestBuilder does not contain a definition for Root

.NET MAUI App,
I am trying to get a list of Children from Root folder on Drive... I get this error in edition/compile time, when I use a snippet of code from MS Learn:
'DriveRequestBuilder' does not contain a definition for 'Root' and no accessible extension method 'Root' accepting a first argument of type 'DriveRequestBuilder' could be found (are you missing a using directive or an assembly reference?)
I just cloned a sample project developed by microsoft staff and inserted a snippet of code from MS Learn.
Pls, get the entire project with the error here:
https://github.com/leoderja/DriveRequestBuilder_RootNotDefined.git
The error is in:
MauiAppBasic.csproj project ->
MSALClient folder ->
MSGraphHelper.cs file ->
TestRootChildrenAsync method
Using Microsoft.Graph version 5.0.0-rc.1
EDITION: Here a minimal example:
using Microsoft.Graph;
GraphServiceClient graphClient = new GraphServiceClient(new HttpClient());
var children = await graphClient.Me.Drive.Root.Children.Request().GetAsync();
The problem was Microsoft.Graph v5.00 rc1. When I set v4.50 the errors disappeared. I hope that Microsoft staff update the documentation with the changes when final release of v5 is available.
Since version 5 the Root is accessible through Drives[userDriveId] but not through Me.Drive
var children = await client.Drives[userDriveId].Root.Children.GetAsync();
If you don't know the user's drive id you need to call Me.Drive.
var driveItem = await client.Me.Drive.GetAsync();
var children = await client.Drives[driveItem.Id].Root.Children.GetAsync();

Identity error when to ASP.NET Core MVC RC2 upgrading from RC1

I have from my RC1 version:
services.AddIdentity<User, Role>(options =>
{
// configure identity options
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 3;
options.User.AllowedUserNameCharacters = null;
})
.AddEntityFrameworkStores<JobsDbContext, int>()
.AddUserStore<UserStore<User, Role, JobsDbContext, int>>()
.AddRoleStore<RoleStore<Role, JobsDbContext, int>>()
.AddDefaultTokenProviders();
and I am getting an error on the first line specifically this part of the line:
AddIdentity<User, Role>
The error is:
The call is ambiguous between the following methods or properties: 'Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions.AddIdentity(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' and 'Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions.AddIdentity(Microsoft.Extensions.DependencyInjection.IServiceCollection, System.Action)' JobsLedger..NETCoreApp,Version=v1.0 C:\Users\simon\DEV\JobsLedger-RC2-FIrstAttempt\src\JobsLedger\Startup.cs 64 Active
I know this is bleeding edge but if there is anybody out there who might have an idea on this I am all ears..
Please check the other answers on StackOverflow, there is a dozen of question asking the exact same thing.
Your issue is that you mix RC1 and RC2 libraries. This won't work! All of stack libraries (ASP.NET/MVC/EF/Identity) have to be 1.0.0-rc2-final, not 1.0.0-rc2-* or rc1. Read the annoncements, they have all the breaking changes in them.
Often outdated package name is an issue (i.e. Microsoft.AspNet.Mvc is outdated and you have to use Microsoft.AspNetCore.Mvc, as the first one will drag old dependencies.
Also some of your other dependencies (i.e. Swashbuckle.Swagger etc.) may still reference old rc1 libraries. They all need to be upgraded to the latest rc2 builds.
The error message you are getting is because two assemblies with different name are referenced and both have the same extension method in the same namespace so the compiler doesn't know which one to choose.

How can I read version of project in dotnet core (formerly asp.net mvc6)

how can I read assembly version information for my project, the value which in this case comes from the from project.json, and read that in my ASP.net core Controller and pass it to the view?
You can use Razor to get this right from the View and bypass the Controller.
<b>Version</b> #(
Assembly.GetAssembly(typeof(HomeController))
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion
)
To get your application version, as it exists in project.json, you would write:
string appVersion = Assembly.
GetEntryAssembly().
GetCustomAttribute<AssemblyInformationalVersionAttribute>().
InformationalVersion;
Additionally, if you want to know which version of .net core your app is running on you can do this:
....
string dotNetRuntimeVersion = typeof(RuntimeEnvironment)
.GetTypeInfo()
.Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
You may need to add these units to your using for the above runtime version snippet:
using Microsoft.DotNet.InternalAbstractions;
using System.Reflection;
You can get the AssemblyInformationalVersionAttribute from your project's assembly and then pass it to the view.
Here's how to get that attribute: https://github.com/aspnet/dnx/blob/dev/src/Microsoft.Dnx.Host/RuntimeEnvironment.cs#L35-L44
In an early beta version you could add constructor to your controller with parameter IApplicationEnvironment. this param have a property with Version name
public HomeController(IApplicationEnvironment appEnvironment) {
this.appEnvironment = appEnvironment;
}
(No longer works in ASP.net core 1.0)

Using Kentico API from LINQPad is throwing an exception

I am trying to call Kentico API from LINQPad, but getting the following exception:
[AbstractProvider.GetProvider]: The object type 'cms.document' is missing the provider type configuration
My code is:
void Main()
{
var pages = DocumentHelper.GetDocuments("CMS.MenuItem").Path("/", PathTypeEnum.Children);
pages.Dump();
}
Note: I tested the code from Visual Studio, it works, but not from LINQPad.
The problem is that during the initial discovery Kentico looks only at the following paths:
AppDomain.CurrentDomain.BaseDirectory
AppDomain.CurrentDomain.RelativeSearchPath
Which in case of LINQPad are C:\Program Files (x86)\LINQPad4\ and null. Therefore the providers do not get resolved.
I've tried running the code in a new AppDomain but it doesn't seem to work in LINQPad. I suggest submitting this to Kentico as an idea or an issue.
A workaround to this would be copying the LINQPad executable to a location of Kentico DLLs - e.g. C:\inetpub\wwwroot\Kentico82\Lib. That works just fine.
Update (thx to Joe Albahari):
If you wrap your code in this:
var appDomain = Util.CreateAppDomain ("AD", null, new AppDomainSetup
{
PrivateBinPath = #"C:\inetpub\wwwroot\Kentico82\CMS\bin",
});
appDomain.DoCallBack(() => { /* your code */ });
you'll be able to execute it. However, you can't Dump() it to the output window. But you can write it to a text file for example. If you experience the following error:
FileNotFoundException: Could not load file or assembly 'LINQPad, Version=1.0.0.0, Culture=neutral, PublicKeyToken=21353812cd2a2db5' or one of its dependencies. The system cannot find the file specified.
Go to Edit -> Preferences -> Advanced -> Run each query in its own process and turn it off.

Can I use a regular System.dll in a Compact Framework project?

In my test Winforms app (in which I'm targeting .NET 3.5, to simulate the Windows CE / Compact Framework 3.5 app that this is a first-line test for as much as possible), I added some JSON.NET code to deserialize json returned from WebAPI methods:
try
{
const string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
MessageBox.Show(string.Format("Content from HttpWebRequest is {0}", s));
var arr = JsonConvert.DeserializeObject<JArray>(s);
int i = 1;
foreach (JObject obj in arr)
{
var id = (string)obj["Id"];
var accountId = (double)obj["AccountId"];
var departmentName = (string)obj["DeptName"];
MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
i++;
}
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
...This runs fine in the .NET 3.5 Winforms app, but when I copied it over to the Windows CE-targetted app, the code wouldn't run, with the following errors spilling forth:
The type 'System.ComponentModel.IBindingList' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
The type 'System.ComponentModel.ITypedList' is defined in an assembly that is not referenced. You must add a reference to assembly 'System, Version=2.0.0.0...
The type 'System.ComponentModel.INotifyPropertyChanging' is defined in an assembly that is not referenced....
The type 'System.ComponentModel.ICustomTypeDescriptor' is defined in an assembly...
The type 'System.ComponentModel.INotifyPropertyChanged' ...
The type 'System.Uri'...
I saw that in the Winforms (testbed) app, I'm using version 2.0.0.0 of the "regular" (or "deluxe" when compared to CF) System.dll. In the Windows CE app, though, I was using the CF flavor of version 3.5 found here:
C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5\WindowsCE\System.dll
I tried using version 2 CF from C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE\System.dll, but that failed, too - so it's apparently not really the version (3.5 vs. 2.0), but the "flavor" (CF vs "deluxe"/regular System.dll).
SO...I replaced the CF-flavored System.dll[s] with the one successfully used by the Winforms test app, explicitly the one in C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll (I have no System.dll in C:\Windows\Microsoft.NET\Framework\v3.5, anyway).
It no longer gives those same err msgs as listed above, but there is another compile error that may (or may not be) related (Can I give an emulator more disk space?) now.
Whether it is or not (related), it brings up the intriguing question: Will using a regular System.dll in a Windows CE project cause a problem?
If it will -- or there's a good chance that it will -- cause a problem, since it was apparently the JSON.NET code that required the change to an "off-colored" version of System.dll, is there a CF-ready / CF-specific version of JSON.NET? Will I have to create my own CF-targeted version of an assembly from the JSON.NET source?
UPDATE
In the JSON.NET readme, it states:
For a Compact Framework 3.5 build download Json.NET 3.5.
Which I assumed meant the .DLL in \Json50r7\Bin\Net35
Am I wrong about that?
UPDATE 2
When I attempt to open Newtonsoft.Json.Net35.sln in Windows 2008, with the intention of creating a CE-targeted assembly, it doesn't allow me, saying, "The selected file is a solution file, but was created by a newer version of this appllication and cannot be opened*"
It also says in the JSON.NET read me:
Microsoft stopped support for the Compact Framework in Visual Studio 2010.
...so I don't think I can open it in a newer version of VS2008 and create a CF-friendly DLL, either...
UPDATE 3
Looking for a "Compact" folder in the download from http://json.codeplex.com/releases/view/113546, but I see no such folder:
It's not the "Portable" folder, is it?
As Robert Harvey suggests, the tile and the actual question here don't match. You probably should fix that.
The answer to the current title "Can I use a regular System.dll in a Compact Framework Project?" is absolutely, definitively no. You cannot mix and match. Full-framework assemblies cannot run under the Compact Framework. There's no way to make them work. Period. Stop trying this.
The answer to "How do I use JSON.NET is a Compact Framework Project" is that you should go to the JSON.NET project site on GitHub and specifically look at the last JSON.NET 3.5 release (it was Release 8) and download it. Inside that zip file is a folder named "Compact" that contains an assembly named Newtonsoft.Json.Compact.dll. Add a reference to that DLL to your Compact Framework 3.5 project.