Input to console application in C# - c#

I created a dll file for my matlab program. I integrated it into C# console application now I have to call this console application from php. The user selects an image whose imagepath should be passed as input in the C# console application.
I checked the console application my defining an image path and it works fine how can I program it to accept input from php aplication so that I can call exec(exepath imgpath)in php. I have to pass the image path to the matlab dll file too. My Console application is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using shoesddl;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
namespace shoes_describe
{
class Program
{
static void Main(string[] args)
{
shoesddl.shoes_describe obj = new shoesddl.shoes_describe();
MWArray img= "C:/Users/adithi.a/Desktop/dressimages/T1k5aHXjNqXXc4MOI3_050416.jpg";
obj.shoes(img);
}
}
}
I need the imgpath i.e img in the above program from php. How can I achieve it?

use Command Line Parameters. Your method is accepting parameters in string[] args. You can pass the image path alongwith the exe name, from your PHP code.
> exepath imgpath
That imagepath would available at args[0]

Related

Using to get PS script name from a C# DLL? Getting "Object reference not set to an instance of an object."

ERROR:
Object reference not set to an instance of an object.
I'm trying to create a DLL that can get the Entrypoint application name that is written in Powershell.
The layout is very simple:
In Powershell I add the line
Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')
then I create the object
$value = New-Object PS_get_value.Stack
and call the C# method
$rtn = $value.Get_stack()
If the Get_stack() method returns a basic string like "Test" it works fine….
BUT if I try to use the .net Assembly.GetEntryAssembly().Location (which should return the full path to the calling (parent) app), I get the error above.
I am trying to get the full path (or at least the filename) of the application script that is running in Powershell. I plan on using that value to validate that the program (PS script) is the one that should be running. If there is a different way for the C# code to get it that's fine. BTW if I run a normal program it works. I do know that there is something about managed code base, I'm not sure what that is.
Thanks for any help or direction your can give.
Code Example:
PS:
Add-Type -Path ('C:\Users\Public\PS\DLL\get_value.dll')
$addNum = New-Object PS_get_value.Stack
$_rtnKey = $addNum.Get_stack()
Write-Host "RTNed Key Version 2: $_rtnKey"
C# (the DLL):
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
namespace PS_get_value
{
public class Stack{
public string Get_stack()
{
string _test_a = g_stack();
return _test_a;
}
public string g_stack()
{
return System.Reflection.Assembly.GetEntryAssembly().Location;
}
}
}
Give it a try by returning one of the following:
Assembly.GetExecutingAssembly().Location
or
Assembly.GetExecutingAssembly().CodeBase

Powershell addscript and invoke from C# not displaying result on command line

I've the below powershell script file
C:\user\deskptop\script1.ps1
The contents of the script is just the below:
get-process
i'm trying to create a C# console app to get the output of this script on console. When i execute the script outside C# it runs fine but when i execute it inside C# it doesn't produce anything. i'm trying use addscript and invoke.
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace InvokePowerShellScriptFrmCsharp1
{
class Program
{
static void Main(string[] args)
{
string script = #"C:\\Users\\Desktop\\script1.ps1";
PowerShell shell = PowerShell.Create();
shell.AddScript(script);
//shell.AddCommand("get-process");
shell.Invoke();
//shell.AddScript(script).Invoke();
Collection<PSObject> pSObjects = shell.Invoke();
foreach (PSObject p in pSObjects)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
}
When i execute the above i get the console with 'Press any key to continue' but no output before that.
but if i just try the below i get the result
shell.addcommand("get-process");
I want to get this working with addscript coz in the future if there is more than one command in the powershell script then i need to be able to execute the script from C# for desired results.
i've tried many links to try research but don't seem to be getting it to work.
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
https://www.reddit.com/r/csharp/comments/692mb1/running_powershell_scripts_in_c/
Could someone please let me know where i could be going wrong.
Try loading the script contents first, then passing that to the AddScript method:
string script = File.ReadAllText(#"C:\Scripts\script1.ps1");

Invoking PS script from C# code (Visual studio 2017)

I am trying to invoke my PS script from C# code.
**PS code. -- Try.ps1**
Write-Host "HelloHost"
Write-Debug "HelloDebug"
Write-Output "HelloOutput"
echo "tofile" > $PSScriptRoot/a.txt
**C# code**
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
namespace TryitOut
{
class Program
{
static void Main(string[] args)
{
using (PowerShell pshell = PowerShell.Create())
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
pshell.AddScript(path + "\\Try.ps1");
IAsyncResult result = pshell.BeginInvoke();
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for PS script to finish...");
Thread.Sleep(1000);
}
Console.WriteLine("Finished!");
Console.ReadKey();
}
}
}
}
When I run "Try.ps1" independently it runs ok and creates a.txt ans shows console output as expected.
But, it not getting invoked/executed via this C# code.
Question 1. can you please help, what I am doing wrong?
Q 2. How can I see PS console output when invoking Try.ps1 via C# code
Thank you for your time :).
Dealing with output from the PowerShell object is done in two ways. One is the direct return values of the Invoke call, and the other is via various streams. In both cases, you are responsible for dealing with the data; the console does not automatically output them as when you run a script in the standard PowerShell window. For example, to get the results from Write-Object, you can add the following to your C# code after your while loop:
foreach(PSObject pso in pshell.EndInvoke(result))
{
Console.WriteLine(pso);
}
This works fine for the simple strings in your example, but for complex objects with multiple properties, you need to pull the individual properties by name. For example:
string propValue = pso.Members["PropertyName"].Value.ToString();
Have a look at a previous answer of mine to see one way to convert complex objects to your own type: Dealing with CimObjects with PowerShell Inside C#
Handle the debug, information, verbose, etc like this:
foreach(DebugRecord dbr in pshell.Streams.Debug)
{
Console.WriteLine(dbr);
}
You will need to add this to the start of your script as well:
$DebugPreference = 'continue'

Read DLL content programmatically in C#

I am working on a small c# console application that will check my .net DLL and look for environment specific information from compiled dll.
Basically, I want to check c# Web published project and display any file contain production specific information developer forgot to update...
Issue: I am running into is when a developer switch between environment from Dev to test and test to prod. They forget to switch their environment value either in C# or web.config file.
Is there a way I can open individual DLL and extract the DLL content as a string using C# code and a free decompiler?
Try this:
using System;
using System.Linq;
using System.Reflection;
#if DEBUG
[assembly:AssemblyConfiguration("debug")]
#else
[assembly:AssemblyConfiguration("release")]
#endif
namespace ConsoleApp1
{
internal class Program
{
private static void Main()
{
// this should be the filename of your DLL
var filename = typeof(Program).Assembly.Location;
var assembly = Assembly.LoadFile(filename);
var data = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(AssemblyConfigurationAttribute));
if (data != null)
{
// this will be the argument to AssemblyConfigurationAttribute
var arg = data.ConstructorArguments.First().Value.ToString();
Console.WriteLine(arg);
}
}
}
}

Sikuli Integrator C#

I want to use SikuliIntegrator in C#.
I run VS as administrator, install SikuliIntegrator throught NuGet manager and want to test him on simple task.
Heres my code
using SikuliModule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SikuliTrainingNet
{
class Program
{
static void Main(string[] args)
{
string MyPicture = #"c:\111\Sik\MyPicture.png";
SikuliAction.Click(MyPicture);
}
}
}
after running code (and have prepared MyPicture on screen), all i get is exception "###FAILURE" any idea why?
I dont wanna use Sikuli4Net, becose its look like it work on web aps and I need just few simple clicks on desktop aplication.
I try sikuli in Java, and there it works with no problem. But I need to make my program in C#.
I Used This Code For Sikuli4Net in C#,It Was Working For Me First You need add the References please see this link for Reference
http://interviews.ga/angularjs/sikulic/
static void Main(string[] args)
{
APILauncher launch = new APILauncher(true);
Pattern image1 = new Pattern(#"C:\Users\Ramesh\Desktop\Images\userName.png");
Pattern image2 = new Pattern(#"C:\Users\Ramesh\Desktop\Images\password.png");
Pattern image3 = new Pattern(#"C:\Users\Ramesh\Desktop\Images\Login.png");
launch.Start();
IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Url = "http://gmail.com";
Screen scr = new Screen();
scr.Type(image1, "abc#gmail.com", KeyModifier.NONE);
scr.Type(image2, "12345", KeyModifier.NONE);
scr.Click(image3, true);
Console.ReadLine();
}
I used this code and it was working fine. First you should open the webpage on which you want to click and then give a path of the image(it should be a part of the webpage)
here is my code:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SikuliModule;
using OpenQA.Selenium;
namespace WordPressAutomation.DifferentTests
{
[TestClass]
public class Sikuli
{
[TestMethod]
public void TestMethod1()
{
driver.Initialize();
driver.instance.Navigate().GoToUrl("https://www.google.co.in");
SikuliAction.Click("E:/img.png");
}
}
}
To use SikuliInyegrator, you need to check the execution results in these files:
C:\SikuliExceptionLog.txt
C:\SikuliOutputLog.txt
Also you need to:
Have installed JRE7 or superior
Have environment variable PATH with the location of the bin folder
See installed in your “control panel > program and features> visual C++ 2010 Redistributable Package” at x86 and x64 bits according to your java JRE runtime platform. If not, then download and install the Redistributable Package form Microsoft site.

Categories