Invoking a method thtough C# - wmi

I am trying to get some data from the UWF_Volume WMI provider. Please see the following link,
https://msdn.microsoft.com/en-us/library/jj979756(v=winembedded.81).aspx
More specifically I am trying to get the exclusion files using the following class,
UInt32 GetExclusions([out, EmbeddedInstance("UWF_ExcludedFile")] string ExcludedFiles[]);
I am not familiar with out parameters but from a research I can understand that acts as a reference argument. So I wrote the following method,
public void getUWFExclusions()
{
{
string computer = ".";
ManagementScope scope = new ManagementScope(#"\\" + computer + #"\root\standardcimv2\embedded");
ManagementClass cls = new ManagementClass(scope.Path.Path, "UWF_Volume", null);
foreach (MethodData m in cls.Methods)
{
richTextBox1.AppendText("The class contains this method:" + m.Name + "\n");
}
ManagementBaseObject outParams;
foreach (ManagementObject mo in cls.GetInstances())
{
outParams = mo.InvokeMethod("GetExclusions", null, null);
richtextbox1.appendtext(string.format("ExcludedFiles" + mo[ExcludedFiles]));
}
}
catch (Exception e)
{
richTextBox1.AppendText(e.ToString());
}
}
The problem is that the line,
richtextbox1.appendtext(string.format("ExcludedFiles" + mo[ExcludedFiles]));
returns "Not Found"
I appreciate any help to debug this problem.

I guess you are missing the Object Query that actually gets data via call to WMI. I am not sure about windows 8 but till 7 we used to get data by WQL and that is not there in above code.

Related

Textract Form Analysis, Java SDK 1.x

I'm looking to extract form data utilizing textract. I've tested with a PDF in the demo and results are great. Results using the SDK however are far from optimal, actually, completely inaccurate. If I use StartDocumentAnalysisRequest/StartDocumentAnalysisResult (asynchronous), I only get 1 block returned of type PAGE, never KEY_VALUE_SET. If I convert my PDF to an image and use the synchronous methods, I do get KEY_VALUE_SET back but results are completely inaccurate.
Does anyone know how I can utilize the asynchronous analysis functionality to retrieve form values as the documentation indicates?
Sample Code below:
StartDocumentAnalysisResult startDocumentAnalysisResult = amazonTextract.startDocumentAnalysis(req);
String startJobId = startDocumentAnalysisResult.getJobId();
GetDocumentAnalysisResult documentAnalysisResult = null;
String jobStatus = "IN_PROGRESS";
while (jobStatus.equals("IN_PROGRESS")) {
try {
TimeUnit.SECONDS.sleep(10);
GetDocumentAnalysisRequest documentAnalysisRequest = new GetDocumentAnalysisRequest()
.withJobId(startJobId)
.withMaxResults(1);
documentAnalysisResult = amazonTextract.getDocumentAnalysis(documentAnalysisRequest);
jobStatus = documentAnalysisResult.getJobStatus();
} catch (Exception e) {
logger.error(e);
}
}
if (!jobStatus.equals("IN_PROGRESS")) {
List<Block> blocks = documentAnalysisResult.getBlocks();
logger.error("block list size " + blocks.size());
Map<String, Map<String, Block>> keyValueBlockMap = new HashMap<>();
Map<String, Block> keyMap = new HashMap<>();
Map<String, Block> valueMap = new HashMap<>();
Map<String, Block> blockMap = new HashMap<>();
for (Block block : blocks) {
logger.error("Block Type:" + block.getBlockType());
String blockId = block.getId();
blockMap.put(blockId, block);
if (block.getBlockType().equals("KEY_VALUE_SET")) {
if (block.getEntityTypes().contains("KEY")) {
keyMap.put(blockId, block);
} else {
valueMap.put(blockId, block);
}
}
}
keyValueBlockMap.put("keyMap", keyMap);
keyValueBlockMap.put("valueMap", valueMap);
keyValueBlockMap.put("blockMap", blockMap);
Map<String, String> keyValueRelationShip = getKeyValueRelationShip(keyValueBlockMap);
for (String key : keyValueRelationShip.keySet()) {
logger.error("Key: " + key);
logger.error("Value: " + keyValueRelationShip.get(key));
}
}
Synchronous path which results in completely horrible results:
AnalyzeDocumentRequest request = new AnalyzeDocumentRequest() .withFeatureTypes(FeatureType.FORMS) .withDocument(new Document(). withS3Object(new com.amazonaws.services.textract.model.S3Object() .withName(objectName) .withBucket(awsHelper.getS3BucketName())));
AnalyzeDocumentResult result = amazonTextract.analyzeDocument(request);
You are not using the recommended version for the AWS SDK for Java. You are using a old version and not the recommended one.
I have tested the AWS SDK for Java V2 and I am able to get lines and text that lines up with the AWS Management Console.
You can find textTract V2 examples in the repo linked above.
I am able to get to lines and the corresponding text by using software.amazon.awssdk.services.textract.TextractClient.
For example when i debug through the code using the same PNG as I used in the console, i get the proper result.

How do I add precautions to get around Microsoft.ACE.OLEDB.12.0 not registered?

When I use the following code on my home computer it works fine for me. However, I have to use it on multiple different machines.
"Provider = Microsoft.ACE.OLEDB.12.0;"
I was thinking that there could be a get around to this because I need it in a more universal format so that it works on multiple machines.
I have hoped that there could be a work around, maybe by including an alternative provider in the code (if that is possible) or an catch or if statement that will rerun the code but with an alternate provider if it cannot find the first one.
It would be changed to Microsoft.Jet.OLEDB.4.0
If anyone could scratch up a little bit of code to work around this so that my program could take into account both providers that would be great as it would make my projects more universal.
Background code (ignore unsafe SQL unless you want to fix it):
OleDbDataReader^ openData(String^ fieldEntity, String^ field, String^ tableName)
{
String^ sqlstr = "SELECT * FROM ";
sqlstr += tableName + " WHERE " + field + " = " + fieldEntity;
OleDbConnection^ conn = nullptr;
conn = gcnew OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;" +
"Data Source =" + "myDatabaseV3.accdb");
OleDbCommand^ cmd = nullptr;
//fix this so that it will consider both providers.
conn->Open();
cmd = gcnew OleDbCommand(sqlstr, conn);
OleDbDataReader^ reader = cmd->ExecuteReader(System::Data::CommandBehavior::CloseConnection);
return reader;
}
I have solved this problem myself. I realised that I could you another try catch statement in my class to change the connection string if there is an exception
conn = gcnew OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;" +
"Data Source =" + "myDatabaseV3.mdb");
pause();
OleDbCommand^ cmd = nullptr;
//fix this so that it will come out of the current directiory
try {
conn->Open();
}
catch (Exception^ ex)
{
conn->ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" +
"Data Source =" + "myDatabaseV3.accdb";
conn->Open();
}
You could switch these around if you wanted the order of these doesn't really matter. Furthermore, if this solution is invalid you could have a nested try catch statement. However, my code in particular has this In a class and the way this is ran anyway is in a try catch in another part of the code so it is unnecessary for me.

Is there any way to get the Active Solution Configuration name in C# Code?

I have three solution configurations in my UWP solution in Visual Studio:
Development
Staging
Production
Each is a associated with a different web service and auth provider in the configuration files. In my code, how do I tell which one is which? In the past I've explicitly provided DEFINE constants, but there must be a better way by now.
The active solution configuration is stored in the .suo file beneath the .vs directory at the root solution folder. The .suo file has a compound file binary format, which means you can't just parse it with text manipulation tools.
However, using OpenMcdf -- a tool that can be used to manipulate these types of files -- you can easily get the active solution configuration.
Here's a console app I wrote that works. Feel free to adapt the code to your situation:
using OpenMcdf;
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace GetActiveBuildConfigFromSuo
{
internal enum ProgramReturnCode
{
Success = 0,
NoArg = -1,
InvalidFileFormat = -2
}
internal class Program
{
private const string SolutionConfigStreamName = "SolutionConfiguration";
private const string ActiveConfigTokenName = "ActiveCfg";
internal static int Main(string[] args)
{
try
{
ValidateCommandLineArgs(args);
string activeSolutionConfig = ExtractActiveSolutionConfig(
new FileInfo(args.First()));
throw new ProgramResultException(
activeSolutionConfig, ProgramReturnCode.Success);
}
catch (ProgramResultException e)
{
Console.Write(e.Message);
return (int)e.ReturnCode;
}
}
private static void ValidateCommandLineArgs(string[] args)
{
if (args.Count() != 1) throw new ProgramResultException(
"There must be exactly one command-line argument, which " +
"is the path to an input Visual Studio Solution User " +
"Options (SUO) file. The path should be enclosed in " +
"quotes if it contains spaces.", ProgramReturnCode.NoArg);
}
private static string ExtractActiveSolutionConfig(FileInfo fromSuoFile)
{
CompoundFile compoundFile;
try { compoundFile = new CompoundFile(fromSuoFile.FullName); }
catch (CFFileFormatException)
{ throw CreateInvalidFileFormatProgramResultException(fromSuoFile); }
if (compoundFile.RootStorage.TryGetStream(
SolutionConfigStreamName, out CFStream compoundFileStream))
{
var data = compoundFileStream.GetData();
string dataAsString = Encoding.GetEncoding("UTF-16").GetString(data);
int activeConfigTokenIndex = dataAsString.LastIndexOf(ActiveConfigTokenName);
if (activeConfigTokenIndex < 0)
CreateInvalidFileFormatProgramResultException(fromSuoFile);
string afterActiveConfigToken =
dataAsString.Substring(activeConfigTokenIndex);
int lastNullCharIdx = afterActiveConfigToken.LastIndexOf('\0');
string ret = afterActiveConfigToken.Substring(lastNullCharIdx + 1);
return ret.Replace(";", "");
}
else throw CreateInvalidFileFormatProgramResultException(fromSuoFile);
}
private static ProgramResultException CreateInvalidFileFormatProgramResultException(
FileInfo invalidFile) => new ProgramResultException(
$#"The provided file ""{invalidFile.FullName}"" is not a valid " +
$#"SUO file with a ""{SolutionConfigStreamName}"" stream and an " +
$#"""{ActiveConfigTokenName}"" token.", ProgramReturnCode.InvalidFileFormat);
}
internal class ProgramResultException : Exception
{
internal ProgramResultException(string message, ProgramReturnCode returnCode)
: base(message) => ReturnCode = returnCode;
internal ProgramReturnCode ReturnCode { get; }
}
}
Download DTE nuget packages : EnvDTE.8.0.2
Add below code
EnvDTE.DTE DTE = Marshal.GetActiveObject("VisualStudio.DTE.15.0") as EnvDTE.DTE;
var activeConfig = (string)DTE.Solution.Properties.Item("ActiveConfig").Value;

SqlDataAdapter not loading datatable - C++

I have been trying to load an SQL database into a datatable in C++, however; it doesn't seem to want to work. The connection is working though, as DataReader works. Here is my code
void importDatabase() {
SqlConnection con;
SqlDataAdapter^ da;
SqlCommand cmd;
DataTable^ dt;
int count = 1;
try {
con.ConnectionString = "Data Source=MYNAME\\SQLEXPRESS;Initial Catalog=VinylRecords;Integrated Security=True";
cmd.CommandText = "SELECT * FROM Records";
cmd.Connection = %con;
con.Open();
da = gcnew SqlDataAdapter(%cmd);
dt = gcnew DataTable("Records");
Console::Write(da->ToString());
da->Fill(dt);
for (int i = 0; i < dt->Rows->Count - 1; i++) {
String^ value_string;
value_string = dt->Rows[i]->ToString();
Console::WriteLine(dt->Rows[i]->ToString());
count++;
}
cout << "There are " << count << " many records";
}
catch (Exception^ ex) {
Console::WriteLine(ex->ToString());
}
}
Please note, that I slightly altered the source name to post here, but only the first part.
What is wrong with my code?
So, the problem is here:
dt->Rows[i]->ToString()
Rows[i] is a Row object. And the Row class's ToString() method always prints out the fully qualified typename, which is what you are seeing. So this is technically working just fine. What you will need to do to get something useful is: you will need to access a specific column in that row and get it's value, then output that.
Something along the lines of:
foreach (DataRow dr in dt.Rows)
{
Console.Write(dr.Field<int>("ColumnOne"));
Console.Write(" | ");
Console.WriteLine(dr.Field<string>("ColumnTwo"));
}
I am not entirely sure on the syntax for accessing a specific cell inside of a DataTable when using C++\CLI. So I have provided the C# equivalent to explain why it is you were getting output of managed type names (e.g. "System.Data.DataRow") instead of the info inside of the Row's columns.
Also, I noticed you tagged this question with "mysql", but you are using the ADO.NET System.Data.SqlClient namespace. The SqlDataReader and SqlDataAdapter classes only work with TSQL (Microsoft's SQL Server databases) If you are actually connecting to a mysql database you will want to use the System.Data.OdbcDataAdapter class. You can read a little more here: https://msdn.microsoft.com/en-us/library/ms254931.aspx

Create stored procedure from x++

Got myself into trouble today trying to create a stored procedure from ax.
Here is a simple example:
static void testProcedureCreation(Args _args)
{
MyParamsTable myParams;
SqlStatementExecutePermission perm;
str sqlStatement;
LogInProperty Lp = new LogInProperty();
OdbcConnection myConnection;
Statement myStatement;
ResultSet myResult;
str temp;
;
select myParams;
LP.setServer(myParams.Server);
LP.setDatabase(myParams.Database);
//Lp.setUsername("sa");
//Lp.setPassword("sa");
sqlStatement = #"create procedure testproc
as begin
print 'a'
end";
//sqlStatement = strFmt(sqlStatement, myStr);
info(sqlStatement);
perm = new SqlStatementExecutePermission(sqlStatement);
perm.assert();
try
{
myConnection = new OdbcConnection(LP);
}
catch
{
info("Check username/password.");
return;
}
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(sqlStatement);
while (myResult.next())
{
temp = myResult.getString(1);
info(temp);
if (strScan(temp, 'Error', 1, strLen(temp)) > 0)
throw error(temp);
}
myStatement.close();
CodeAccessPermission::revertAssert();
}
To be honest, in my real example I am using BCP and some string concat with a lot of | ' and "".
Anyway, here is what I got:
For a couple of hours I kept changing and retrying a lot of things and, a good thought came into my mind.
"Let's try with a much easier example and check the results!"
OK, no luck, the results were the same, as you can see in the pic above.
But for no reason, I tried to :
exec testproc
in my ssms instance and to my surprise, it worked. My small procedure was there.
It would be so nice if someone could explain this behavior and maybe what should be the correct approach.
This Q/A should provide an answer.
How to get the results of a direct SQL call to a stored procedure?
executeQuery vs executeUpdate