UWP LaunchFullTrustProcessForCurrentAppAsync - EXE file not found - c#

We are creating a UWP application which is intended for Side loading only.
At various times this application needs to reboot the PC (it's desktop only), to do this we intend to use LaunchFullTrustProcessForCurrentAppAsync() to call a simple external EXE which uses Process.Start("shutdown") to reboot the PC.
We have created the EXE called RebootPC.exe and on it's own it works fine.
We now include it in our UWP project:
First we add the desktop and rescap namespaces to our project and we also add rescap to our IgnorableNamspaces
xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp uap5 rescap">
Then, we then modify the Extension section to include our EXE, we know we cannot put the EXE in our project root as C# compiler removes it so we have put it in a sub folder (in this case \Assets). We also set the EXE's type to 'Content' and 'Copy always' in the Solution explorer
<desktop:Extension Category="windows.fullTrustProcess" Executable="Assets\RebootPC.exe">
<desktop:FullTrustProcess>
<desktop:ParameterGroup GroupId="rebooter" Parameters=""/>
</desktop:FullTrustProcess>
</desktop:Extension>
finally in the manifest we add rescap to the Capabilities section - we know it has to be first in the list otherwise you get a manifest error when packaging
<Capabilities>
<rescap:Capability Name="runFullTrust"/>
<Capability Name="internetClient" />
<DeviceCapability Name="bluetooth" />
<DeviceCapability Name="radios" />
OK, so the manifest is changed. We now go to our C# code:
In that we perform the following:
if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0))
{
try
{
await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
When we build and run the project in Visual Studio it seems to work fine, under the intended circumstances the PC will reboot as intended.
The problem comes when we try to package it for installation on other PCs. We use Store->Create App Packages (remember this application is for side loading only).
The creation of the package works fine and we can install it on other PCs with no problem. The problem is that when we run the Application and it comes time to run the external EXE to reboot the PC a command window opens but we get an exception saying "System can't find c:\users.......\Assets\RebootPC.exe"
So, even though the packaging is done without error and even though we have set the properties of RebootPC.exe to 'Content' and 'Copy always' it is either not being included in the package or not being installed along with the App?
So, does anyone know how we can check if it is being included in the package? and if so how we can check if and where it is being installed on the target machine? or has anyone else had this issue and found the solution?
This has had us baffled for days and is driving us crazy!!!
UPDATE: I think the issue may not be that RebootPC.exe can't be found but rather shutdown.exe - If this is the case then it's a bit of a school boy error!!!
Anyway, I will sort this and see if that fixes the issue
I will leave the rest of the question up as it might provide useful information for others

As Mentioned in the official sample the exe file has to in the Appx folder of your project
Make sure the RebootPC.exe was copied to the Appx folder -
UWP\bin\x64\Release\AppX if not rebuild the solution or copy it
manually.
https://github.com/Microsoft/DesktopBridgeToUWP-Samples/tree/master/Samples/AppServiceBridgeSample#builddeploy-and-run-the-sample

try
{
await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("rebooter");
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

Related

Could not load file or assembly 'Microsoft.Management.Infrastructure

I am writing a multi-platform c# command line application using .NET Core 3.1 that will need to work as a single executable. I am using Visual Studio 2019 (16.5.4). My OS is Windows 10.0.18363.778 and I intentionally did NOT install Powershell 7. I tested this first bit on my Windows and WSL Ubuntu and it worked until I added Powershell SDK 7. After I installed Microsoft.Powershell.SDK 7.0.0 and when Ì set the project file as follows, everything runs nicely and I can validate I am using PS7 and not Windows PS.
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
However, when I add the runtimeIdentifier in PropertyGroup:
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
Build successfully completes without errors. However when I ran (both debuging or standalone) and application hits Powershell.Invoke, it throws a FileNotFound Exception with message:
"Could not load file or assembly 'Microsoft.Management.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified."
1) What am I missing to get all depdendencies in the executable directory?
2) When I add the following to create the single executable
<PublishSingleFile>true</PublishSingleFile>
<UseAppHost>true</UseAppHost>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
It does not get created. I get the executable if I use:
"dotnet publish -r win-x64 -c Debug"
but nothing happens when I run it. (This step used to work fine before PS7)
Is there anthing else I need to do to get the single executable running?
I did some research and figured the following:
Answer 1: There is no Runtime identifer specific Microsoft.Management.Infrastructure.dll files in the runtimes directory. Either Powershell SDK does not support all runtime identifers or its a bug. I will take it to github.
Answer 2: Running the single Executable file is misleading. My expected result was creation of a log file which is created in the application directory. I figured that when the single exe is run, it actually unzips ALL the files to the temp directory and runs the application from there (not the single executable) and hence the log file is not created where the single file executabe is.
To resolve your problem, you have to add this reference to your project. It take me 1 day to found this.
<PackageReference Include="NETStandard.Library" Version="1.6.1" />

Prompt for source of container: WixAttachedContainer Problem

Good day everyone,
While working with Wix I am having a hard time solving the following error message:
Prompt for source of container: WixAttachedContainer
The scenario:
We have a setup project with the default Wix template that acts as a bundle for several packages, called MyBundle.exe.
We have a managed bootstrapper application wix exe with WPF and C# that acts as a standalone installer, but this needs to be included in the bundle stated above, called MyApp.exe.
MyApp.exe gets installed correctly when installing MyBundle.exe.
When uninstalling MyBundle.exe and having a DetectCondition to uninstall MyApp.exe. MyApp.exe gets removed correctly.
The Problem:
There is a scenario where MyBundle.exe will get removed but has to leave MyApp.exe installed behind.
After removing MyBundle.exe, and trying to remove MyApp.exe I get the following error in the log:
Prompt for source of container: WixAttachedContainer, path: "Path_To_EXE"
If I install MyApp.exe as a standalone and uninstall it, everything works just fine.
If I install MyBundle.exe (MyApp.exe included in MyBundle.exe) and uninstall MyApp.exe before removing MyBundle.exe, this works fine as well.
I have read the logs of MyApp.exe where the error comes up and I found that MyApp.exe is trying to reach the cache folder of MyBundle.exe
Prompt for source of container: WixAttachedContainer, path: C:\ProgramData\Package Cache\{Bundle_GUID}\Dependencies\MyApp.exe
But at this point, that folder is no more on the system.
The configuration of the ExePackage in MyBundle.exe is as follows:
<ExePackage Id="MyApp_Package"
Description="MyApp Package"
DisplayName="MyApp Package"
SourceFile="My_Path_To_Package"
Compressed="yes"
Permanent="yes"
PerMachine="yes"
Vital="yes"
Cache="yes">
</ExePackage>
I have tried several combinations of the tags Permanent, Cache, but still to no effect.
I have tried already hooking up to the ResolveSource method inside the C# code on MyApp.exe following instructions like this:
Managed Bootstrapper Application "Failed to resolve source for file" but to no success.
Can any of you point me in the correct direction?
UPDATE: Both MyBundle.exe and MyApp.exe, as well as the msi included are signed using signtool.
Thanks.
Take a look at "insignia"
https://wixtoolset.org/documentation/manual/v3/overview/insignia.html
It's not enough to just use signtool to sign the boostrapper EXE. The bundle inside it needs to be signed also.

ASP.NET Core 1.0 on IIS error 502.5 - Error Code 0x80004005

I just updated my server (Windows 2012R2) to .NET Core 1.0 RTM Windows Hosting pack from the previous .NET Core 1.0 RC2. My app works on my PC without any issues but the server keeps showing:
HTTP Error 502.5 - Process Failure
Common causes of this issue:
The application process failed to start
The application process started but then stopped
The application process started but failed to listen on the configured port
It previously worked with the RC2 version. Don't know what could go wrong.
This is all event viewer says:
Failed to start process with the commandline 'dotnet .\MyWebApp.dll'. Error code = '0x80004005'.
the worst part is that app logs are empty! I mean those stdout_xxxxxxxxx.log files are completely empty and all have 0 byte size.
What should I do?? How can I know the cause of error when it's not logged??
I was able to fix it by running
"C:\Program Files\dotnet\dotnet.exe" "C:\fullpath\PROJECT.dll"
on the command prompt, which gave me a much more meaningful error:
"The specified framework 'Microsoft.NETCore.App', version '1.0.1' was
not found.
- Check application dependencies and target a framework version installed at:
C:\Program Files\dotnet\shared\Microsoft.NETCore.App
- The following versions are installed:
1.0.0
- Alternatively, install the framework version '1.0.1'.
As you can see, I had the wrong NET Core version installed on my server. I was able to run my application after uninstalling the previous version 1.0.0 and installing the correct version 1.0.1.
I had the same problem, in my case it was insufficient permission of the user identity of my Application Pool, on Publishing to IIS page of asp.net doc, there is a couple of reason listed for this error:
If you published a self-contained application, confirm that you didn’t set a platform in buildOptions of project.json that conflicts with the publishing RID. For example, do not specify a platform of x86 and publish with an RID of win81-x64 (dotnet publish -c Release -r win81-x64). The project will publish without warning or error but fail with the above logged exceptions on the server.
Check the processPath attribute on the <aspNetCore> element in web.config to confirm that it is dotnet for a portable application or .\my_application.exe for a self-contained application.
For a portable application, dotnet.exe might not be accessible via the PATH settings. Confirm that C:\Program Files\dotnet\ exists in the System PATH settings.
For a portable application, dotnet.exe might not be accessible for the user identity of the Application Pool. Confirm that the AppPool user identity has access to the C:\Program Files\dotnet directory.
Confirm that you have correctly referenced the IIS Integration middleware by calling the .UseIISIntegration() method of the application’s WebHostBuilder().
If you are using the .UseUrls() extension method when self-hosting with Kestrel, confirm that it is positioned before the .UseIISIntegration() extension method on WebHostBuilder(). .UseIISIntegration() must set the Url for the reverse-proxy when running Kestrel behind IIS and not have its value overridden by .UseUrls().
In my case it was the fourth reason, I changed it by right clicking my app pool, and in advanced setting under Process Model, I set the Identity to a user with enough permission:
I got this working with a hard reset of IIS (I had only just installed the hosting package).
Turns out that just pressing 'Restart' in IIS Manager isn't enough. I just had to open a command prompt and type 'iisreset'
So I got a new server, this time it's Windows 2008R2 and my app works fine.
I can't say for sure what the problem was with the old server but I have one idea.
So because I previously compiled the app without any platform in mind it gave me the dll version which only works if the target host has .Net Core Windows Hosting package installed. In my case it was installed and that was fine.
After the app didn't work I decieded to compile it as a console app with win7-x64 as runtime. This time the moment I ran the exe of my app on the server, it crashed with an error about a missing dll:
The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing
That dll is from Universal C Runtime that's included in the Visual C++ Redistributable for Visual Studio 2015.
I tried to install that package (both x64 & x86) but it failed each time (don't know why) on Windows Server 2012 R2.
But when I tried to install them in the new server, Windows Server 2008 R2, they successfully installed. That might have been the reason behind it, but still can't say for sure.
I had the same issue when publishing the web app.
If anybody still has this problem fixed it by changing {AppName}.runtimeconfig.json
{
"runtimeOptions": {
"framework": {
"name": "Microsoft.NETCore.App",
"version": "1.1.2"
},
"configProperties": {
"System.GC.Server": true
}
}
}
Change the version from "version": "1.1.2" to "version": "1.1.1" and everythign worked ok
I had the same problem.
To find out the exact source of it I switched on logging in
web.config file:
<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />
and created logs subfolder in MyWebService root folder.
After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.
Had the same issue and all solutions didn't work. Found this gem and thought I'd pass along if it helps someone else. Install on Server 2012 R2 getting the DLL missing error, try to reinstall VS C++ 2015 and get an error. Fix is to do the following:
Seems the file
C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu has problems being installed.
Open admin command prompt do:
c:
mkdir tmp
mkdir tmp\tmp
move "C:\ProgramData\Package Cache\...\packages\Patch\x64\Windows8.1-KB2999226-x64.msu" c:\tmp
expand -F:* c:\tmp\Windows8.1-KB2999226-x64.msu c:\tmp\tmp
dism /online /add-package /packagepath:c:\tmp\tmp\Windows8.1-KB2999226-x64.cab
NOTE: replace the "..." with the correct folder name. After this reinstall the VS C++ 2015 package.
I had a similar issue, and to quote Sherlock Holmes:
"when you have eliminated the impossible, whatever remains, however improbable, must be the truth?"
I checked if the .NET framework I was targeting was installed on the server, and it turns out it wasn't. I installed the 4.6.2 .NET Framework and it worked.
I got this issue on my production server after my VS project was automatically upgraded to .NET Core 1.1.2.
I simply installed the 1.1.2 .net core runtime from here on my production server: https://www.microsoft.com/net/download/core#/runtime
SOLVED I just ran through the same issue today while deploying to AZURE. Then I tried the same for local IIS, got the same issue. As I am new to .net CORE, struggled few hour before I actually solved it.
In our solution, after I publish to IIS, I observed my web.confile file, specially below line <aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" arguments="-argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" stdoutLogEnabled="false" />
In our deployment folder the generated web.config looks like:<aspNetCore processPath="dotnet" arguments=".\Yodlee.dll -argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
Now PLEASE try changing the above configuration in visual studio solution to<aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" forwardWindowsAuthToken="false" stdoutLogEnabled="false" />
In our new deployment folder the generated web.config looks like:<aspNetCore processPath="dotnet" arguments=".\Yodlee.dll" forwardWindowsAuthToken="false" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
And This SOLVED my problem, Hope it help.
I had the same problem when I updated my dev machine to Core 1.0.1, but forgot to update the server.
I was getting HTTP Error 502.5 while trying to publish my .NET Core 2.0 API to AWS EB, and solved it by adding the following code to the .csproj:
<PropertyGroup>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
I had a same issue . I changed application pool identity to network service account . Then I explicitly set the path to dotnet.exe in the web.config for the application to work properly as #danielyewright said in his github comment . It works after set the path.
Thanks
Sharing that in my case this error was because i forgot to update project.json with:
"buildOptions": {
"emitEntryPoint": true
}
I had the same error in question, with the same issues as described by VSG24 in Proposed answer - nasty error message when typing 'dotnet' into CMD:
The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing
I solved this by manually installing the following 2 updates on Windows Server 2012 R2 (and the pre-requisites and all the other updates linked - read the installation instructions carefully on the Microsoft website):
KB2919355
KB2999226
Hope this helps someone.
I faced the same issue when I tried to publish Debug version of my web application. This set of files didn't contain the file web.config with the proper value of attribute processPath.
I took this file from Release version, value was assigned to the path to my exe file.
<aspNetCore processPath=".\My.Web.App.exe" ... />
In my case was problem with Net Core version installed on server.
I just install the same version as on my development machine and everything is OK :-)
Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.
So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.
Copy it back to the location if it is no longer there.
If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )
This worked for me instantly, and I repeated it across application multiple servers.
I needed to install the latest .net Core version found here.
No need to restart the site or server
I solved it by adding "edit permission" to the application of the site, mapped to the physical directory and then selected the windows user that could have access to this root folder. (private network).
In my case, after installing AspNetCore.2.0.6.RuntimePackageStore_x64.exe and DotNetCore.2.0.6-WindowsHosting.exe , I need to restart server to make it worked without 502 bad gateway and proxy error.
UPDATE:
There is a way you could use it without restart:
https://stackoverflow.com/a/50808634/3634867
Open command prompt with Administrator credentials
Type following command and hit enter
> IISRESET
OR
Open Visual Studio 2017 with Administrator credentials
Type following command in Package Manager Console and hit enter
PM> IISRESET
PM> IISRESET
Attempting stop...
Internet services successfully stopped
Attempting start...
Internet services successfully restarted
I had this problem aswell (The error occurred both on VS 15 and 17). However on VS15 it returned a CONNECTION_REFUSED error and on VS17 it returned ASP.NET Core 1.0 on IIS error 502.5.
FIX
Navigate to your project directory and locate the hidden folder .vs (it's located in the projects folder dir). (Remember to show hidden files/folders)
Close VS
Delete .vs-folder
Start VS as admin (.vs-folder will be recreated by VS)
For me it was that the connectionString in Startup.cs was null in:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
and it was null because the application was not looking into appsettings.json for the connection string.
Had to change Program.cs to:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json").Build())
.UseStartup<Startup>().Build();
I have no idea why this worked for me, but I am using Windows Authentication and I had this bit of code on my BuildWebHost in Program.cs:
.UseStartup<Startup>()
.UseHttpSys(options =>
{
options.Authentication.Schemes =
AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
options.Authentication.AllowAnonymous = false;
})
.Build();
After removing the .UserHttpSys bit, it now works, and I can still authenticate as a domain user.
BuildWebHost now looks like
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
I was getting the same error, and found out the problem was that during the publish to Azure, my web.config file was modified so this following line ended up like this:
<aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" arguments="-argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" stdoutLogEnabled="false" startupTimeLimit="3600" requestTimeout="23:00:00" />
The problem for Production are the contents of the arguments: "-argFile IISExeLauncherArgs.txt"
It seems like this issue is going to be addressed in the next .NET Core SDK (currently in preview), but for now, the workaround is to add this block to the .csproj file:
<Target Name="bug_242_workaround" AfterTargets="_TransformWebConfig">
<Exec Command="powershell "(Get-Content '$(PublishDir)Web.config').replace(' -argFile IISExeLauncherArgs.txt', '') | Set-Content '$(PublishDir)Web.config'"" />
</Target>
This will modify the web.config and remove the problematic part for publishing.
Reference: https://github.com/aspnet/websdk/issues/242
Hope it helps.
Worked for me after changing the publishing configuration.
For me it was caused by having different versions of .Net Core installed. I matched my dev and production server and it worked.
I had a similar issue (Asp.Net Core 2.x) that was caused by trying to run a 32-bit asp.net core app in IIS on a 64-bit windows server. The root cause was that the web.config that is auto-generated (if your project does not explicitly include one, which asp.net core projects do not by default) does not contain the full path to the dotnet executable. When you install the hosting bundle on a 64 bit machine it will install the 64 and 32 bit versions of dotnet, but the path will resolve by default to 64 bit and your 32 bit asp.net core app will fail to load. In your browser you may see a 502.5 error and if you look the server event log you might see error code 0x80004005. If you try to run dotnet.exe from a command prompt to load your asp.net core application dll on that server you may see an error like "BadImageFormatException" or "attempt was made to load a program with an incorrect format". The fix that worked for me was to add a web.config to my project (and deployment) and in that web.config set the full path to the 32-bit version of dotnet.exe.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="C:\Program Files (x86)\dotnet\dotnet.exe" arguments=".\My32BitAspNetCoreApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</location>
</configuration>
I got the same problem and the reason in my case was that the EF core was trying to read connection string from appsettings.development.json file. I opened it and found the connection string was commented.
//{
// "ConnectionStrings": {
// "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
// "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
// }
//}
I then uncommitted them like below and the problem solved:
{
"ConnectionStrings": {
"DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
"IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
}
}

.NET executables do not work after overwritten with new versions

I faced very strange behaviour - after I overwrite .NET exectables with new versions from network drive it cannot start.
When try to start from Windows Explorer it shows me following error:
[Window Title]
C:\Programs\zzz\clients.net\zzzNet.exe
[Content]
C:\Programs\zzz\clients.net\zzzNet.exe
The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail.
I tried to execute following commands:
SxsTrace Trace -logfile:SxsTrace.etl
SxStrace Parse -logfile:SxSTrace.etl -outfile:SxSTrace.txt
And got following result:
=================
Begin Activation Context Generation.
Input Parameter:
Flags = 0
ProcessorArchitecture = AMD64
CultureFallBacks = en-US;en;ru-RU;ru
ManifestPath = C:\Programs\zzz\clients.net\zzzNet.exe
AssemblyDirectory = C:\Programs\zzz\clients.net\
Application Config File = C:\Programs\zzz\clients.net\zzzNet.exe.Config
-----------------
INFO: Parsing Application Config File C:\Programs\zzz\clients.net\zzzNet.exe.Config.
INFO: Parsing Manifest File C:\Programs\zzz\clients.net\zzzNet.exe.
INFO: Manifest Definition Identity is (null).
ERROR: Line 0: XML Syntax error.
ERROR: Activation Context generation failed.
End Activation Context Generation.
It is quite simple .NET application (1 exe + 8 dll files). It was built for .NET 3.5 Client Profile.
I not defined any special "manifest" there. Just clicked "New Windows Forms Project" in Visual Studio and developed it.
Also app.config does not contain anything special - only primitive standard settings - appSettings and userSettings sections.
On PC where I developed it all is perfectly works. Problems only began when I copy these binaries to this particular VM and try to start.
Also please note - these executables were not installed in GAC or such, I just copied them into a folder on VM and started. And when it was 1st time all was working fine.
So, the problem pattern is following:
Copy .NET execuatbles to new VM (it is Win 7 x64), run it, all is working fine. Close it.
Build new version of .NET execuatbles on host PC, copy new .NET execuatbles to VM (with files overwriting).
Try to start - got mentioned problem.
After some shaman-style actions (like OS reboot, etc) it begin to work but why that happened at all?!
Why replacing .NET executables with new versions is causing SUCH HUGE PROBLEMS?!
Also the BIG QUESTION - is there any special procedure to replace .NET executables to keep them working? Because it is a new app development, I do not want lost so much time on every new executables installation. :-\
Could you please help? Because it looks completely weird!
Thank you in adance.
PS. I checked all VS projects - all they have PlatformTarget=AnyCPU. Also in run-time I can see ProcessType=MSIL (I show this info in AboutBox for application). So, there is no mix of x86/x64 binaries.
It seems that was related to mapped network drive behavior.
When I copied new files from network drive folder it copied wrong files - a strange random mess of new files and older ones (which were there before I updated them on VM host).
The scenario to make it working:
on VM: delete all files in a folder on network drive
on VM host: copy new files into a folder which is mapped as network drive on VM
on VM: copy files into target folder
on VM: run application - it works now
Weird thing. I remember I have seen something similar with Windows Explorer on Windows 2008 behaviour when copying updated win32 binaries.

Powershell, Service Bus For Windows Server Programmatically: Command found, module could not be loaded

From C# code I'm trying to retrieve all the namespaces from powershell... (Later more complex things, like creating namespaces)
PowerShell ps = PowerShell.Create();
ps.AddCommand("Import-Module").AddArgument("ServiceBus").Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Above code gives the following exception:
The 'Get-SBNamespace' command was found in the module 'ServiceBus',
but the module could not be loaded. For more information, run
'Import-Module ServiceBus'.
Does anyone know how to solve this error?
CURRENT STATUS: after some debugging I've found that no modules are loaded by default in the PowerShell object. Using the code:
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[]{#"serviceBus"});
PowerShell ps = PowerShell.Create(iss);
doesn't work to load the service bus module. Also the code:
ps.AddCommand("Import-Module").AddParameter("-Name", "serviceBus").Invoke();
doesn't work to import the service bus module. Running Visual Studio in administrator mode also doesn't make a difference
Thanks in advance
You didn't say which version of Visual Studio you're using. If it's VS 2012, when you tried the x64 platform target did you make sure that "Prefer 32-bit" was not checked? Even if it was not checked try checking it, saving the project configuration, clearing it and saving again - this worked for me on another project.
UPDATE
It's been suggested elsewhere that there's a bug in VS2012 that shows "Prefer 32-bit" as greyed-out and unchecked when it's actually active. I'm running Update 2 and I don't see that. But it sounds like you might be. I suggest you edit the .csproj file directly.
Whilst "Platform Target" is set at "Any CPU", in Solution Explorer, right-click on the Project name (or, with go to the PROJECT menu) and select "Unload Project". Project files will close and Solution Explorer will display project name (unavailable) > The project file was unloaded:
Right-click on the Project name again and select "Edit project name.csproj". The file is XML and mostly comprises PropertyGroup and ItemGroup elements. In a console project, the first PropertyGroup usually contains a Platform element which should read AnyCPU if you followed my instructions above. The next two PropertyGroups are normally for Debug and Release configurations. If you've added another configuration, it will have its own PropertyGroup. In each of these, look for an element which reads:
<Prefer32Bit>true</Prefer32Bit>
What you should have is an element which reads:
<Prefer32Bit>false</Prefer32Bit>
Either change it or insert it (in each configuration ProjectGroup), save the file and close it. Back in Solution Explorer, right-click the project and select "Reload Project". Let me know if that solves it. You can confirm your PowerShell is now running 64-bit by get the result of
[System.IntPtr]::Size
e.g.
ps.AddScript("[System.IntPtr]::Size");
which will be 4 in an x86 process and 8 in an x64 process.
Which my project set up like this, I was able to load ServiceBus using:
ps.AddCommand("Import-Module").AddArgument("ServiceBus");
Hopefully, you will, too.
I don't have ServiceBus installed so I can't verify exactly what you've tried but
ps.AddCommand("Import-Module").AddArgument("ActiveDirectory").Invoke();
worked for me, so your original syntax looks good.
Just to test for failure, I tried:
ps.AddCommand("Import-Module").AddArgument("CheeseDirectory");
ps.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
var importResult = ps.Invoke();
foreach (PSObject result in importResult)
{
Console.WriteLine(result);
}
and got
The specified module 'CheeseDirectory' was not loaded because no valid
module file was found in any module directory.
Have you tried similar?
Do you take care of your Assembly target in your C# program (x86 versus X64). The module may exist in one target, not in the other. PowerShell exists in both.
Seems you're trying to import some modules and execute the cmdlet or function inside the module, right?
So I think you could try the following code:
PowerShell ps = PowerShell.Create();
Assembly ass = Assembly.LoadFile(#"yourServiceBus.dll");
ps.AddCommand("Import-Module").AddParameter("Assembly", ass).Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Hope this could help.

Categories