The method call in C# is like this -
public void GetKey()
{
WSManConnectionInfo connectioninfo = new WSManConnectionInfo();
var ss = new NetworkCredential("xxx.yyyy\\Administrator", "PassFail2Hehe");
connectioninfo.ComputerName = "<some IP Address>";
connectioninfo.Credential = new PSCredential(ss.UserName, ss.SecurePassword);
//Runspace runspace = RunspaceFactory.CreateRunspace(connectioninfo);
//runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
var re = ps.AddScript("Get-Service");
var results = re.Invoke();
}
}
I am using the NuGet package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0', as it is showing as the recommended package in Visual Studio 2019 for resolving the types of "Runspace", "PowerShell" etc.
However, I am getting the exception when the instance of "Runspace" or "PowerShell" is created. The exception is like this - "Common Language Runtime detected an invalid program."
I found this post and realized that I was getting the warning indeed for the NuGet package -
"Package 'Microsoft.PowerShell.5.ReferenceAssemblies 1.1.0' was restored using '.NETFramework,Version=v4.6.1,
.NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2,
.NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project."
As per suggested in the post, I installed Powershell Core 7.1.3, but the warning and exceptions were not resolved. Then I switched to ".Net Standard 2.0", since it the project was a class library, but nothing changed. The same warning message and exception.
How can I make remote PowerShell call using ".Net Core 5.0" (or ".Net Standard 2.0") ?
If you want to target .Net 5, the correct nuget package to use is Microsoft.PowerShell.SDK
Related
I have a .NETCore app which I am trying to add 7 zip functionality to.
Compiling gives this warning:
warning NU1701: Package 'SevenZipSharp 0.64.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project.
So I presume the project is .NETCore v5.0. Can I run SevenZipSharp in this project?
Running the app gives an error at the call to CompressFiles: SevenZip.SevenZipLibraryException: 'Can not load 7-zip library or internal COM error! Message: failed to load library.'
public void ZipQOB(string sevenZipDllPath, string zippedQobPath, string unzippedQobFiles)//List<string> sourceFiles)
{
// throw exception if paths passed in are null, does 7zipsharp throw exceptions in this case?
try
{
if (System.IO.File.Exists(sevenZipDllPath) && System.IO.Directory.Exists(zippedQobPath))// && System.IO.Directory.Exists(unzippedQOBFiles))
{
string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll");
//SevenZipCompressor.SetLibraryPath(sevenZipDllPath);
SevenZipCompressor.SetLibraryPath(path);
SevenZipCompressor sevenZipCompressor = new()
{
CompressionLevel = SevenZip.CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
string[] files = System.IO.Directory.GetFiles(unzippedQobFiles);
sevenZipCompressor.CompressFiles(zippedQobPath + #"\zip.QOB", files);
//System.IO.Path.ChangeExtension(zippedQobPath, ".QOB");
}
This question How do I use 7zip in a .NET Core app running on Linux? mentions a CLI wrapper ported from .NET Framework to .NET Core, but I can't find any details - is this something I would have to write and how?
I have already tried things suggested elsewhere, I altered the project build setting to:
Platform Target = AnyCPU,
ticked Prefer 32-bit
Should I just look at a different option as this page seems lists some stating .netcore compatible: https://github.com/topics/7zip?l=c%23
Many thanks for any help :)
Microsoft.SqlServer.SqlManagementObjects 161.47027.0
Microsoft.Data.SqlClient 5.0.0
After upgrading Microsoft.Data.SqlClient from 4.1.0 to 5.0.0
I got this error creating a ServerConnection object:
using Microsoft.SqlServer.Management.Common;
var serverConnection = new ServerConnection("localhost", "sa", "mypwd");
System.MissingMethodException: 'Method not found: 'Void
Microsoft.Data.SqlClient.SqlConnectionStringBuilder.set_Encrypt(Boolean)
It looks for a not implemented set_Encrypt method inside a Microsoft.Data.SqlClient.SqlConnectionStringBuilder
Does it mean Microsoft.SqlServer.SqlManagementObjects has not been updated yet to support Microsoft.Data.SqlClient 5.0.0?
If so do I need to wait for this update before I can upgrade Microsoft.Data.SqlClient 5.0.0 into my project?
You can also upgrade the ServerManagementObjects reference to 170.7.0-preview to resolve. Apparently the issue is with the smo library not the sqlclient library.
https://github.com/dotnet/SqlClient/issues/1702
Their code should be backwards compatible, but they need to be recompiled against MDS 5.0
Below is MyConnectionString"
"Server=tcp:xxx.xxxx.windows.net;Authentication=Active Directory Default;Database=TestDB;TrustServerCertificate=True;MultipleActiveResultSets=True;"
Had the error:
Method not found: 'Void Microsoft.Data.SqlClient.SqlConnectionStringBuilder.set_Encrypt(Boolean)'. When usingMicrosoft.Data.SqlClient 5.0.1.`
Fixed By: Downgraded the package Microsoft.Data.SqlClient to 4.1.0.and Using Microsoft.SqlServer.SqlManagementObjects 161.47021.0.
Fixed the error. Thank you for this post.
We had the same MissingMethodException when attempting the update of Microsoft.Data.SqlClient 4.1.0 to 5.0.0 in our system. Simply updating Microsoft.Data.SqlClient - independently of Microsoft.SqlServer.SqlManagementObjects - resulted in the exception when constructing the Microsoft.SqlServer.Management.Common.ServerConnection using SQL Server Authentication (not Windows Authentication).
This snippet causes the MissingMethodException if using Microsoft.Data.SqlClient 5.0.0 (worked in 4.1.0):
Return New ServerConnection With {
.ApplicationName = My.Application.Info.Title,
.ServerInstance = connectionParameters.DataSource,
.ConnectTimeout = connectionParameters.ConnectionTimeout,
.LoginSecure = False,
.Login = connectionParameters.UserName,
.Password = connectionParameters.Password
}
For now, we are holding off on updating Microsoft.Data.SqlClient, but went ahead with the Microsoft.SqlServer.SqlManagementObjects update (161.47021.0 to 161.47027.0). I am hopeful that an upcoming Microsoft.Data.SqlClient version will fix this issue.
As part of trying to test a NuGet package with a Console application, is it possible to have the console application get the latest version of said NuGet package programmatically, and then use said package to call various methods and what not? This is the flow that I'm trying to achieve...
A NuGet package is created locally (already done as part of a build process)
A console application installs this package
The same console application calls a few methods that are inside this package (if this uses reflection insdie the console app to achieve this it isn't an issue)
How can this be achieved? I've tried the following code using the NuGet.Core & NuGet.Protocol NuGet packages...
// exception thrown for trying to resolving newtonsoft
IPackageRepository packageRepository = new NuGet.LocalPackageRepository(directoryPath);
PackageManager pm = new PackageManager(packageRepository, GetExecutingAssemblyDirectory());
pm.InstallPackage("package_id", SemanticVersion.Parse("package_version"));
NuGet.Common.ILogger logger = new Logger();
IEnumerable<LocalPackageInfo> packageInfos = LocalFolderUtility.GetPackagesV2(directoryPath, logger);
foreach (LocalPackageInfo lpi in packageInfos)
{
// no obvious way to actually install the package
}
// never more than zero packages
var localRepo = new LocalPackageRepository(directoryPath);
var packages = localRepo.GetPackages();
if (packages?.Count() > 0)
{
var packageManager = new PackageManager(localRepo, GetExecutingAssemblyDirectory());
packageManager.InstallPackage(packages.ElementAt(0).Id);
}
I haven't been able to get any of those pieces of code to work. Is this actually possible? Would I have to look at using 2 Console apps (one to install into the other, which then does the calling of methods), and if so how would this be done?
As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.
I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.
Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.
Note:
I am using dotnetcore 2.0 with Visual Studio 2017
Error
I am getting following error.
return owinAppBuilder.Build,
Task>>(); TypeLoadException: Could not load type
'System.Security.Cryptography.DpapiDataProtector' from assembly
'System.Security, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
My attempt
app.UseOwin(setup => setup(next =>
{
var owinAppBuilder = new AppBuilder();
var aspNetCoreLifetime =
(IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
new AppProperties(owinAppBuilder.Properties)
{
OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
DefaultApp = next,
AppName = "test"
};
// Only required if CORS is used, configure it as you wish
var corsPolicy = new System.Web.Cors.CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = true
};
//corsPolicy.GetType()
// .GetProperty(nameof(corsPolicy.ExposedHeaders))
// .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());
owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
PublicClientId = "self";
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
Provider = new MyServiceProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true,
RefreshTokenProvider = new MyRefreshTokenProvider(),
};
owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
//owinAppBuilder.UseTus(context => new DefaultTusConfiguration
//{
// // Excluded for brevity, use the same configuration as you would normally do
//});
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:
Package 'Microsoft.Owin 3.1.0' was restored using
'.NETFramework,Version=v4.6.1' instead of the project target framework
'.NETCoreApp,Version=v2.0'. This package may not be fully compatible
with your project.
There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).
So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.
If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change
<TargetFramework>netcoreapp2.0</TargetFramework>
To some .NET framework version that supports .NET Standard 2.0, for example:
<TargetFramework>net47</TargetFramework>
Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.
That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.
Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).
The Microsoft.Owin components will not work on dotnet core 2.0, they only work on .NET 4.5+
I'm trying to write an application that communicates with Visual Studio Team Services, using the Nuget packages listed here.
The example code is directly from Microsoft's official documentation, on same same page the packages are listed, under "Pattern for use". My test code is in a console application, set to version 4.7 of the .net framework (compiled by Visual Studio 2017 15.2(26430.16) Release, but I don't think that matters). The code is identical to Microsoft's example, other than changing the connection url, project, and repo name.
The only Nuget package directly installed (about 30 others are installed as dependencies) is Microsoft.TeamFoundationServer.ExtendedClient.
Install-Package Microsoft.TeamFoundationServer.ExtendedClient
using System;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
namespace vssApiTest
{
class Program
{
const String c_collectionUri = "https://[[redacted]].visualstudio.com/DefaultCollection";
const String c_projectName = "Inspections";
const String c_repoName = "Src";
static void Main(string[] args)
{
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to VSTS
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;
}
}
}
On the line VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);, a TypeLoadException is thrown (at run-time) with the message:
Inheritance security rules violated by type:
'System.Net.Http.WebRequestHandler'. Derived types must either match
the security accessibility of the base type or be less accessible.
None of the Google search variants I've tried on this error message have returned anything helpful.
Am I doing something wrong, is the example code I'm following wrong, or is there some other issue going on?
The problem was due to a bug introduced in version 4.1.0 of the System.Net.Http Nuget package, as discussed here.
The solution was to update that Nuget package to the latest version (4.3.2 at this time, it may have been fixed in earlier versions also).