Can't load executable from memory, VB.NET assembly - windows

So basically, I'm trying to load exe file into memory and run its Main function.
It's coded in VB.NET and it has a Namespace called ConApp and a Module called MyModule
So far I've tried this in powershell:
$path = [path to exe]
$bytes = [IO.File]::ReadAllBytes($path)
[System.Reflection.Assembly]::Load($bytes)
And this is the output:
GAC Version Location
--- ------- --------
False v4.0.30319
So I assume it's loaded here? And then when I try to call it like this:
[ConApp.MyModule]::Main()
I get this error:
Unable to find type [ConApp.MyModule].
At line:1 char:1
+ [ConApp.MyModule]::Main()
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (ConApp.MyModule:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
Any ideas on how could I achieve the execution from memory? Thanks in advance.

The answer was actually simple, I wasn't calling the assemblyname first.
So it should've been:
[ConApp.ConApp.MyModule]::Main()
instead of:
[ConApp.MyModule]::Main()

Related

Unable to import powershell module remotley

I'm importing module remotely. module located in C:\Users\Ananth\Documents\WindowsPowerShell\Modules\MSOnline\. I am able to view the module remotely. while importing getting below error. if try to execute in powershell application module importing successfully in both bit versions.
Import-Module : Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. An attempt was made to
load a program with an incorrect format.
At line:1 char:1
+ Import-Module MSOnline
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Import-Module], BadImageFormatException
+ FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand
Could not load file or assembly 'file:///C:\Users\CAC-Dev\Documents\WindowsPowerShell\Modules\MSOnline\
1.1.183.66\Microsoft.Online.Administration.Automation.PSModule.dll'

Firefox automation using Selenium Powershell ISE, Windows 10

PS ISE 5.1
Windows 10
Has anyone had luck with Firefox automation using Selenium with PS ISE? Below, I have two different examples below where in each method I am unsuccessfully able to open the firefox browser, let alone navigate anywhere. I'll explain more under each method.
Method 1) Install of Selenium PS Module:
Source:
https://github.com/adamdriscoll/selenium-powershell
In the following method, I installed a module that is supposed to be a powershell wrapper for C# Selenium. The error is triggered from module itself. I have placed the error message in the comment block below. How would I find which "assembly" is needed, that contains this "type"?
cls
$website = "https://www.google.com/"
Import-Module "C:\Program Files\WindowsPowerShell\Modules\Selenium\3.0.1\Selenium.psm1" -Function *
$Driver = Start-SeFirefox
Enter-SeUrl $website -Driver $Driver
Cannot find the type for custom attribute 'ValidateURIAttribute'. Make sure that the assembly that contains this type is loaded.
At C:\Program Files\WindowsPowerShell\Modules\Selenium\3.0.1\Selenium.psm1:403
char:9
+ [ValidateURIAttribute()]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ([ValidateURIAttribute()]:AttributeAst) [], RuntimeException
+ FullyQualifiedErrorId : CustomAttributeTypeNotFound
Cannot find the type for custom attribute 'ValidateURIAttribute'. Make sure that the assembly that contains this type is loaded.
At C:\Program Files\WindowsPowerShell\Modules\Selenium\3.0.1\Selenium.psm1:580
char:9
+ [ValidateURIAttribute()]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ([ValidateURIAttribute()]:AttributeAst) [], RuntimeException
+ FullyQualifiedErrorId : CustomAttributeTypeNotFound
Method 2) Downloaded geckodriver.exe and WebDriver.dll
Sources:
https://www.reddit.com/.../getting_started_in_web.../
https://adamtheautomator.com/selenium-powershell/
https://www.selenium.dev/downloads/
In this example, I have downloaded geckodriver.exe and WebDriver.dll, placed them both in the same folder and added the folder to my system's environment variables. I've added a comment block below showing the error message. I commented out the Add-type call as it gave me different errors and it didn't load the webdriver, so I used the loadform call instead. Which file is the error referencing to? The code is using the DLL file; I know this because FireFoxOptions line of code works and the code opens the exe, so that clearly is found as well. There are only 2 files and both are working to some degree. The line that's not working is
$Firefoxdriver = New-Object OpenQA.Selenium.Firefox.Firefoxdriver($Firefoxoptions)
This would be a function from the dll file; can it not find the EXE at this point, even though the code had already executed the EXE file? Regarding the GAC = false, I read that not all DLL's can be registered with the system because some don't have all the necessary functions; I'm not sure if that's required or not.
cls
$PathToFolder = 'F:\Programs\Selenium\WorkingDirectory'
if ($env:Path -notcontains ";$PathToFolder" ) {
$env:Path += ";$PathToFolder"
}
[System.Reflection.Assembly]::LoadFrom("{0}\\WebDriver.dll" -f $PathToFolder)
#Add-Type -Path "$($PathToFolder)\WebDriver.dll"
$Firefoxoptions = New-Object OpenQA.Selenium.Firefox.Firefoxoptions
#$Firefoxoptions.AddArgument('-headless') ##### <----- Used to make the window not appear, or 'headless' - comment out to have a normal window show.
$Firefoxoptions.AcceptInsecureCertificates = $True
$Firefoxdriver = New-Object OpenQA.Selenium.Firefox.Firefoxdriver($Firefoxoptions)
pause
GAC Version Location
--- ------- --------
False v4.0.30319 F:\Programs\Selenium\WorkingDirectory\WebDriver.dll
New-Object : Exception calling ".ctor" with "1" argument(s): "Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0,
Culture=neutral,
PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified."
At F:\Programs\PowerShell\SeleniumFireFox.ps1:15 char:18
+ ... foxdriver = New-Object OpenQA.Selenium.Firefox.Firefoxdriver($Firefox ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: 🙂) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Press Enter to continue...:
Here is a snippet of the Java code that works in Eclipse. I wonder if what I'm missing in the code above is whatever the System.setProperty is doing in Java?
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","F:\\Programs\\Selenium\\GeckoDriver\\geckodriver-v0.29.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = "https://www.google.com/";
String expectedTitle = "Google";
String actualTitle = "";
// launch Fire fox and direct it to the Base URL
driver.get(baseUrl);
Additional notes (partly just venting): The reason I'm trying to do this in powershell is because I know powershell more; it's generally easier for me to write code. In my example, I am trying to combine two pieces of working code together; one of them is the Firefox automation in Java and the other is an api call in Powershell. My first attempt was to port the powershell code into Java, but I don't know Java well and the littlest things were frustrating me. In Java, I couldn't figure out how to make the API call which was so simple in powershell; simply using Invoke-RestMethod. The answers I found online to do that were saying that it's actually complex in Java because I would need to manage cookies and do all sorts of stuff. I couldn't even find consistent date functions; different answers were importing different date function modules and it made combining code difficult. So, I decided to try and port my Java code to Powershell. The code I'm using works for other people, at least according to the answers I've found online, but do not work for me.
It looks like you are not importing the full module, is this on purpose? If Selenium is in your modules path, you should be able to run:
Import-Module Selenium
If that's not possible, most modules have a .psd1 file that should be the import target, and may load other .psm1 files, nested modules, assemblies, etc. Your github link recommends the following:
Import-Module "{FullPath}\selenium-powershell\Selenium.psd1"
At the very least, you are missing a type definition - these are usually included in .dll or .xml files with the module, and can be seen with get-module once imported under ExportedTypeFiles:
(Get-Module ActiveDirectory).ExportedTypeFiles
C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\ActiveDirectory\ActiveDirectory.Types.ps1xml

Exception calling ".ctor" while connecting to an Oracle database (ODP.net)

This is my code to connect to an Oracle database:
[Reflection.Assembly]::LoadFile("E:\oracle\product\11.2.0\ODP.NET\bin\2.x\Oracle.DataAccess.dll")
$constr = "User Id=system;Password=password;Data Source=SERVER\INST"
$conn= New-Object Oracle.DataAccess.Client.OracleConnection($constr)
First line is working fine. I can see the assembly is loading and GAC is true.
Up to the second line there is no error.
But when it reaches the 3rd line, I am getting this error:
New-Object : Exception calling ".ctor" with "1" argument(s): "The type initializer for 'Oracle.DataAccess.Client.Oracle Connection' threw an exception.
$conn= New-Object <<<< Oracle.DataAccess.Client.OracleConnection($constr)
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
"
Can anybody advise me on this.
Powershell version is 2.
Update
PS I:\> [Reflection.Assembly]::LoadFile("E:\oracle\product\11.2.0\ODP.NET\bin\2.x\Oracle.DataAccess.dll")
GAC Version Location
--- ------- --------
True v2.0.50727 C:\Windows\assembly\GAC_64\Oracle.DataAccess\2.112.3.0__89b483f429c47342\Oracle.DataAccess.dll
Oracle.DataAccess.dll is architecture specific. That means that you have to make sure the PowerShell process and the Oracle.DataAccess.dll assembly have the same bits (32 or 64).
May I suggest you to use the platform-independent Oracle managed driver? It works a lot better than the Oracle client specific Oracle.DataAccess.
Also see my answer here.

How to resolve "Install-Package : The current environment doesn't have a solution open."

I have a solution having 1 project.
Open Package Manager Console, run Install-Package MSBuildTasks
But it gave me an error below:
Install-Package : The current environment doesn't have a solution open.
At line:1 char:16
+ Install-Package <<<< MSBuildTasks
+ CategoryInfo : InvalidOperation: (:) [Install-Package], InvalidOperationExcep
tion
+ FullyQualifiedErrorId : NuGetNoActiveSolution,NuGet.PowerShell.Commands.InstallPackage
Command
I don't understand why it comes. Kindly suggest me waiting for reply. Thanks
I usually get this error because I created or opened a project (.csproj or other) that doesn't have a saved solution (.sln) associated with it.
If you go to File->Save All it should offer to save the solution somewhere. Save it and that makes the error go away for me.

How do I Enable Migrations in the Package Manager Console?

I'm trying to enable migrations in MVC4, Entity Framework 5.00, however when I input the command it throws the following error:
Cannot determine a valid start-up project. Using project 'EFMigrations' instead. Your configuration file and working directory may not be set as expected. Use the -StartUpProjectName parameter to set one explicitly. Use the -Verbose switch for more information.
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly 'file://\\s01\data\Documents\Visual Studio 2010\Projects\EFMigrations\packages\EntityFramework.5.0.0\tool
s\EntityFramework.PowerShell.Utility.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
At \\s01\data\Documents\Visual Studio 2010\Projects\EFMigrations\packages\EntityFramework.6.0.0-beta1\tools\EntityFramework.psm1:669 char:62
+ $utilityAssembly = [System.Reflection.Assembly]::LoadFrom <<<< ((Join-Path $ToolsPath EntityFramework.PowerShell.Utility.dll))
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At \\s01\data\Documents\Visual Studio 2010\Projects\EFMigrations\packages\EntityFramework.6.0.0-beta1\tools\EntityFramework.psm1:670 char:50
+ $dispatcher = $utilityAssembly.CreateInstance <<<< (
+ CategoryInfo : InvalidOperation: (CreateInstance:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'file://\\s01\data\Documents\Visual Studio 2010\Projects\EFMigrations\packages\EntityFramework.
5.0.0\tools\EntityFramework.PowerShell.dll' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)"
At \\s01\data\Documents\Visual Studio 2010\Projects\EFMigrations\packages\EntityFramework.6.0.0-beta1\tools\EntityFramework.psm1:698 char:31
+ $domain.CreateInstanceFrom <<<< (
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
any and all help would be appreciated.
Running migrations from a network path is unsupported.
EF Team Triage: The migrations commands require full trust to run. Because you are running from a network share it looks like you are running in a lower trust level. In the past we have made the decision that the migrations commands would require full trust because it reduces the complexity of the implementation.
http://entityframework.codeplex.com/workitem/856
This means you have to put your project on a local drive, then you'll be able to run migrations.
It turns out that #Stijn's answer is indeed correct, However it doesn't provide a solution to the problem, the solution is to simple copy and paste the entire project into your Hard Drive and the command will work

Resources