Using Kentico API from LINQPad is throwing an exception - linqpad

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.

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();

Registering .net assembly for COM succeeds with regasm but fails using RegistrationServices.RegisterAssembly

This is one of the strangest issue I have encountered.
There is a .net assembly, which is exposed to COM.
If you register it with regasm /codebase my.dll - it is sucessfully registered, and can be used.
However, if you register it from code using RegistrationServices.RegisterAssembly() :
[...]
RegistrationServices regSvcs = new RegistrationServices();
Assembly assembly = Assembly.LoadFrom(path);
// must call this before overriding registry hives to prevent binding failures on exported types during RegisterAssembly
assembly.GetExportedTypes();
using (RegistryHarvester registryHarvester = new RegistryHarvester(true))
{
// ******** this throws *********
regSvcs.RegisterAssembly(assembly, AssemblyRegistrationFlags.SetCodeBase);
}
Then it throws exception:
Could not load file or assembly 'Infragistics2.Win.UltraWinTree.v9.2, Version=9.2.20092.2083,
Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb' or one of its dependencies.
Provider type not defined. (Exception from HRESULT: 0x80090017)
This error has very little resource on the net, and looks like related to some security(?) cryptography(?) feature.
After long-long hours, I figured out what causes this (but don't know why):
If there is a public class with a public constructor in the assembly with a parameter UltraTree (from the referenced assembly 'Infragistics2.Win.UltraWinTree.v9.2'), then you cannot register from code, but with regasm only.
When I changed the have a public function Init(UltraTree tree), then it works, I can register from code. So:
// regasm: OK / RegistrationServices.RegisterAssembly(): exception
public class Foo
{
public Foo(UltraWinTree tree) { .. }
}
Foo foo = new Foo(_tree);
-------------- vs --------------
// regasm: OK / RegistrationServices.RegisterAssembly(): OK
public class Foo
{
public Foo() {}
public void Init(UltraWinTree tree) { .. }
}
Foo foo = new Foo();
foo.Init(_tree);
So I could workaround by passing UltraWinTree in a new Init() function instead of constructor, but this is not nice, and I want to know the reason, what the heck is going on?
Anyone has any idea? Thanks.
PS:
Okay, but why we want to register from code? As we use Wix to create installer, which uses heat.exe to harvest registry entries (which are added during asm registration), so heat.exe does assembly registration from code.
I've been dealing with this for years so this is the only answer you need to read:
Heat calls regasm /regfile. So does InstallShield when you tell it to. If you read this page:
https://learn.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool
There's a very important caveat in the remarks section.
You can use the /regfile option to generate a .reg file that contains
the registry entries instead of making the changes directly to the
registry. You can update the registry on a computer by importing the
.reg file with the Registry Editor tool (Regedit.exe). The .reg file
does not contain any registry updates that can be made by user-defined
register functions. The /regfile option only emits registry entries
for managed classes. This option does not emit entries for TypeLibIDs
or InterfaceIDs.
So what to do? Use Heat to generate most of the metadata. Then on a clean machine, (snapshot VM best) us a registry snapshot and compare tool such as InCntrl3 or InstallWatch Pro and sniff out what additional meta regasm writes to the registry. Finally massage that into your Wxs code.
Then on a cleam machine test the install. The result should work and not require any custom actions in the install.

Assembly name was changed after deployment in core web api application

I am using VS 2019 to develop core.net web Api. I am trying to read the all methods and Parameters inside my controller. I am using Repository pattern to develop API.
Below is the code from my repository.
var method = MethodBase.GetCurrentMethod();
_log4net.Info("Assembly Name : " + Assembly.GetCallingAssembly().FullName);
_log4net.Info("Method Name : " + method.Name);
_log4net.Info("Repository Name :" + method.ReflectedType.FullName);
var result =
((System.Reflection.TypeInfo)Assembly.GetCallingAssembly().GetTypes().Where(type
=> type.FullName.Contains("AsmeController")).FirstOrDefault()).DeclaredMethods;
_log4net.Info(result);
Log's:
In Debug Mode:
After deployment in IIS
This code is working as expected and returns the list of Method Info in Debug mode and not working and return Null in Release mode even after deployed in IIS.
As i observed using logs, Assembly name was changing Demo.dll to “ Assembly Name : Anonymously Hosted DynamicMethods Assembly “ after deployment.
Please give me suggestions to solve this problem.
For the work around i am directly reading the application dll, Instead of reading current assembly. So that i can able to access the all info from there.
string assemblyFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location + "\\Demo.dll");
Assembly testAssembly = Assembly.LoadFile(assemblyFile);
var result = ((TypeInfo)testAssembly.GetTypes().Where(type => type.FullName.Contains("AsmeController")).FirstOrDefault()).DeclaredMethods;

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.

How to load a dll in an AppDomain with different NET version

I have some third party assembly which was build using Net 2.0. Although I can of course reference that assembly in net 4, running the app results in all kinds of strange errors.
So I though loading it in a separate application domain will fix the problem but it does not. I assume it is still executed using the Net 4 runtime. Is there any way to force execution of an application domain in a different net version ?
I use CreateInstanceFromAndUnwrap and than call the proxy.
Thanks for any help
Joe
You can use the supportedRuntime configuration element to set the CLR version of an AppDomain. If you do not want to add this to your app.config, you can add a second .config file that will be used during the construction of the new AppDomain. Have a look at AppDomainSetup.ConfigurationFile for more info.
Create AppDomain. And Create DomainManager:MarshalByRef object in new domain.
DomainManager Load Assembly To created(new) domain.
AppDomainSetup ads = new AppDomainSetup();
AppDomain managerAD = AppDomain.CreateDomain("AD1", null, ads);
Assembly asm = managerAD.Load(typeof(DomainManager).Assembly.FullName);
string typeName = typeof(DomainManager).FullName;
DomainManager manager = (DomainManager)managerAD.CreateInstanceAndUnwrap(asm.GetName().Name,
typeName);
public class DomainManager : MarshalByRefObject
{
public void GetAppDomain(string assemblyFileName)
{
Assembly asm2 = Assembly.LoadFrom(assemblyFileName);
Type neededType = asm2.GetType(<paste type>);
object instance = Activator.CreateInstance(procType);
}