C# Get an array to convert to a PSObject - c#

I'm trying to use the System.Management.Automation namespace to use the built-in gridviewer from PowerShell in c#, however I can't seem to be able to get it to display my list of items, it always just returns it as one line as if I was trying to get the info of the array instead of it's members.
SomeClass[] list; //let's say I have a simple array of one object type
PowerShell posh = PowerShell.Create();
posh.AddCommand("Out-Gridview");
posh.AddArgument(list); //this inputs the list as first argument for the command
posh.Invoke(); //this now just opens a gridview with information about the list itself (length, syncroot, ...)
So what I would like is a way to translate my already existing list into a powershell-compatible object inside my C# code, preferably using only the automation library and other default .NET classes.

Related

Is there a way to get a list of all the fields in a mainframe system (IBM Pcomm) using c#?

While trying to use the autECLFieldList method in C#, "//using AutECLFieldList;", the compiler shows the error that reference is not added. Also, is there a way wherein we can use a loop to get a list of the field elements and their contents by using AutECLFieldList.gettext or something similar.
Thanks in advance.

Calling into python code using Pythonnet from C# and custom C# classes

I have the majority of my code base in c# where data is entered into a datagrid in a GUI and then this is taken into a set of python3 functions to interrogate the data further.
From the datagrid information , user defined objects containing boolean, float and dictionary properties are populated which are then passed into python.
Currently the python code is using only python functionality and I think this may be the issue as the dict.keys() method in the python funciton is not recognising the C# dictionary that is passed in.
Is there an easy way to convvert the c# dictionary into a python dictionary so that the python code can be unchanged?
Thanks!
A quick and dirty work around would be to use NewtonSoft nugget to serialize your class contents (in this case, your dictionary) and convert it into a JSON.
using Newtonsoft.Json
var myDictionary = new Dictionary<string,string>();
myDictionary.Add("key1","value1");
myDictionary.Add("key2","value2");
//Now convert the dictionary into json.
var jsonToSend = JsonConvert.SerializeObject(myDictionary);
Now pass in that jsonToSend to the python code and at the python code, load the json into a dict using json module like below:
import json
passedin_json = 'the output of your method that receives the json'
loaded_json_data = json.loads(passedin_json)
And done, Now you've successfully transferred your C# dictionary to your python dict

Dealing with a JSON.Net JArray in Python?

I'm using IronPython as a scripting language in my C# application. One of the "features" that I've implemented is the ability for a script to persist values, which are then exposed to the next script being executed. This is achieved by passing the value(s) to be stored to a C# class, exposed to the script by the "host" application. The code to store a value looks something like this:
store.set("xyz", 123)
('store' is the variable through which the C# object is exposed).
Internally the C# class stores these name/value pairs in a Dictionary<string, object>. When the script finishes executing it serialises the dictionary using Json.Net (var json = JsonConvert.SerializeObject(dict)) and writes the resulting string to file.
When the next script is run, the "host" C# application reads and deserialises the file (JsonConvert.DeserializeObject<Dictionary<string, object>>(s)) and exposes the name/value pairs to the script via the same C# class, which the script can access like this:
my_var = store.get("xyz")
This feature has been working fine with simple types such as ints and floats, but one of our users now needs to persist a list of ints. It works to a fashion - the list gets persisted and exposed to the next Python script, but at this point it is now a JArray type (something to do with Json.Net it seems). This doesn't play nicely with the Python code (which is expecting a list of ints).
I guess the simplest fix is to convert this JArray to a Python int list. But how?
Alternatively it would be nice if the issue could be "fixed" in the C# class (casting?), to avoid users from having to do this conversion in their scripts. However I don't want to change the de/serialisation process to the extent that it no longer reads users' existing data files. Thoughts?
I've found a solution with only minimal impact on script authors. In my C# code, after deserialising the file, I go through the dictionary looking for items with a value of type JArray, and convert them to arrays:
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var keys = dict.Keys.ToList();
foreach (var key in keys)
{
var jarray = dict[key] as JArray;
if (jarray != null)
{
dict[key] = jarray.ToObject<object[]>();
}
}
These arrays are then exposed to the Python script as before; as they are C# arrays the script authoer must convert to Python lists, which is trivial:
my_var = list(store.get("xyz"))

C# powershell objects as a datasource

Bare bones of the problem:
I am trying to populate a ComboBox, or even a ListBox for Windows Forms and for standard arrays and class definitions, it works great using DataSources and the related ValueMember and DisplayMember.
The problem arises when I attempt to utilise a returned Collection of PSObjects (powershell objects).
Here is the code section that I have tried:
private void PopulateGroups()
{
// DistributionGroups is a Collection<PSObject>
DistributionGroups.Clear();
DistributionGroups = GroupADConnection.GroupsInOU("OU=Distribution Groups,OU=Resources,OU=Groups,DC=Domain,DC=MadeUp");
cmbDistributionGroups.DataSource = DistributionGroups;
string test = DistributionGroups[5].Members["DistinguishedName"].Value.ToString();
cmbDistributionGroups.DisplayMember = #"Members[""SamAccountName""].Value.ToString()";
cmbDistributionGroups.ValueMember = "Members[\"DistinguishedName\"].Value.ToString()";
}
Basic background is that DistributionGroups is a Collection<PSObject> which has the members DistinguishedName and SamAccountName.
With the code displayed here, the DisplayMember will show the whole PSObject value through the ToString method, giving me: #{SamAccountName=AA_ Officer; DistinguishedName=CN=AA\+ Officer,OU=Administration,OU=Distribution Groups,OU=Resources,OU=Groups,DC=Domain,DC=MadeUp}
I have tried both methods of getting a quote character into the string so it will get the correct property. The test String object will correctly get the required member of the PSObject.
Is there something I am missing or is there no way to effectively do this without self defining an array with the PSObject members individually transferred?
Update:
After some more testing, it seems that the DataSource, more specifically the Value/Display Members only take the LAST argument. As in for the given: "Members[\"DistinguishedName\"].Value.ToString()" it only actually uses the ToString() part.
Is this the intended behaviour of the Value/Display Member attributes? Is there a way for me to make it use the full definition?

ExpressionListInit how to create list

I am trying to hydrate an array using the Linq.Expression namespace as this will be built into an IQueryable projection helper.
So far, I have managed to get the constructor for the list, identify its type, and now I am stuck with how to build an expression that will iterate over the source list and and return a new item for this new array to be initialised with.
Expression.Loop seems to be my best bet, but I can't figure out how to make it loop over the source array and give me back my converted items?
Anyone got any pointers of where I can start?
Si

Categories

Resources