Related
In this situation, I am trying to get the value of "FileSizeType", an integer variable, into the method that's under it "NomCategorie"and convert it to a string(that's what the comment says).
static int ChoisirCategory()
{
int FileSizeType;
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
return FileSizeType;
}
static string NomCategorie(int c)
{
//get FileSizeType into c
string FileType;
if (c == 1)
{
return FileType = "Small";
}
else if (c == 2)
{
return FileType = "Medium";
}
else if (c == 3)
{
return FileType = "Large";
}
else if (c == 4)
{
return FileType = "Huge";
}
else
{
return FileType="Non-valid choice";
}
I would suggest using enum class
public enum Test
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
then you can simply convert the number by using
int integer = 1;
if (Enum.IsDefined(typeof(Test), integer)
{
Console.WriteLine((Test)integer).
}
else
{
Console.WriteLine("Bad Integer");
}
output:
Small
Looking at your existing code, you are already returning the value of FileSizeType from the ChoisirCategory, so you can capture it in a variable and then pass that to the NomCategorie method to get the category name, for example:
int categoryId = ChoisirCategory();
string categoryName = NomCategorie(categoryId);
Note that there are many other improvements that can be made (for example, what happens if the user types in "two" instead of "2"?), but I think those suggestions may be out of scope based on the question.
Here's how your code could be simplified if you combine both suggestions above. I've also added an if clause to verify that the value is not higher than those available.
static enum AvailableSizes
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
static int ChoisirCategory()
{
int FileSizeType;
GetInput:
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
// Ensure the value is not higher than expected
// (you could also check that it is not below the minimum value)
if (FileSizeType > Enum.GetValues(typeof(AvailableSizes)).Cast<int>().Max());
{
Console.WriteLine("Value too high.");
goto GetInput;
}
return FileSizeType;
}
static string NomCategorie(int c)
{
if (Enum.IsDefined(typeof(AvailableSizes), c)
{
return (AvailableSizes)c;
}
else
{
return "Invalid category";
}
}
Then somewhere in your code you would call these using this statement
string categoryStr = NomCategorie(ChoisirCategory());
Console.WriteLinte(categoryStr); // or do whatever you want with the returned value
With this code, if the input is higher than 4, it will output "Value too high." and ask the question again until the value is no higher than 4.
If the user types 0 or a negative value, then it will output "Invalid category".
This might help you decide where you want to handle input errors: right after user input or during the parsing of the number to a string.
I'm trying to sign data in C#, using ECDSA algorithm (this part looks OK) and to verify signature in C using Windows crypto API.
Signature part:
CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters();
keyCreationParameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport;
keyCreationParameters.KeyUsage = CngKeyUsages.Signing;
CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters);
ECDsaCng dsa = new ECDsaCng(key); //dsa = Digital Signature Algorithm
byte[] privateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
File.WriteAllText("privatekey.txt", String.Join(",", privateKey));
byte[] publicKey = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob);
File.WriteAllText("publicKey.txt", String.Join(",", publicKey));
CngKey importedKey = CngKey.Import(File.ReadAllText("privatekey.txt").Split(',').Select(m => byte.Parse(m)).ToArray(), CngKeyBlobFormat.EccPrivateBlob);
ECDsaCng importedDSA = new ECDsaCng(importedKey); //dsa = Digital Signature Algorithm
byte[] signed = dsa.SignData(new byte[] { 1, 2, 3, 4, 5 });
File.WriteAllText("signed.txt", String.Join(",", signed));
At this point I'm able to create a signature key and export it to a byte buffer in a file.
Problems come when I'm trying to import this public key in C using windows crypto API.
BYTE KeyBlob[] = { // public key exported by above c# code
69,67,83,49,32,0,0,0,227,146,138,255,218,235,122,141,44,110,211,95,59,227,226,163,81,188,242,115,60,171,46,141,221,117,169,139,42,143,67,85,144,242,232,188,22,158,230,15,110,6,214,252,252,242,224,241,110,186,1,244,176,65,88,184,94,19,98,174,158,7,154,152
};
int _tmain()
{
HCRYPTPROV hProv = NULL;
HCRYPTKEY hKey = NULL;
DWORD dwBlobLen;
BYTE* pbKeyBlob;
if (!CryptAcquireContext(
&hProv,
NULL,
MS_ENHANCED_PROV,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
printf(" Error in AcquireContext 0x%08x \n", GetLastError());
return 1;
}
if (!CryptImportKey(
hProv,
KeyBlob,
sizeof(DesKeyBlob),
0,
CRYPT_EXPORTABLE,
&hKey))
{
printf("Error 0x%08x in importing the key \n",
GetLastError());
}
which returns
Error 0x80090007 in importing the key
which is (believing winerror.h) :
//
// MessageId: NTE_BAD_VER
//
// MessageText:
//
// Bad Version of provider.
//
#define NTE_BAD_VER _HRESULT_TYPEDEF_(0x80090007L)
What do I do wrong?
Thanks to this wonderful website I just found : referencesouce.microsoft.com, I've been able to disassemble what the C# API does when verifying a signature and importing a key.
Apparently I need ncrypt/bcrypt, and signature is verified against a hash, and not the data itself:
public bool VerifyData(Stream data, byte[] signature) {
if (data == null) {
throw new ArgumentNullException("data");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
using (BCryptHashAlgorithm hashAlgorithm = new BCryptHashAlgorithm(HashAlgorithm, BCryptNative.ProviderName.MicrosoftPrimitiveProvider)) {
hashAlgorithm.HashStream(data);
byte[] hashValue = hashAlgorithm.HashFinal();
return VerifyHash(hashValue, signature);
}
}
[SecuritySafeCritical]
public override bool VerifyHash(byte[] hash, byte[] signature) {
if (hash == null) {
throw new ArgumentNullException("hash");
}
if (signature == null) {
throw new ArgumentNullException("signature");
}
// We need to get the raw key handle to verify the signature. Asserting here is safe since verifiation
// is not a protected operation, and we do not expose the handle to the user code.
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
// This looks odd, but Key.Handle is really a duplicate so we need to dispose it
using (SafeNCryptKeyHandle keyHandle = Key.Handle) {
CodeAccessPermission.RevertAssert();
return NCryptNative.VerifySignature(keyHandle, hash, signature);
}
}
Here is a native solution, for whoever needs that:
#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
char key[72] = { 69,67,83,49,32,0,0,0,227,146,138,255,218,235,122,141,44,110,211,95,59,227,226,163,81,188,242,115,60,171,46,141,221,117,169,139,42,143,67,85,144,242,232,188,22,158,230,15,110,6,214,252,252,242,224,241,110,186,1,244,176,65,88,184,94,19,98,174,158,7,154,152 };
char sign[64] = { 165,50,54,149,14,175,128,54,21,30,129,165,137,203,45,123,180,121,118,20,15,61,253,186,65,129,21,26,54,84,40,205,103,254,108,34,126,205,116,183,44,189,5,180,28,119,228,70,127,116,227,248,232,144,53,226,185,251,217,179,148,88,208,152 };
char message[] = { 1, 2, 3, 4, 5 };
BOOL crypt_init(char* key, unsigned long key_len)
{
HCRYPTPROV hProv = NULL;
BCRYPT_ALG_HANDLE hHashAlg = NULL, hSignAlg = NULL;
BCRYPT_HASH_HANDLE hHash = NULL;
PBYTE pbHash = NULL;
PBYTE pbHashObject = NULL;
DWORD cbHashObject = 0,
cbHash = 0,
cbData = 0;
NTSTATUS status;
if (ERROR_SUCCESS != NCryptOpenStorageProvider(&hProv, NULL, 0)) {
printf("CryptAcquireContext failed - err=0x%x.\n", GetLastError());
return FALSE;
}
NCRYPT_KEY_HANDLE keyHandle;
if (ERROR_SUCCESS != NCryptImportKey(hProv, NULL, BCRYPT_ECCPUBLIC_BLOB, NULL, &keyHandle, (PBYTE)key, 72, 0)) {
printf("CryptAcquireContext failed - err=0x%x.\n", GetLastError());
return FALSE;
}
if (!BCRYPT_SUCCESS(status = BCryptOpenAlgorithmProvider(
&hHashAlg,
BCRYPT_SHA256_ALGORITHM,
NULL,
0)))
{
printf("BCryptOpenAlgorithmProvider failed - err=0x%x.\n", status);
return false;
}
if(!BCRYPT_SUCCESS(status = BCryptGetProperty(hHashAlg, BCRYPT_OBJECT_LENGTH, (PBYTE)&cbHashObject, sizeof(DWORD), &cbData, 0))) {
printf("BCryptGetProperty failed - err=0x%x.\n", status);
return FALSE;
}
pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHashObject);
if (NULL == pbHashObject) {
printf("memory allocation failed\n");
return FALSE;
}
if (!BCRYPT_SUCCESS(status = BCryptGetProperty(hHashAlg, BCRYPT_HASH_LENGTH, (PBYTE)&cbHash, sizeof(DWORD), &cbData, 0))) {
printf("BCryptGetProperty failed - err=0x%x.\n", status);
return FALSE;
}
pbHash = (PBYTE)HeapAlloc(GetProcessHeap(), 0, cbHash);
if (NULL == pbHash)
{
printf("memory allocation failed\n");
return FALSE;
}
if (!BCRYPT_SUCCESS(status = BCryptCreateHash(hHashAlg, &hHash, pbHashObject, cbHashObject, NULL, 0, 0)))
{
printf("BCryptCreateHash failed - err=0x%x.\n", status);
return FALSE;
}
if (!BCRYPT_SUCCESS(status = BCryptHashData(hHash, (PBYTE)message, sizeof(message), 0)))
{
printf("BCryptHashData failed - err=0x%x.\n", status);
return FALSE;
}
if (!BCRYPT_SUCCESS(status = BCryptFinishHash(hHash, pbHash, cbHash, 0)))
{
printf("BCryptFinishHash failed - err=0x%x.\n", status);
return FALSE;
}
if(ERROR_SUCCESS != NCryptVerifySignature(keyHandle, NULL, pbHash, cbHash, (PBYTE) sign, sizeof(sign), 0)) {
printf("BCryptVerifySignature failed - err=0x%x.\n", status);
return FALSE;
}
return TRUE;
}
int main() {
crypt_init(key, 72);
}
Using HDF5DotNet, can anyone point me at example code, which will open an hdf5 file, extract the contents of a dataset, and print the contents to standard output?
So far I have the following:
H5.Open();
var h5 = H5F.open("example.h5", H5F.OpenMode.ACC_RDONLY);
var dataset = H5D.open(h5, "/Timings/aaPCBTimes");
var space = H5D.getSpace(dataset);
var size = H5S.getSimpleExtentDims(space);
Then it gets a bit confusing.
I actually want to do some processing on the contents of the dataset but I think once I have dump to standard output I can work it out from there.
UPDATE: I've hacked around this sufficient to solve my own problem. I failed to realise a dataset was a multi-array - I thought it was more like a db table. In the unlikely event anyone is interested,
double[,] dataArray = new double[size[0], 6];
var wrapArray = new H5Array<double>(dataArray);
var dataType = H5D.getType(d);
H5D.read(dataset, dataType, wrapArray);
Console.WriteLine(dataArray[0, 0]);
Try this:
using System;
using HDF5DotNet;
namespace CSharpExample1
{
class Program
{
// Function used with
static int myFunction(H5GroupId id, string objectName, Object param)
{
Console.WriteLine("The object name is {0}", objectName);
Console.WriteLine("The object parameter is {0}", param);
return 0;
}
static void Main(string[] args)
{
try
{
// We will write and read an int array of this length.
const int DATA_ARRAY_LENGTH = 12;
// Rank is the number of dimensions of the data array.
const int RANK = 1;
// Create an HDF5 file.
// The enumeration type H5F.CreateMode provides only the legal
// creation modes. Missing H5Fcreate parameters are provided
// with default values.
H5FileId fileId = H5F.create("myCSharp.h5",
H5F.CreateMode.ACC_TRUNC);
// Create a HDF5 group.
H5GroupId groupId = H5G.create(fileId, "/cSharpGroup", 0);
H5GroupId subGroup = H5G.create(groupId, "mySubGroup", 0);
// Demonstrate getObjectInfo
ObjectInfo info = H5G.getObjectInfo(fileId, "/cSharpGroup", true);
Console.WriteLine("cSharpGroup header size is {0}", info.headerSize);
Console.WriteLine("cSharpGroup nlinks is {0}", info.nHardLinks);
Console.WriteLine("cSharpGroup fileno is {0} {1}",
info.fileNumber[0], info.fileNumber[1]);
Console.WriteLine("cSharpGroup objno is {0} {1}",
info.objectNumber[0], info.objectNumber[1]);
Console.WriteLine("cSharpGroup type is {0}", info.objectType);
H5G.close(subGroup);
// Prepare to create a data space for writing a 1-dimensional
// signed integer array.
ulong[] dims = new ulong[RANK];
dims[0] = DATA_ARRAY_LENGTH;
// Put descending ramp data in an array so that we can
// write it to the file.
int[] dset_data = new int[DATA_ARRAY_LENGTH];
for (int i = 0; i < DATA_ARRAY_LENGTH; i++)
dset_data[i] = DATA_ARRAY_LENGTH - i;
// Create a data space to accommodate our 1-dimensional array.
// The resulting H5DataSpaceId will be used to create the
// data set.
H5DataSpaceId spaceId = H5S.create_simple(RANK, dims);
// Create a copy of a standard data type. We will use the
// resulting H5DataTypeId to create the data set. We could
// have used the HST.H5Type data directly in the call to
// H5D.create, but this demonstrates the use of H5T.copy
// and the use of a H5DataTypeId in H5D.create.
H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_INT);
// Find the size of the type
uint typeSize = H5T.getSize(typeId);
Console.WriteLine("typeSize is {0}", typeSize);
// Set the order to big endian
H5T.setOrder(typeId, H5T.Order.BE);
// Set the order to little endian
H5T.setOrder(typeId, H5T.Order.LE);
// Create the data set.
H5DataSetId dataSetId = H5D.create(fileId, "/csharpExample",
typeId, spaceId);
// Write the integer data to the data set.
H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
new H5Array<int>(dset_data));
// If we were writing a single value it might look like this.
// int singleValue = 100;
// H5D.writeScalar(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
// ref singleValue);
// Create an integer array to receive the read data.
int[] readDataBack = new int[DATA_ARRAY_LENGTH];
// Read the integer data back from the data set
H5D.read(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
new H5Array<int>(readDataBack));
// Echo the data
for(int i=0;i<DATA_ARRAY_LENGTH;i++)
{
Console.WriteLine(readDataBack[i]);
}
// Close all the open resources.
H5D.close(dataSetId);
// Reopen and close the data sets to show that we can.
dataSetId = H5D.open(fileId, "/csharpExample");
H5D.close(dataSetId);
dataSetId = H5D.open(groupId, "/csharpExample");
H5D.close(dataSetId);
H5S.close(spaceId);
H5T.close(typeId);
H5G.close(groupId);
//int x = 10;
//H5T.enumInsert<int>(typeId, "myString", ref x);
//H5G.close(groupId);
H5GIterateDelegate myDelegate;
myDelegate = myFunction;
int x = 9;
int index = H5G.iterate(fileId, "/cSharpGroup",
myDelegate, x, 0);
// Reopen the group id to show that we can.
groupId = H5G.open(fileId, "/cSharpGroup");
H5G.close(groupId);
H5F.close(fileId);
// Reopen and reclose the file.
H5FileId openId = H5F.open("myCSharp.h5",
H5F.OpenMode.ACC_RDONLY);
H5F.close(openId);
}
// This catches all the HDF exception classes. Because each call
// generates unique exception, different exception can be handled
// separately. For example, to catch open errors we could have used
// catch (H5FopenException openException).
catch (HDFException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Processing complete!");
Console.ReadLine();
}
}
}
So, your start was awesome. I've created some extensions which should help you out. Using this in your code, you should be able to things that make more sense in an object-oriented language, such as (in your case):
H5.Open();
var h5FileId= H5F.open("example.h5");
double[,] dataArray = h5FileId.Read2DArray<double>("/Timings/aaPCBTimes");
// or more generically...
T[,] dataArray = h5FileId.Read2DArray<T>("/Timings/aaPCBTimes");
Here are the incomplete extensions, I'll look into adding them into the HDF5Net...
public static class HdfExtensions
{
// thank you http://stackoverflow.com/questions/4133377/splitting-a-string-number-every-nth-character-number
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException("s");
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", "partLength");
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
public static T[] Read1DArray<T>(this H5FileId fileId, string dataSetName)
{
var dataset = H5D.open(fileId, dataSetName);
var space = H5D.getSpace(dataset);
var dims = H5S.getSimpleExtentDims(space);
var dataType = H5D.getType(dataset);
if (typeof(T) == typeof(string))
{
int stringLength = H5T.getSize(dataType);
byte[] buffer = new byte[dims[0] * stringLength];
H5D.read(dataset, dataType, new H5Array<byte>(buffer));
string stuff = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
return stuff.SplitInParts(stringLength).Select(ss => (T)(object)ss).ToArray();
}
T[] dataArray = new T[dims[0]];
var wrapArray = new H5Array<T>(dataArray);
H5D.read(dataset, dataType, wrapArray);
return dataArray;
}
public static T[,] Read2DArray<T>(this H5FileId fileId, string dataSetName)
{
var dataset = H5D.open(fileId, dataSetName);
var space = H5D.getSpace(dataset);
var dims = H5S.getSimpleExtentDims(space);
var dataType = H5D.getType(dataset);
if (typeof(T) == typeof(string))
{
// this will also need a string hack...
}
T[,] dataArray = new T[dims[0], dims[1]];
var wrapArray = new H5Array<T>(dataArray);
H5D.read(dataset, dataType, wrapArray);
return dataArray;
}
}
Here is a working sample:
using System.Collections.Generic;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HDF5DotNet;
namespace HDF5Test
{
public class HDFTester
{
static int myFunction(H5GroupId id, string objectName, Object param)
{
Console.WriteLine("The object name is {0}", objectName);
Console.WriteLine("The object parameter is {0}", param);
return 0;
}
public static void runTest()
{
try
{
// We will write and read an int array of this length.
const int DATA_ARRAY_LENGTH = 12;
// Rank is the number of dimensions of the data array.
const int RANK = 1;
// Create an HDF5 file.
// The enumeration type H5F.CreateMode provides only the legal
// creation modes. Missing H5Fcreate parameters are provided
// with default values.
H5FileId fileId = H5F.create("myCSharp.h5",
H5F.CreateMode.ACC_TRUNC);
// Create a HDF5 group.
H5GroupId groupId = H5G.create(fileId, "/cSharpGroup");
H5GroupId subGroup = H5G.create(groupId, "mySubGroup");
// Demonstrate getObjectInfo
ObjectInfo info = H5G.getObjectInfo(fileId, "/cSharpGroup", true);
Console.WriteLine("cSharpGroup header size is {0}", info.headerSize);
Console.WriteLine("cSharpGroup nlinks is {0}", info.nHardLinks);
Console.WriteLine("cSharpGroup fileno is {0} {1}",
info.fileNumber[0], info.fileNumber[1]);
Console.WriteLine("cSharpGroup objno is {0} {1}",
info.objectNumber[0], info.objectNumber[1]);
Console.WriteLine("cSharpGroup type is {0}", info.objectType);
H5G.close(subGroup);
// Prepare to create a data space for writing a 1-dimensional
// signed integer array.
long[] dims = new long[RANK];
dims[0] = DATA_ARRAY_LENGTH;
// Put descending ramp data in an array so that we can
// write it to the file.
int[] dset_data = new int[DATA_ARRAY_LENGTH];
for (int i = 0; i < DATA_ARRAY_LENGTH; i++)
dset_data[i] = DATA_ARRAY_LENGTH - i;
// Create a data space to accommodate our 1-dimensional array.
// The resulting H5DataSpaceId will be used to create the
// data set.
H5DataSpaceId spaceId = H5S.create_simple(RANK, dims);
// Create a copy of a standard data type. We will use the
// resulting H5DataTypeId to create the data set. We could
// have used the HST.H5Type data directly in the call to
// H5D.create, but this demonstrates the use of H5T.copy
// and the use of a H5DataTypeId in H5D.create.
H5DataTypeId typeId = H5T.copy(H5T.H5Type.NATIVE_INT);
// Find the size of the type
int typeSize = H5T.getSize(typeId);
Console.WriteLine("typeSize is {0}", typeSize);
// Set the order to big endian
H5T.setOrder(typeId, H5T.Order.BE);
// Set the order to little endian
H5T.setOrder(typeId, H5T.Order.LE);
// Create the data set.
H5DataSetId dataSetId = H5D.create(fileId, "/csharpExample",
typeId, spaceId);
// Write the integer data to the data set.
H5D.write(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
new H5Array<int>(dset_data));
// If we were writing a single value it might look like this.
// int singleValue = 100;
// H5D.writeScalar(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
// ref singleValue);
// Create an integer array to receive the read data.
int[] readDataBack = new int[DATA_ARRAY_LENGTH];
// Read the integer data back from the data set
H5D.read(dataSetId, new H5DataTypeId(H5T.H5Type.NATIVE_INT),
new H5Array<int>(readDataBack));
// Echo the data
for (int i = 0; i < DATA_ARRAY_LENGTH; i++)
{
Console.WriteLine(readDataBack[i]);
}
// Close all the open resources.
H5D.close(dataSetId);
// Reopen and close the data sets to show that we can.
dataSetId = H5D.open(fileId, "/csharpExample");
H5D.close(dataSetId);
dataSetId = H5D.open(groupId, "/csharpExample");
H5D.close(dataSetId);
H5S.close(spaceId);
H5T.close(typeId);
H5G.close(groupId);
//int x = 10;
//H5T.enumInsert<int>(typeId, "myString", ref x);
//H5G.close(groupId);
H5GIterateCallback myDelegate;
myDelegate = myFunction;
int x = 9;
int start = 0;
int index = H5G.iterate(fileId, "/cSharpGroup",myDelegate, x, ref start);
// Reopen the group id to show that we can.
groupId = H5G.open(fileId, "/cSharpGroup");
H5G.close(groupId);
H5F.close(fileId);
// Reopen and reclose the file.
H5FileId openId = H5F.open("myCSharp.h5",
H5F.OpenMode.ACC_RDONLY);
H5F.close(openId);
}
// This catches all the HDF exception classes. Because each call
// generates unique exception, different exception can be handled
// separately. For example, to catch open errors we could have used
// catch (H5FopenException openException).
catch (HDFException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Processing complete!");
Console.ReadLine();
}
}
}
I know this is old but for anyone who still need to work with HDF5 files I have a C# wrapper that encapsulated most of the operations at github (based on original work by other person).
There are many examples in the unit tes project.
Is there a way to get all types used inside C# method?
For example,
public int foo(string str)
{
Bar bar = new Bar();
string x = "test";
TEST t = bar.GetTEST();
}
would return: Bar, string and TEST.
All I can get now is the method body text using EnvDTE.CodeFunction. Maybe there is a better way to achieve it than trying to parse this code.
I'm going to take this opportunity to post up a proof of concept I did because somebody told me it couldn't be done - with a bit of tweaking here and there, it'd be relatively trivial to extend this to extract out all referenced Types in a method - apologies for the size of it and the lack of a preface, but it's somewhat commented:
void Main()
{
Func<int,int> addOne = i => i + 1;
Console.WriteLine(DumpMethod(addOne));
Func<int,string> stuff = i =>
{
var m = 10312;
var j = i + m;
var k = j * j + i;
var foo = "Bar";
var asStr = k.ToString();
return foo + asStr;
};
Console.WriteLine(DumpMethod(stuff));
Console.WriteLine(DumpMethod((Func<string>)Foo.GetFooName));
Console.WriteLine(DumpMethod((Action)Console.Beep));
}
public class Foo
{
public const string FooName = "Foo";
public static string GetFooName() { return typeof(Foo).Name + ":" + FooName; }
}
public static string DumpMethod(Delegate method)
{
// For aggregating our response
StringBuilder sb = new StringBuilder();
// First we need to extract out the raw IL
var mb = method.Method.GetMethodBody();
var il = mb.GetILAsByteArray();
// We'll also need a full set of the IL opcodes so we
// can remap them over our method body
var opCodes = typeof(System.Reflection.Emit.OpCodes)
.GetFields()
.Select(fi => (System.Reflection.Emit.OpCode)fi.GetValue(null));
//opCodes.Dump();
// For each byte in our method body, try to match it to an opcode
var mappedIL = il.Select(op =>
opCodes.FirstOrDefault(opCode => opCode.Value == op));
// OpCode/Operand parsing:
// Some opcodes have no operands, some use ints, etc.
// let's try to cover all cases
var ilWalker = mappedIL.GetEnumerator();
while(ilWalker.MoveNext())
{
var mappedOp = ilWalker.Current;
if(mappedOp.OperandType != OperandType.InlineNone)
{
// For operand inference:
// MOST operands are 32 bit,
// so we'll start there
var byteCount = 4;
long operand = 0;
string token = string.Empty;
// For metadata token resolution
var module = method.Method.Module;
Func<int, string> tokenResolver = tkn => string.Empty;
switch(mappedOp.OperandType)
{
// These are all 32bit metadata tokens
case OperandType.InlineMethod:
tokenResolver = tkn =>
{
var resMethod = module.SafeResolveMethod((int)tkn);
return string.Format("({0}())", resMethod == null ? "unknown" : resMethod.Name);
};
break;
case OperandType.InlineField:
tokenResolver = tkn =>
{
var field = module.SafeResolveField((int)tkn);
return string.Format("({0})", field == null ? "unknown" : field.Name);
};
break;
case OperandType.InlineSig:
tokenResolver = tkn =>
{
var sigBytes = module.SafeResolveSignature((int)tkn);
var catSig = string
.Join(",", sigBytes);
return string.Format("(SIG:{0})", catSig == null ? "unknown" : catSig);
};
break;
case OperandType.InlineString:
tokenResolver = tkn =>
{
var str = module.SafeResolveString((int)tkn);
return string.Format("('{0}')", str == null ? "unknown" : str);
};
break;
case OperandType.InlineType:
tokenResolver = tkn =>
{
var type = module.SafeResolveType((int)tkn);
return string.Format("(typeof({0}))", type == null ? "unknown" : type.Name);
};
break;
// These are plain old 32bit operands
case OperandType.InlineI:
case OperandType.InlineBrTarget:
case OperandType.InlineSwitch:
case OperandType.ShortInlineR:
break;
// These are 64bit operands
case OperandType.InlineI8:
case OperandType.InlineR:
byteCount = 8;
break;
// These are all 8bit values
case OperandType.ShortInlineBrTarget:
case OperandType.ShortInlineI:
case OperandType.ShortInlineVar:
byteCount = 1;
break;
}
// Based on byte count, pull out the full operand
for(int i=0; i < byteCount; i++)
{
ilWalker.MoveNext();
operand |= ((long)ilWalker.Current.Value) << (8 * i);
}
var resolved = tokenResolver((int)operand);
resolved = string.IsNullOrEmpty(resolved) ? operand.ToString() : resolved;
sb.AppendFormat("{0} {1}",
mappedOp.Name,
resolved)
.AppendLine();
}
else
{
sb.AppendLine(mappedOp.Name);
}
}
return sb.ToString();
}
public static class Ext
{
public static FieldInfo SafeResolveField(this Module m, int token)
{
FieldInfo fi;
m.TryResolveField(token, out fi);
return fi;
}
public static bool TryResolveField(this Module m, int token, out FieldInfo fi)
{
var ok = false;
try { fi = m.ResolveField(token); ok = true; }
catch { fi = null; }
return ok;
}
public static MethodBase SafeResolveMethod(this Module m, int token)
{
MethodBase fi;
m.TryResolveMethod(token, out fi);
return fi;
}
public static bool TryResolveMethod(this Module m, int token, out MethodBase fi)
{
var ok = false;
try { fi = m.ResolveMethod(token); ok = true; }
catch { fi = null; }
return ok;
}
public static string SafeResolveString(this Module m, int token)
{
string fi;
m.TryResolveString(token, out fi);
return fi;
}
public static bool TryResolveString(this Module m, int token, out string fi)
{
var ok = false;
try { fi = m.ResolveString(token); ok = true; }
catch { fi = null; }
return ok;
}
public static byte[] SafeResolveSignature(this Module m, int token)
{
byte[] fi;
m.TryResolveSignature(token, out fi);
return fi;
}
public static bool TryResolveSignature(this Module m, int token, out byte[] fi)
{
var ok = false;
try { fi = m.ResolveSignature(token); ok = true; }
catch { fi = null; }
return ok;
}
public static Type SafeResolveType(this Module m, int token)
{
Type fi;
m.TryResolveType(token, out fi);
return fi;
}
public static bool TryResolveType(this Module m, int token, out Type fi)
{
var ok = false;
try { fi = m.ResolveType(token); ok = true; }
catch { fi = null; }
return ok;
}
}
If you can access the IL for this method, you might be able to do something suitable. Perhaps look at the open source project ILSpy and see whether you can leverage any of their work.
As others have mentioned, if you had the DLL you could use something similar to what ILSpy does in its Analyze feature (iterating over all the IL instructions in the assembly to find references to a specific type).
Otherwise, there is no way to do it without parsing the text into a C# Abstract Syntax Tree, AND employing a Resolver - something that can understand the semantics of the code well enough to know if "Bar" in your example is indeed a name of a type that is accessible from that method (in its "using" scope), or perhaps the name of a method, member field, etc... SharpDevelop contains a C# parser (called "NRefactory") and also contains such a Resolver, you can look into pursuing that option by looking at this thread, but beware that it is a fair amount of work to set it up to work right.
I just posted an extensive example of how to use Mono.Cecil to do static code analysis like this.
I also show a CallTreeSearch enumerator class that can statically analyze call trees, looking for certain interesting things and generating results using a custom supplied selector function, so you can plug it with your 'payload' logic, e.g.
static IEnumerable<TypeUsage> SearchMessages(TypeDefinition uiType, bool onlyConstructions)
{
return uiType.SearchCallTree(IsBusinessCall,
(instruction, stack) => DetectTypeUsage(instruction, stack, onlyConstructions));
}
internal class TypeUsage : IEquatable<TypeUsage>
{
public TypeReference Type;
public Stack<MethodReference> Stack;
#region equality
// ... omitted for brevity ...
#endregion
}
private static TypeUsage DetectTypeUsage(
Instruction instruction, IEnumerable<MethodReference> stack, bool onlyConstructions)
{
TypeDefinition resolve = null;
{
TypeReference tr = null;
var methodReference = instruction.Operand as MethodReference;
if (methodReference != null)
tr = methodReference.DeclaringType;
tr = tr ?? instruction.Operand as TypeReference;
if ((tr == null) || !IsInterestingType(tr))
return null;
resolve = tr.GetOriginalType().TryResolve();
}
if (resolve == null)
throw new ApplicationException("Required assembly not loaded.");
if (resolve.IsSerializable)
if (!onlyConstructions || IsConstructorCall(instruction))
return new TypeUsage {Stack = new Stack<MethodReference>(stack.Reverse()), Type = resolve};
return null;
}
This leaves out a few details
implementation of IsBusinessCall, IsConstructorCall and TryResolve as these are trivial and serve as illustrative only
Hope that helps
The closest thing to that that I can think of are expression trees. Take a look at the documentation from Microsoft.
They are very limited however and only work on simple expressions and not full methods with statement bodies.
Edit: Since the intention of the poster was to find class couplings and used types, I would suggest using a commercial tool like NDepend to do the code analysis as an easy solution.
This definitely cannot be done from reflection (GetMethod(), Expression Trees, etc.). As you mentioned, using EnvDTE's CodeModel is an option since you get line-by-line C# there, but using it outside Visual Studio (that is, processing an already existing function, not in your editor window) is nigh-impossible, IMHO.
But I can recommend Mono.Cecil, which can process CIL code line-by-line (inside a method), and you can use it on any method from any assembly you have reference to. Then, you can check every line if it is a variable declaration (like string x = "test", or a methodCall, and you can get the types involved in those lines.
With reflection you can get the method. This returns a MethodInfo object, and with this object you cannot get the types which are used in the method. So I think the answer is that you cannot get this native in C#.
Whilst working with the MSI Interop API I have come across some unusual behaviour which is causing my application to crash. It is simple enough to 'handle' the problem but I would like to know more about 'why' this is happening.
My first call to MSIEnumRelatedProducts returns an value of 0 and correctly sets my string buffer to a productcode. My understanding is that this would only happen if the given upgradecode (passed as a parm to the method) has a 'related family product' currently installed, otherwise it would return 259 ERROR_NO_MORE_ITEMS.
However when I subsequently call MSIGetProductInfo using the same productcode I get the return value 1605, "This action is only valid for products that are currently installed.".
Does anyone have any ideas under what circumstances this might happen? It is 100% repeatable on 1 machine but I have not yet managed to get reproduction steps on another machine.
All our products are build with the Wix Property "AllUsers=1" so products should be installed for all users, not just one.
Any ideas/suggestions appreciated.
Thanks
Ben
Update:
I've noticed that when running the problem msi package with logging the following line is shown:
MSI (s) (88:68) [12:15:50:235]: FindRelatedProducts: could not read ASSIGNMENTTYPE info for product '{840C...etc.....96}'. Skipping...
Does anyone have any idea what this might mean?
Update: Code sample.
do
{
result = _MSIApi.EnumRelatedProducts(upgradeCode.ToString("B"), 0,
productIndex, productCode);
if (result == MSIApi.ERROR_BAD_CONFIGURATION ||
result == MSIApi.ERROR_INVALID_PARAMETER ||
result == MSIApi.ERROR_NOT_ENOUGH_MEMORY)
{
throw new MSIInteropException("Failed to check for related products",
new Win32Exception((Int32)result));
}
if(!String.IsNullOrEmpty(productCode.ToString()))
{
Int32 size = 255;
StringBuilder buffer = new StringBuilder(size);
Int32 result = (Int32)_MSIApi.GetProductInfo(productCode,
MSIApi.INSTALLPROPERTY_VERSIONSTRING,
buffer,
ref size);
if (result != MSIApi.ERROR_SUCCESS)
{
throw new MSIInteropException("Failed to get installed version",
new Win32Exception(result));
}
version = new Version(buffer.ToString());
}
productCode = new StringBuilder(39);
productIndex++;
}
while (result == MSIApi.ERROR_SUCCESS);
I suppose that you try to use MsiGetProductInfo to get a property other as described in documentation. For example you can get in the way the value of the "PackageCode" property (INSTALLPROPERTY_PACKAGECODE) without any problem, but you can't get the value of the "UpgradeCode" property with respect of MsiGetProductInfo and receive the error 1605 (ERROR_UNKNOWN_PRODUCT).
UPDATED: OK, now I understand you problem. How you can find in the internet there are a bug in MsiGetProductInfo, so it work not always. Sometime it get back 1605 (ERROR_UNKNOWN_PRODUCT) or 1608 (ERROR_UNKNOWN_PROPERTY) back. In the case as the only workaround is to get the version property manually. I could reproduce the problem which you described on my computer with the Microsoft Office Outlook 2010 MUI (UpgradeCode = "{00140000-001A-0000-0000-0000000FF1CE}") and wrote a workaround where I get the product version from the registry. In the example I get information only from HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products. If you have an interest to products installed not only for all users you have to modify the program. Here is the code
using System;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace EnumInstalledMsiProducts {
internal static class NativeMethods {
internal const int MaxGuidChars = 38;
internal const int NoError = 0;
internal const int ErrorNoMoreItems = 259;
internal const int ErrorUnknownProduct = 1605;
internal const int ErrorUnknownProperty = 1608;
internal const int ErrorMoreData = 234;
[DllImport ("msi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int MsiEnumRelatedProducts (string lpUpgradeCode, int dwReserved,
int iProductIndex, //The zero-based index into the registered products.
StringBuilder lpProductBuf); // A buffer to receive the product code GUID.
// This buffer must be 39 characters long.
// The first 38 characters are for the GUID, and the last character is for
// the terminating null character.
[DllImport ("msi.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern Int32 MsiGetProductInfo (string product, string property,
StringBuilder valueBuf, ref Int32 cchValueBuf);
}
class Program {
static int GetProperty(string productCode, string propertyName, StringBuilder sbBuffer) {
int len = sbBuffer.Capacity;
sbBuffer.Length = 0;
int status = NativeMethods.MsiGetProductInfo (productCode,
propertyName,
sbBuffer, ref len);
if (status == NativeMethods.ErrorMoreData) {
len++;
sbBuffer.EnsureCapacity (len);
status = NativeMethods.MsiGetProductInfo (productCode, propertyName, sbBuffer, ref len);
}
if ((status == NativeMethods.ErrorUnknownProduct ||
status == NativeMethods.ErrorUnknownProperty)
&& (String.Compare (propertyName, "ProductVersion", StringComparison.Ordinal) == 0 ||
String.Compare (propertyName, "ProductName", StringComparison.Ordinal) == 0)) {
// try to get vesrion manually
StringBuilder sbKeyName = new StringBuilder ();
sbKeyName.Append ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products\\");
Guid guid = new Guid (productCode);
byte[] buidAsBytes = guid.ToByteArray ();
foreach (byte b in buidAsBytes) {
int by = ((b & 0xf) << 4) + ((b & 0xf0) >> 4); // swap hex digits in the byte
sbKeyName.AppendFormat ("{0:X2}", by);
}
sbKeyName.Append ("\\InstallProperties");
RegistryKey key = Registry.LocalMachine.OpenSubKey (sbKeyName.ToString ());
if (key != null) {
string valueName = "DisplayName";
if (String.Compare (propertyName, "ProductVersion", StringComparison.Ordinal) == 0)
valueName = "DisplayVersion";
string val = key.GetValue (valueName) as string;
if (!String.IsNullOrEmpty (val)) {
sbBuffer.Length = 0;
sbBuffer.Append (val);
status = NativeMethods.NoError;
}
}
}
return status;
}
static void Main () {
string upgradeCode = "{00140000-001A-0000-0000-0000000FF1CE}";
StringBuilder sbProductCode = new StringBuilder (39);
StringBuilder sbProductName = new StringBuilder ();
StringBuilder sbProductVersion = new StringBuilder (1024);
for (int iProductIndex = 0; ; iProductIndex++) {
int iRes = NativeMethods.MsiEnumRelatedProducts (upgradeCode, 0, iProductIndex, sbProductCode);
if (iRes != NativeMethods.NoError) {
// NativeMethods.ErrorNoMoreItems=259
break;
}
string productCode = sbProductCode.ToString();
int status = GetProperty (productCode, "ProductVersion", sbProductVersion);
if (status != NativeMethods.NoError) {
Console.WriteLine ("Can't get 'ProductVersion' for {0}", productCode);
}
status = GetProperty (productCode, "ProductName", sbProductName);
if (status != NativeMethods.NoError) {
Console.WriteLine ("Can't get 'ProductName' for {0}", productCode);
}
Console.WriteLine ("ProductCode: {0}{3}ProductName:'{1}'{3}ProductVersion:'{2}'{3}",
productCode, sbProductName, sbProductVersion, Environment.NewLine);
}
}
}
}
which produce on my computer the correct output
ProductCode: {90140000-001A-0407-0000-0000000FF1CE}
ProductName:'Microsoft Office Outlook MUI (German) 2010'
ProductVersion:'14.0.4763.1000'
ProductCode: {90140000-001A-0419-0000-0000000FF1CE}
ProductName:'Microsoft Office Outlook MUI (Russian) 2010'
ProductVersion:'14.0.4763.1000'
instead of errors in the ProductVersion before.
You should look at Windows Installer XML's Deployment Tools Foundation. It has a very mature MSI Interop ( Microsoft.Deployment.WindowsInstaller ) which will make writing and testing this code a lot easier.
I see you already have WiX ( hopefully v3+ ) so look for it in the C:\Program Files\Windows Installer XML v3\SDK folder.