I have a project where i will have to build dual stacked virtual machines. I usually work with powershell but it does not appear to be able to do that. I may have to use C#. I am kinda rusty on this but for some reason this code give me an error "Cannot create an instance of the abstract class or interface 'VMware.Vim.VimClient'".
using System.Text;
using VMware.Vim;
namespace Vimfunctions
{
public class VimFunctions
{
protected VimClient ConnectServer(string viServer, string viUser, string viPassword)
{
**VimClient vClient = new VimClient();**
ServiceContent vimServiceContent = new ServiceContent();
UserSession vimSession = new UserSession();
vClient.Connect("https://" + viServer.Trim() + "/sdk");
vimSession = vClient.Login(viUser, viPassword);
vimServiceContent = vClient.ServiceContent;
return vClient;
}
I added the reference to the project. I must have forgot to do something.
As per https://communities.vmware.com/thread/478700:
"either stick with the PowerCLI 5.5 release as mentioned or to modify your code to use the VimClientImpl class instead of VimClient (which is now an interface)."
A complete simple example I used:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VMware.Vim;
namespace vSphereCli
{
class Program
{
static void Main(string[] args)
{
VMware.Vim.VimClientImpl c = new VimClientImpl();
ServiceContent sc = c.Connect("https://HOSTNAME/sdk");
UserSession us = c.Login("admin#vsphere.local", "password");
IList<VMware.Vim.EntityViewBase> vms = c.FindEntityViews(typeof(VMware.Vim.VirtualMachine), null, null, null);
foreach (VMware.Vim.EntityViewBase tmp in vms)
{
VMware.Vim.VirtualMachine vm = (VMware.Vim.VirtualMachine)tmp;
Console.WriteLine((bool)(vm.Guest.GuestState.Equals("running") ? true : false));
Console.WriteLine(vm.Guest.HostName != null ? (string)vm.Guest.HostName : "");
Console.WriteLine("");
}
Console.ReadLine();
}
}
}
Add a reference to "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\VMware.Vim.dll". Update the hostname, password; and volia!
Related
I am trying to access the macros inside of an Access database (accdb).
I tried using:
using Microsoft.Office.Interop.Access.Dao;
...
DBEngine dbe = new DBEngine();
Database ac = dbe.OpenDatabase(fileName);
I found a container["Scripts"] that had a document["Macro1"] which is my target. I am struggling to access the contents of the document. I also question if the Microsoft.Office.Interop.Access.Dao is the best reference for what I am trying to achieve.
What is the best way to view the content of the macros and modules?
You can skip the DAO part, it's not needed in this case. Macros are project specific, so in order to get them all, you would need to loop through your projects. In my example, i just have one project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Access;
namespace Sandbox48
{
public class Program
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Access.Application oAccess = null;
string savePath = #"C:\macros\";
oAccess = new Microsoft.Office.Interop.Access.Application();
// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
#"", //filepath
true //Exclusive
);
var allMacros = oAccess.CurrentProject.AllMacros;
foreach(var macro in allMacros)
{
var fullMacro = (AccessObject)macro;
Console.WriteLine(fullMacro.Name);
oAccess.SaveAsText(AcObjectType.acMacro, fullMacro.FullName, $"{savePath}{ fullMacro.Name}.txt");
}
Console.Read();
}
}
}
I am trying to automate a simple geotiff to KMZ process using GDAL and C#
The code I have written is a little buggy and I am having a lot of trouble working out how to use the API. I am hoping this is a simple fix for more advanced developers.
My code is as follows:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSGeo.GDAL;
namespace TestingTIFFtoKMZ
{
class Program
{
static void Main(string[] args)
{
string outputName = Environment.CurrentDirectory + #"\BR01899_Mackenzie_09_EXPORT";
string vrtfile = outputName + #"\tempMosaic.vrt";
string filenameKMZ = outputName + #"\" + Environment.CurrentDirectory + ".kmz";
string[] tiffFiles = Directory.GetFiles(outputName, "*.tif");
var vrtOptions = new GDALBuildVRTOptions(new[] { "-overwrite" });
GDALTranslateOptions transOptions = new GDALTranslateOptions(new[] { "-of", "KMLSUPEROVERLAY", "-co", "format=png" });
Dataset vrtDataset = Gdal.wrapper_GDALBuildVRT_names(vrtfile, tiffFiles, vrtOptions, null, null);
// vrtDataset.Dispose();
Gdal.wrapper_GDALTranslate(filenameKMZ, vrtDataset, transOptions, null, null);
}
}
}
I am getting a null return value on the vrtDataset variable and (i think) as a result, I am getting a null reference error when I call the Gdal.wrapperGDALTranslate method.
Any help appreciated. Thanks.
It needed,
Gdal.AllRegister();
and an absolute path to the VRT file being created.
I am trying to insert a new property into the msi file. I am able to update the msi database file using the following code.Is there a way to add new values into a table. I am not able to find any.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsInstaller;
namespace msiExample
{
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class msiMain
{
static void Main(string[] args)
{
WindowsInstaller.Installer ins = (WindowsInstaller.Installer)new Installer();
string strFileMsi = #"C:\APP.msi";
System.Console.WriteLine("STARTING SECOND QUERY");
Database db2 = ins.OpenDatabase(strFileMsi, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeDirect);
View vw2 = db2.OpenView(#"Select * FROM Property where Value='Unknown'");
vw2.Execute(null);
Record rcrd2 = vw2.Fetch();
while (rcrd2 != null)
{
System.Console.WriteLine(rcrd2.get_StringData(1));
rcrd2.set_StringData(1,"No data");
vw2.Modify(WindowsInstaller.MsiViewModify.msiViewModifyUpdate, rcrd2);
rcrd2 = vw2.Fetch();
}
db2.Commit();
vw2.Close();
System.Console.WriteLine("completed");
}
}
}
Windows Installer XML (WiX) Deployment Tools Foundation (DTF) libraries help a lot here. The easiest way I know to do it is:
using Microsoft.Deployment.WindowsInstaller.Linq;
using (QDatabase database = new QDatabase(#"C:\data\test.msi", DatabaseOpenMode.Direct))
{
var record = database.Properties.NewRecord();
record.Property = "MyProperty";
record.Value = "MyValue";
record.Insert();
}
If you still want to think SQL then:
using Microsoft.Deployment.WindowsInstaller;
using (Database database = new Database(#"C:\data\test.msi", DatabaseOpenMode.Direct))
{
database.Execute("INSERT INTO `Property` (`Property`, `Value`) VALUES('MyProperty', 'MyValue')");
}
the DTF answer from Christopher Painter is better but with the com objet, based on your code :
WindowsInstaller.View vw2 = db2.OpenView("INSERT INTO Property (Property, Value) VALUES ('property_name', 'property_value')");
vw2.Execute(null);
db2.Commit();
vw2.Closed();
Use ` for name of tables and columns
Use ' for strings values
I'm attempting to grab a device handle on the Synaptics Touchpad using the Synaptics SDK, specifically using methods in the SYNCTRLLib.
However, the SYNCTRL method failed to find it, returning -1.
Syn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Syn
{
SynAPICtrl SynTP_API = new SynAPICtrl();
SynDeviceCtrl SynTP_Dev = new SynDeviceCtrl();
SynPacketCtrl SynTP_Pack = new SynPacketCtrl();
int DeviceHandle;
//Constructor
public Syn ()
{
SynTP_API.Initialize();
SynTP_API.Activate();
//DeviceHandle == -1 ? Can't find device?
DeviceHandle = SynTP_API.FindDevice(new SynConnectionType(), new SynDeviceType(), 0);
//Below line causing Unhandled Exception
SynTP_Dev.Select(DeviceHandle);
SynTP_Dev.Activate();
SynTP_Dev.OnPacket += SynTP_Dev_OnPacket;
}
public void SynTP_Dev_OnPacket()
{
Console.WriteLine(SynTP_Pack.FingerState);
Console.WriteLine(SynTP_Pack.X);
Console.WriteLine(SynTP_Pack.Y);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Program
{
static void Main(string[] args)
{
Syn mySyn = new Syn();
mySyn.SynTP_Dev_OnPacket();
}
}
}
I see that you are using the C# wrappers for Synaptics SDK. Even though CPP code might be not trivial to you, you might want to take a look at the file Samples/ComTest.cpp. It contains some example logic in order to find devices, more specifically at lines 66-76:
// Find a device, preferentially a TouchPad or Styk.
ISynDevice *pDevice = 0;
long lHandle = -1;
if ((pAPI->FindDevice(SE_ConnectionAny, SE_DeviceTouchPad, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceStyk, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceAny, &lHandle)) ||
pAPI->CreateDevice(lHandle, &pDevice))
{
printf("Unable to find a Synaptics Device.\n");
exit(-1);
}
Also, make sure you have registered the dlls. According to the ReadSynSDK.txt file:
For certain purposes it may be necessary to register the dlls
that are provided with the SDK. This can be done with the windows regsvr32
utility.
I'm compiling code on-the-fly using System.CodeDom.Compiler. Everything inside the compiled source works well, whatever I'm putting inside this source. I know how to call my functions:
o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
But let's say I'm using a WebClient to retrieve a string asynchronously using WebClient.DownloadStringAsync. Or any other context where I want my compiled source to tell to the host "Hey, I got a nice string ready for you." For the example, I've used a WebBrowser. Basically, I know how to deal with each of the two instances: My hosting program and the compiled program, but I want my compiled program to communicate with the host. By the way, I'm not a super-experimented programmer, so no obvious method comes to my mind.
What I've tried:
1 . I don't really need to try it because it would work, but I could use a timer reading a strings stack or tasks queue inside the compiled source, but the purpose of my application is to have +- 60 scripts able to execute ponctual tasks, not continuous background processes, so it wouldn't be efficient on the CPU.
2 . I've passed the handler to the compiled source like if it was in the hosting app:
//In the hosting app
MethodInfo mi2 = o.GetType().GetMethod("attachCallbackToHost");
mi2.Invoke(o2, new object[] { new WebBrowserNavigatedEventHandler (wb_navigated) });
//... And the handler
public static void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string browserHtmlFromCompiledSource = ((WebBrowser)sender).DocumentText;
MessageBox.Show(browserHtmlFromCompiledSource);
}
// Plain text from the compiled source code
public void attachCallbackToHost(WebBrowserNavigatedEventHandler handlerFromTheHost)
{
wb.Navigated += handlerFromTheHost;
}
And it did nothing.
3 . Maybe I could share a class or variable by passing it to the compiled assembly?
So, the question is either this or the other:
How to watch efficiently for change inside a specific variable or property inside the compiled program?
How to attach a callback to the host?
Ok. I got it: In order to access the host from the compiled source, the only thing required is to add the host assembly to the refered assemblies in the compiler parameters:
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
So no need for any special callback or INotifier.
Here's the full code that strictly answers my question and nothing more:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace MamaProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string source =
#"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using MyMama = MamaProgram;
namespace Baby
{
public class Program
{
public WebBrowser wb = new WebBrowser();
public void navigateTo(string url)
{
wb.Navigated += wb_navigated;
wb.Navigate(url);
}
public void wb_navigated(object sender, WebBrowserNavigatedEventArgs e)
{
MyMama.Form1.getResult(wb.DocumentText);
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false,
TreatWarningsAsErrors = false
};
compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
compilerParams.ReferencedAssemblies.Add("System.Data.dll");
compilerParams.ReferencedAssemblies.Add(typeof(System.Linq.Enumerable).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add(typeof(System.ComponentModel.Component).Assembly.Location); // Trick to add assembly without knowing their name
compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Compilation failed");
object o = results.CompiledAssembly.CreateInstance("Baby.Program");
MethodInfo mi2 = o.GetType().GetMethod("navigateTo");
mi2.Invoke(o, new object[] { "http://www.google.com" });
}
public static void getResult(string result)
{
MessageBox.Show(result);
}
}
}