Is it possible to utilize Format-Table from C#? - c#

I'd like to have a C# console program which uses Format-Table to display objects. Here's a simple C# program:
using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
namespace PowerShellFormatTableTest
{
class Program
{
static void Main(string[] args)
{
var ps = PowerShell.Create()
.AddCommand("Get-Process")
.AddCommand("Format-Table");
foreach (var result in ps.Invoke())
{
// ...
}
}
}
}
The majority of the result elements are of course FormatEntryData objects.
Is there a way to print the Format-Table formatted output to the console?
The above example is just a trivial example. Normally, I'll be passing arbitrary objects

If you pipe the result from Format-Table to Out-String, then you should get the same output as a string-object. Try this:
var ps = PowerShell.Create()
.AddCommand("Get-Process")
.AddCommand("Format-Table")
.AddCommand("Out-String");

Here's the example updated to demonstrate Frode's suggestion:
using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
namespace PowerShellFormatTableTest
{
class Program
{
static void Main(string[] args)
{
var ps = PowerShell.Create()
.AddCommand("Get-Process")
.AddCommand("Format-Table")
.AddCommand("Out-String");
Console.WriteLine(ps.Invoke()[0]);
}
}
}

Related

I'm trying to use the c# file handle, but it's not available

c# File handler error.I can't find it.
use SafeFileHandle filehandle -> error
I tried to copy it, but it didn't work out well.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Win32.SafeHandles;
namespace test
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("검색할 경로를 입력하세요.");
string result1 = Console.ReadLine();
Console.WriteLine("파일 확장자를 입력하세요.");
string result2 = Console.ReadLine();
Filehandle file1 = new Filehandle();
file1.FileCheck(result1,result2);
}
}
You need to install the package in your project before you can use it.
dotnet add package Microsoft.Win32.SafeHandles

ironpython 'NoneType' object has no attribute 'mode'

enter image description hererecently,i need to watermark the pictures in our databases,we use C# mvc,so i want to use pythons2 PIL lib.honest,itis a bad idea,after my fit my PIL,_imaging ,a question still stop me.
Is it happend to someone?
enter image description here
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
public static void Main(string[] args)
{
Microsoft.Scripting.Hosting.ScriptRuntime runtimeobj = IronPython.Hosting.Python.CreateRuntime();
dynamic obj = runtimeobj.UseFile("H:\\vs2015setup_pros\\WebApplication3\\WebApplication3\\bin\\te.py");
Console.WriteLine(obj.f1());
Console.ReadKey();
}
}
}
pythoncode
# -*- coding:utf8 -*-
import sys
sys.path.append(r"H:\vs2015setup_pros\ConsoleApplication2\packages\Lib\site-packages")
sys.path.append(r"H:\vs2015setup_pros\ConsoleApplication2\packages\DynamicLanguageRuntime.1.2.2\lib\Lib")
sys.path.append(r"H:\vs2015setup_pros\ConsoleApplication2\packages\Lib")
#sys.path.append(r"H:\vs2015setup_pros\ConsoleApplication2\packages\DynamicLanguageRuntime.1.2.2\lib\net45\Lib")
#sys.path.append(r"H:\vs2015setup_pros\ConsoleApplication2\packages\DynamicLanguageRuntime.1.2.2\lib\Lib\site-packages\Pillow-6.1.0-py2.7-win32.egg")
#
s="asgrgergerasfefefas"
import time
import random
import math
from PIL import Image,ImageDraw
def f1():
print s.split("s")
print "tiememememfff",time.time()
print random.randint(100,200)
a=Image.open(r"C:\Users\Administrator\Desktop\11.png",)
print a.size
print 21313
newe = Image.new("RGB",(300,200),(100,100,100)) #when the code run to here in C#,it blocked
print 213131311313
newe.save(r"C:\Users\Administrator\Desktop\0000.png")
ss = ImageDraw.Image
drawyy = ImageDraw.Draw(a)
print 768767676
drawyy.text((0,1),"fewfwefwfw",fill=(0,25,25))
a.save(r"C:\Users\Administrator\Desktop\777.png")

Selenium c# find element select element exception

I'm fairly new to c# and writing a simple selenium code which will go onto www.asos.com. I then click on the country on the right hand side by finding the xpath. When I click on the country I want to change the country to 'india' and the currency to 'USD', and then select my preference.
I'm getting exception for driver.FindElement, SelectElement, SelectByValue previously when using java I wasn't getting these exceptions.
Exception I see for driver = The name driver doesn't exist in the current context
SelectElement = the type or namespace name 'SelectElement' could not be found
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
IWebDriver webDriver = new ChromeDriver(#"Path to my chrome driver defined here");
webDriver.Navigate().GoToUrl("www.asos.com");
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[2]/div/ul/li[3]/div/button')]")).Click();
var country = driver.FindElement(By.Id("country"));
var select_country = new SelectElement(country);
select_country = SelectByValue("India");
var currency = driver.FindElement(By.Id("currency"));
var select_currency = new SelectElement(currency);
select_currency = SelectByValue("$ USD");
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
}
}
driver.FindElement(By.XPath("//*[#id="chrome - header"]/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
The erro in quotation marks, try:
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
Use the value of the option in the html. Also call the select on the select element. For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver= new ChromeDriver(#"Path to my chrome driver defined here");
driver.Navigate().GoToUrl("www.asos.com");
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[2]/div/ul/li[3]/div/button')]")).Click();
var country = driver.FindElement(By.Id("country"));
var select_country = new SelectElement(country);
select_country.SelectByValue("IN");
var currency = driver.FindElement(By.Id("currency"));
var select_currency = new SelectElement(currency);
select_currency.SelectByValue("2");
driver.FindElement(By.XPath("//*[#id='chrome - header']/header/div[5]/div[2]/div/section/form/div[3]/button")).Click();
}
}
You may also want to throw in some waits to give the page time to load.

Would you share your idea how to call python command from embedded Python.Net?

I've been played with Python.Net for a week, but I can't find any sample code to use Python.Net in embedded way although Python.Net source has several embeddeding tests. I've searched many threads from the previous emailing list (Python.Net), the results are not consistent and are clueless.
What I'm trying to do is to get result (PyObject po) from C# code after executing python command such as 'print 2+3' from python prompt via Python.Net because IronPython doesn't have compatibility with the module that I currently using.
When I executed it from nPython.exe, it prints out 5 as I expected. However, when I run this code from embedded way from C#. it returns 'null' always. Would you give me some thoughts how I can get the execution result?
Thank you,
Spark.
Enviroments:
1. Windows 2008 R2, .Net 4.0. Compiled Python.Net with Python27, UCS2 at VS2012
2. nPython.exe works fine to run 'print 2+3'
using NUnit.Framework;
using Python.Runtime;
namespace CommonTest
{
[TestFixture]
public class PythonTests
{
public PythonTests()
{
}
[Test]
public void CommonPythonTests()
{
PythonEngine.Initialize();
IntPtr gs = PythonEngine.AcquireLock();
PyObject po = PythonEngine.RunString("print 2+3");
PythonEngine.ReleaseLock(gs);
PythonEngine.Shutdown();
}
}
}
It seems like PythonEngine.RunString() doesn't work. Instead, PythonEngine.RunSimpleString() works fine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Reflection;
using Python.Runtime;
namespace npythontest
{
public class Program
{
static void Main(string[] args)
{
string external_file = "c:\\\\temp\\\\a.py";
Console.WriteLine("Hello World!");
PythonEngine.Initialize();
IntPtr pythonLock = PythonEngine.AcquireLock();
var mod = Python.Runtime.PythonEngine.ImportModule("os.path");
var ret = mod.InvokeMethod("join", new Python.Runtime.PyString("my"), new Python.Runtime.PyString("path"));
Console.WriteLine(mod);
Console.WriteLine(ret);
PythonEngine.RunSimpleString("import os.path\n");
PythonEngine.RunSimpleString("p = os.path.join(\"other\",\"path\")\n");
PythonEngine.RunSimpleString("print p\n");
PythonEngine.RunSimpleString("print 3+2");
PythonEngine.RunSimpleString("execfile('" + external_file + "')");
PythonEngine.ReleaseLock(pythonLock);
PythonEngine.Shutdown();
}
}
}

Windows 7 clipboard copy paste operation using C#

I'm working on a Windows application where I need to use clipboard data. I am trying to copy text from clipboard by the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MultiValuedClipBoard
{
class Class1
{
public String SwapClipboardHtmlText(String replacementHtmlText)
{
String returnHtmlText = "hello";
if (Clipboard.ContainsText(TextDataFormat.Html))
{
returnHtmlText = Clipboard.GetText(TextDataFormat.Html);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
}
return returnHtmlText;
}
}
}
Calling the above function by:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
namespace MultiValuedClipBoard
{
class Program
{
static void Main(string[] args)
{
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.ReadLine();
}
}
}
When running this code it gives the output "Hello" which is the default value, not clipboard data.
Your code will not work because of two reasons:
[1] When you say:
if (Clipboard.ContainsText(TextDataFormat.Html))
Here you are basically assuming that the clipboard already contains a text and that too in HTML format, but depending on the values you are setting in the clipboard it doesn't look like you are intending to use the pre-existing clipboard value anywhere in your program. So, this if condition should not be there.
[2] Secondly, you are further trying to set the string "chetan" to the clipboard which is definitely not in HTML format. So,
Clipboard.SetText(replacementHtmlText, TextDataFormat.Html);
becomes
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
Hence, effectively, your new code becomes something like this:
String returnHtmlText = "hello";
//if (Clipboard.ContainsText(TextDataFormat.Html))
//{
returnHtmlText = Clipboard.GetText(TextDataFormat.Text);
Clipboard.SetText(replacementHtmlText, TextDataFormat.Text);
//}
return returnHtmlText;
Clearly Clipboard.ContainsText(TextDataFormat.Html) evaluates to false. Which means that the clipboard in fact does not contain text in the format you specify.
I changed your program to prove the point:
[STAThread]
static void Main(string[] args)
{
Clipboard.SetText("boo yah!", TextDataFormat.Html);
Class1 aas = new Class1();
string a = aas.SwapClipboardHtmlText("chetan");
Console.WriteLine(a);
Console.WriteLine(Clipboard.GetText(TextDataFormat.Html));
Console.ReadLine();
}
Output:
boo yah!
chetan

Categories