Referencing external assemblies from PowerShell snap-in - c#

I'm developing a custom PowerShell snap-in, which references another project in the solution.
When I try to debug the snap-in (following [these instructions][1]), the assembly fails to load and my cmdlet fails with the message "Could not load file or Assembly..."
How do you instruct PowerShell on how to locate assemblies, or how do you specify where are located the assemblies needed by the snap-in?
I'd prefer to avoid registering the assemblies in the GAC, at least during development.

Not sure of the exact behaviour, but I would try and make use of fuslogvw to see exactly where the runtime is looking for the problematic assemblies. That would give you a clue as to how to get them to be copied into the correct place on build. This post by Scott Hanselman is quite useful, and this is the official documentation.
If you find the solution, please add an answer, as this must be a common scenario.

SOLUTION (Posting it here as suggested by one of the comments to my question)
My problem was rather specific, as I'm developing on a 64 bits server machine, but I'm posting the solution in case it could help someone else as well.
Using fuslogvw as suggested, I saw that the dependent assembly was being searched using the machine.config file under C:\Windows\Microsoft.NET\Framework64 and then the binding failed; launching the project with "start without debugging", instead, the machine.config file under C:\Windows\Microsoft.NET\Framework was taken (notice the missing 64 at the end).
I thought that the problem could be due to the image format, and infact the dependent assembly was being compiled with x86 as CPU target; I changed it to "Any CPU" and now the assembly is loaded correctly.

Related

Identifying problematic dependencies in C++/CLI project

My application compiles fine, but I get the following runtime error:
System.IO.FileNotFoundException was unhandled
HResult=-2147024770
Message=Could not load file or assembly {Wrapper} or one of its dependencies. The specified module could not be found.
The reference to Wrapper in the calling Application looks correct. The Wrapper dll exists in the correct location.
This project used to build and run on someone else's system, I saw it demonstrated several times. That person/computer is no longer available. Some paths of some dependencies have changed since the last time it was successfully built and run, I have fixed all compile errors related to this.
Just to clarify my project structure:
Digraph G
{
App [ label = "My C# Application"]
Wrapper [ label = "C++/CLI Wrapper"]
Lib [ label = "C++ Library"]
Dll [ label = "My helper C# DLL"]
CDep [ label = "Series of deep C++ dependencies managed \n by CMake for Lib, hard coded relative paths for Wrapper."]
App->Wrapper->Lib->CDep;
App->Dll->Wrapper->CDep;
}
Wrapper is a C++/CLI wrapper around a C++ library. The error is triggered when we try to load a class in the Application that has a using statement for the Wrapper.
Wrapper does have a lot of dependencies, but the error message does not indicate which dependency is problematic. This is a large, complicated system, most of which is built by other teams. The C++ components use CMake to get all the dependencies correct, but CMake does not natively support C#.
I tried using fuslogvw to find the binding error, but it showed me absolutely nothing until I changed settings to include all binds, and then it only showed successful binds.
http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.100).aspx
The paths are long, but not over 256 characters.
I had a warning in the compile for Dll (see graph above):
Warning 1 There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "{cli_wrapper.dll}", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
In Configuration Manager, the Dll is building for Platform "Any CPU" and Wrapper is building for "x64". I changed the dll to x64. I still get the runtime error.
Could not load file or assembly or one of its dependencies
Performed a clean, deleted build directory contents. No change.
Re-opened Visual Studio. No change.
Tried changing assembly name, default namespace, and project name to match. No change.
Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format
I believe we have to compile for 64 bit. We are dependant on a 64 bit C++ library.
Could not load file or assembly ... The parameter is incorrect
I am local administrator.
How to enable assembly bind failure logging (Fusion) in .NET
Tried the registry settings, but they appear to just be fuslogvw settings. No improvement in available log data.
Many other similar questions had ASP or service install specific answers.
I found the problem. There was more than one version of the library available to me, and I was using the include files from one version and the compiled library of the other. Dependancy Walker was key to finding which library had the problem, and if Aschratt had posted that as an answer rather than as a comment I would have accepted his answer.
I had the same error with a similar project earlier this week. First, when using C++/CLI, "Any CPU" doesn't exist. I had to build both for x86 to get through things.
Also, though my wrapper's dependencies were satisfied, it's the wrapper's exception that is caught by the CLR so it claims that the wrapper is missing a dependency. I was actually missing a dependency for the C++ DLL my wrapper wrapped (in my case, it was just a matter of forgetting to drop SDL2.dll and OpenAL32.dll in my new "Release" configuration output folder... I'd previously only worked with the Debug configuration where I'd already dropped those DLLs.
If you're positive you've got your wrapper's dependencies worked out, I'd recommend using Dependency Walker to check out the native DLL's dependencies. You could use Assembly.GetReferencedAssemblies with an outside script/program to double-check your wrapper as well (or ILSpy: http://ilspy.net/).
Last but not least, take a look at this: http://www.codeproject.com/Articles/442784/Best-gotchas-of-Cplusplus-CLI. He details the first two recommendations I made as well as some others.
Good luck!
One alternate root cause I've been running into quite a bit later, is that the application I'm working on uses impersonation, and the impersonated user does not have permissions to the GAC or to the folder that some dlls are in. You need to either give that user permissions, or change the way you do impersonation to load the dependencies before impersonation starts.

How to Fix, Could not load file or assembly 'XXX' or one of its dependencies. Strong name signature could not be verified

Currently I have the source of System.Web.Mvc assembly. Building is fine. But at runtime it throws,
Could not load file or assembly 'System.Web.Mvc' or one of its dependencies.
Strong name signature could not be verified. The assembly may have been tampered
with, or it was delay signed but not fully signed with the correct private key.
(Exception from HRESULT: 0x80131045)
How can I debug it? I am using windows 7.
It seems that you are trying to debug the ASP.NET MVC source code and have built your own version of the System.Web.Mvc assembly. The problem with this approach is that you cannot sign it with the official keys. This means that any third party component that you might be using and which depends on System.Web.Mvc should also be recompiled against your own version. Take for example Razor. It also depends on System.Web.Mvc. Did you recompile that as well?
Personally I find it extremely difficult to be building your own version of System.Web.Mvc. In practice I debug the source code by using the publicly available PDB symbols. So I would advice you NOT to be compiling your own version but work with the official one. Take a look at this post: https://stackoverflow.com/a/13610108/29407
Just resolved the same problem:
build solution with asp.net source code (mine is called 'Runtime.sln')
unload tests folder from it
open properties of System.Web.Mvc project
uncheck Sign on Signing tab
try to rebuild solution
uncheck Sign on Signing tab for each failed project
I also removed strong name details from InternalsVisibleTo attributes in AssemblyInfo.cs but it might needed only if you want to build test projects as well.
After that I added System.Web.Mvc, System.Web.WebPages.Deployment and System.Web.WebPages projects as existing projects to my new solution and now I can debug their source code.
I've had this before and removing the reference to System.Web.Mvc and re-adding it worked.
I also did a clean and re-build which worked.
Hope that helps
In the AssemblyInfo.cs file there will be a line
[assembly: System.Reflection.AssemblyDelaySign(true)], if this is removed the GAC issue will be resolved
I tried profiling my application using Visual studio performance profiler and got this error for third party assembly. I did a clean and re-build solution and it worked.
Add this line to your config file: < hostingEnvironment shadowCopyBinAssemblies="false" / >

Updating GAC dlls

I got a DLL registered in the GAC which has a bug in it (v4.2.0).
I've therefore fixed that bug, updated the file version only (v4.2.1) (keeping the assembly version, v4.2.0) and built a new MSI package.
The problem is that the DLL is not installed in the GAC. I verified this by right-clicking on the DLL in C:\Windows\Microsoft.NET\assembly\GAC_MSIL\MyDLL\v4.0_4.2.0.0__2269313d92725976 and checked the file version, which is still v4.2.0 There are also no other folders created under C:\Windows\Microsoft.NET\assembly\GAC_MSIL\MyDLL.
But! If I uninstall the first version and then install the new DLL it get's installed OK in the GAC.
Am I approaching this the wrong way? Our applications are set to use specific versions, so just creating assembly version v4.3.0 and install it in the GAC wont work.
Update
I've found the article about publisher policies ( http://support.microsoft.com/kb/891030) and are attempting that instead. I've generated the policy assembly. But Visual Studio crashes when I try to add it to the setup project =(
I've also tried to add it as a content file to the primary project (and then add content files to GAC). But then it complains on the assembly not being signed.
So I'm still stuck.
Updating the [AssemblyFileVersion] for a bug fix is usually the right approach, although it gets iffy if you do so for an assembly in the GAC. You run the risk of breaking another app that also uses the assembly and unintentionally depends on the buggy behavior to function correctly. An unintentional mistake like renaming a public method is of course always a good way to break an app, the road to DLL Hell is paved with many good intentions that turned out bad.
The GAC however only pays attention to [AssemblyVersion] and ignores the file version. To get the updated assembly to replace the existing one you do have to remove the old one first. This is intentional, preventing accidental replacement.
A <bindingRedirect> in the .config file of the app you want to repair will be a lot easier to get going than a publisher policy.
I believe this has to do with what parameters of a .NET assembly the GAC uses to give it a unique identifier. If the assembly version is one of those uniqueness parameters, but file version is not, that may explain your symptoms. Specifically this pertains to the GACs need for a strong named assembly
This link says as much
http://msdn.microsoft.com/en-us/library/wd40t7ad.aspx

Strongly signed assemblies

I am not a .NET developer, so there might be some basic things I don't know.
I have some experience coding in C#, but now I have a question. One of my projects (A) references another ptoject (B), with "local copy" set. When B.dll is in the same location as A.exe everything works. But when B.dll is put in a common directory from PATH it doesn't work.
One of my coworkers said he thought I should make B strongly signed. Is he correct? Is that why one would strongly sign an assembly?
I read a bit about in in the internet but all I saw was about security... If so, how does one sign an assembly and what consequences does it have? Please note that I am using VS2003 .Net 1.1.
Edit: Thank you all very much for your answers, however all the links you provided refer to later versions of VS and .NET which have some sort of Signing tab in project properties. Does anybody know (or give a link )how to strongly name the assembly in VS2003 .Net1.1?
Your problem is not related to assembly signing in the first place. .NET does not use the PATH environment variable to load assemblies. The process is actually a bit more complex and you best read all details in MSDN (also see steps 1 to 4):
How the Runtime Locates Assemblies
In your case it might be the best to install the shared assembly to the GAC. Installing to the GAC requires that your assembly has a strong name, so this is probably what your co-worker referred to.
Update:
As you asked specifically about strong-naming a .NET 1.1 assembly I'd suggest checking out the following question:
How to give a .NET 1.1 dll a strong name in VS2003
I think that what your co-worker might be referring to is "Strong Naming" an Assembly.
Strong Naming is what enables you to deploy your assembly to the GAC.
Once it is in the GAC, then any application using that assembly can always locate it. Path's are irrelevant and that is the preferred way to have shared assemblies deployed.
To strong name an assembly, you can use the sn.exe tool that comes with Visual Studio to generate a strong name and then sign the assembly using the keyfile that is generated via sn.exe.
EDIT : Example of how to use SN.exe to strong name an assembly is here
Also, I think you should understand how the runtime loads assemblies. From MSDN
The runtime uses the following steps to resolve an assembly reference:
Determines the correct assembly version by examining applicable
configuration files, including the application configuration file,
publisher policy file, and machine configuration file.
If the configuration file is located on a remote machine, the
runtime must locate and download the application configuration file
first.
Checks whether the assembly name has been bound to before and, if so,
uses the previously loaded assembly.
Checks the global assembly cache. If the assembly is found there, the
runtime uses this assembly.
Probes for the assembly using the following steps: If configuration
and publisher policy do not affect the original reference and if the
bind request was created using the Assembly.LoadFrom method, the
runtime checks for location hints.
If a codebase is found in the configuration files, the runtime checks
only this location. If this probe fails, the runtime determines that
the binding request failed and no other probing occurs.
Probes for the assembly using the heuristics described in the probing
section. If the assembly is not found after probing, the runtime
requests the Windows Installer to provide the assembly. This acts as
an install-on-demand feature.
Note: There is no version checking for assemblies without strong
names, nor does the runtime check in the global assembly cache for
assemblies without strong names.
The right way to do this is by deploying your .dll in the GAC. http://support.microsoft.com/kb/815808
what is the reason you want to put the B.dll in a common directory? is it because it can be used by a another program? if so adding it to the GAC is the best option. See this one
As 0xA3 already mentioned you should read the article at MSDN. But what is not so good explained in the article is the usage of the AssemblyResolve event. It will be thrown if the Framework didn't find the assembly at any place, givin you a chance to start a search on yourself (maybe in your common folder) and return the needed assembly.
An example on how to use this, can be found in my question here.

Assembly references won't resolve properly on our build server

We code in C# using VS2008 SP1. We have a server that runs Team System Server 2008 which we use for source control, tasks etc. The server is also our build machine for Team Build. This has been working just fine for a long time. Untill now. We get these error messages when trying to build one of our projects that has a reference to one external assembly (this happens both via Team Build, and when logging on physically and doing a regular build via Visual Studio):
C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets
: warning MSB3246: Resolved file has a
bad image, no metadata, or is
otherwise inaccessible. Could not load
file or assembly 'C:\Program
Files\Syncfusion\Essential
Studio\7.1.0.21\Assemblies\3.5\Syncfusion.XlsIO.Base.dll'
or one of its dependencies. The module
was expected to contain an assembly
manifest.
C:\Program
Files\MSBuild\Microsoft\VisualStudio\v9.0\ReportingServices\Microsoft.ReportingServices.targets(24,2):
error MSB4062: The
"Microsoft.Reporting.RdlCompile" task
could not be loaded from the assembly
Microsoft.ReportViewer.Common,
Version=9.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a. Could
not load file or assembly
'Microsoft.ReportViewer.Common,
Version=9.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or
one of its dependencies. The module
was expected to contain an assembly
manifest. Confirm that the
declaration is correct, and that the
assembly and all its dependencies are
available.
The referenced component
'Syncfusion.XlsIO.Base' could not be
found.
These errors are for one project with one problematic assembly reference. When I try to build the entire solution there are of course many more errors because of this one. And there are two other projects that has the same problem with other assembly references. I have a list of the referenced assemblies that VS can't seem to resolve:
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.WinForms
Syncfusion.Compression.Base
Syncfusion.Core
Syncfusion.XlsIO.Base
The Syncfusion assemblies are from a 3rd-party component package. The other two are related to the Microsoft ReportViewer component.
The references has been added via the Add Reference window, in the .NET tab, so I don't think there is anything suspicious about that. In the properties window for the assembly reference, there is no value in Culture, Description, Path, Runtime Version or Strong Name. Version says 0.0.0.0 and Resolved is False. I guess it is pretty obvious that VS cant resolve the reference. My question is why??? I've scratched my head a lot over this one. This only occurs on the server, the solution builds just fine on both my machine, and my coworkers machine. The assembly reference properties are fine on our machines.
I have tried uninstalling the 3rd-party component (on the server of course), and then reinstalling it again. Didn't help. I tried to repair the VS2008 installation. Didn't help. Tried to retrieve an earlier version from source control (that I know has buildt on the server before), and I got the same error messages. I have checked file permissions, and everything appears to be in order. I am running out of ideas...
How do I solve this?
Update 16.02.2009:
I have tried to compare ildasm output of the dll on my pc and on the server (see the comment I wrote about that), and there is one small difference in a line that to me appears to be a comment. I must admit that I don't understand why there is a difference at all, so maybe someone could explain that to me?
I also tried running a virus scan on the server. Didn't help. Tried to remove the reference and then readd it by browsing to the dll on disk. Didn't work.
Update 17.03.2009:
I've found the solution! The culprit was the TruPrevent module of Panda Antivirus. After disabling the module, everything works! =)
I discovered this with the help of fuslogvw.exe and the log it generated. Googled the result, and stumbled upon this blog entry.. Hope this can help somebody else to.
Almost certainly the problem is environmental - not source related.
Some ideas ...
(i) Try disabling your anti-virus/anti-malware tools - I've seen cases where these tools (particularly Trend Micro Antivirus, for some reason) can keep a DLL file locked after (during?) scanning, interfering with compilers.
(ii) Check your PATH environment variable. Even in these modern days, the PATH variable is used to resolve some things - if this is messed up (too long, maximum length is 2048 characters IIRC) then things can be odd.
(iii) You've checked File permissions - have you checked permissions in the registry? For example, SyncFusion installs its license key in both the User and Machine hives - if the build server can't read one or the other, could cause issues.
Good luck!
It could also be that the referenced assemblies are in the GAC on the dev machine, but not on the build machine. Get it out of the GAC, into your source repository, and reference it by path.
We've had the same problem, turns out the C drive was full (only had 28MB).
Freeing space resolved the issue, even though the build happens on D.
Do you see any differences between ildasm of this file
'C:\Program Files\Syncfusion\Essential Studio\7.1.0.21\Assemblies\3.5\Syncfusion.XlsIO.Base.dll'
on your machine versus on the server?
My suspicion is that the user that the build process is under does not have access to the folder that your 3rd party control is in. Since this functions properly on your machines, it is almost certainly user/permission specific.
Your 3rd party dll may depend on unmanaged dlls. Often it's because a specific version of the VC++ Runtime Dlls are missing.
Open the Dll with the Dependency Walker http://www.dependencywalker.com/ on your server and check for missing references.
Not sure if this'll help in your case, but I did have something similar before where a dll apparently got unregistered somehow, and running regsvr32 on the dll did the trick.

Categories

Resources