Getting a return value from a methodInfo.invoke - invoke

How do I get a return value (int) from a methodInfo.invoke?
What makes it difficult for me is the fact that I use a string variable to call the method.
Check the example below:
if (Convert.ToBoolean(getParameterFromXML("issue", k, 1)) == true)
{
m = k + 1;
MethodInfo methodInfo = typeof(frmDetails).GetMethod("Issue" + m);
methodInfo.Invoke(this, Parameters);
}
What can I do? Any help would be appreciated.

When I read this you get the result of the method back from the Invoke-call. It is returned as an object so you need to cast it to a specific type.
var returnValue = (int) methodInfo.Invoke(this, Parameters);

Related

INSERT INTO MSSQL from textfile contains NULL values on INTEGER

I have problems to insert/bulk NULL values from textfile into MSSQL.
When replace NULL value with a number it works with no problem.
2 Columns is set to ALLOW NULLS,
PublicationCaption and PublicationNumber
Here is example of text file
1#DI#Dagens Industri#435#358#2016-10-19
2#DN#Dagens Nyheter#NULL#359#2016-10-19
I think there is some problem with the foreach loop in code where I need add something to make this work.
Here is the code I'm using
public static DataTable Publication()
{
DataTable dtPublication = new DataTable();
dtPublication.Columns.AddRange(new DataColumn[6] { new DataColumn("ID", System.Type.GetType("System.Int32")),
new DataColumn("PublicationCode", System.Type.GetType("System.String")),
new DataColumn("PublicationCaption",System.Type.GetType("System.String")),
new DataColumn("PublicationNumber", System.Type.GetType("System.Int32")),
new DataColumn("ProductNumber", System.Type.GetType("System.Int32")),
new DataColumn("CreatedDate", System.Type.GetType("System.DateTime")),
});
for (int i = 0; i < dtPublication.Columns.Count; i++)
{
dtPublication.Columns[i].AllowDBNull = true;
}
string txtData = File.ReadAllText(#"C:\Publication2.txt", System.Text.Encoding.Default);
foreach (string row in txtData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dtPublication.Rows.Add();
int i = 0;
foreach (string cell in row.Split('#'))
{
dtPublication.Rows[dtPublication.Rows.Count - 1][i] = cell;
i++;
}
}
}
return dtPublication;
}
Im getting (The input string had an incorrect format. Unable to store in the PublicationNumber column. Type Int32 is expected.) when DEBUGGING.
Please I need some advise, help with this to solve the problem.
Thanks for your time.
The database doesn't know that the "NULL" string you try to insert actually means a null value. To fix this, change the "NULL" string to DBNull.Value:
if (cell == "NULL")
dtPublication.Rows[dtPublication.Rows.Count - 1][i] = DBNull.Value;
else
dtPublication.Rows[dtPublication.Rows.Count - 1][i] = cell;
There is no feature that translates a string "NULL" to a nullable field in a DataTable. You have to implement it yourself:
object value = DBNull.Value;
if(!"NULL".Equals(cell, StringComparison.InvariantCultureIgnoreCase))
value = cell;
dtPublication.Rows[dtPublication.Rows.Count - 1][i] = value;

Whole Structure is being replaced with the last pointer Value

In my program I have used an array of pointers as a structure variable to get first name and second name from the user.
The following is my function call statement:
ret_val = update_person(&ptr_person[person_index],f_name,s_name);
where ptr_person[SIZE] is a pointer variable and f_name and s_name are character array variables.
The following is my function definition where name_ret is int:
name_ret update_person(person_name_et **person,char *first_arg,char *second_arg)
{
int val = SUCCESS, val1 = SUCCESS,val2= SUCCESS;
int f_len = sizeof(first_arg);
int s_len = sizeof(second_arg);
val2 = remove_newline(first_arg);
val1 = remove_newline(second_arg);
val = allocate_person(person, f_len, s_len);
if((val && val1) == SUCCESS)
{
(*person)->first_name = first_arg;
(*person)->second_name = second_arg;
return SUCCESS;
}
else
{
return FAILURE;
}
}
The problem in the code is it works fine at the instance but when the function is called next iteration the ptr_Person[0] is replaced with ptr_person[1] and if we have 5 instances then all the 5 variables are replaced by the last values.

dynamic_cast to interface won't compile

I have some C# code like this:
string GetString(int n, CultureInfo cultureInfo)
{
T value = data[n];
IFormattable formattable = value as IFormattable;
if (formattable != null)
return formattable.ToString(null, cultureInfo)
return value.ToString();
}
I'm trying to do the same thing in a C++ generic class:
String^ GetString(int n, CultureInfo^ cultureInfo)
{
T value = data[n];
IFormattable^ formattable = dynamic_cast<IFormattable^>(value);
if (formattable != nullptr)
return formattable->ToString(nullptr, cultureInfo);
return value->ToString();
}
When I try to compile it, I get:
error C2681: 'T': invalid expression type for dynamic_cast
I'm not sure why it won't compile as I was under the understanding that dynamic_cast was similar to the as operator in C#
I saw someone mention that there are issues with generics and dynamic_cast in another post, and was able to figure it out.
I was thinking the problem was with IFormattable, but the problem is with 'value'.
It compiles fine and works if I cast the value to Object^ first:
String^ GetString(int n, CultureInfo^ cultureInfo)
{
T value = data[n];
IFormattable^ formattable = dynamic_cast<IFormattable^>((Object^)value);
if (formattable != nullptr)
return formattable->ToString(nullptr, cultureInfo);
return value->ToString();
}

Function and delegate literals in D

Reading TDPL about function and delegate literals (5.6.1)
auto f = (int i) {};
assert(is(f == function));
I've got an assertion failure. Is this assertion correct?
I tried the following:
int z = 5;
auto f = (int i) { return i < 5; };
auto d = (int i) { return i < z; };
assert(is(typeof(f) == typeof(d)));
Assertion is valid there. Actually f is a delegate, not a function even if it doesn't need a frame pointer to access local variables. Is this a bug?
Also, I do not understand how assert(is(f == function)); should work.
I tried assert(is(f == delegate)); but it was failed also. What's wrong?
I use DMD32 D Compiler v2.053
UPDATE
auto f = (int i) {};
assert(is(typeof(f) == delegate))
Works correct, although there is no reason to be a delegate
But
auto f = function (int i) {};
assert(is(typeof(f) == void function(int))); // correct
assert(is(typeof(f) == function)); // failed!!!!!
Miracle. It seems D2 is not ready for production use yet.
"f" is a variable. The is expression compares types. This should work:
assert(is(typeof(f) == delegate));
If you want to create a function instead of a delegate, you can use the function literal syntax:
auto f = function (int i) { ... };
assert(is(typeof(f) == function)); // should be true
If the function literal syntax is not used, the literal is assumed to be delegate (Expressions, look under "Function Literals". This makes sense because D should not change the type based on the whether the body of the literal needs the stack frame (this would be super screwy). EDIT: TDPL does actually specify that the compiler will infer a function instead of a delegate if it can, regardless of the "function" keyword. This seems like a poor idea to me, so this might be something that has been dropped.
As to why the is(f == function) doesn't work, this looks like a regression.
You might find isFunctionPointer and isDelegate helpful.
Update:
See this, taken from traits.d:
template isSomeFunction(/+###BUG4217###+/T...)
if (/+###BUG4333###+/staticLength!(T) == 1)
{
enum bool isSomeFunction = isSomeFunction_bug4333!(T).isSomeFunction;
}
private template isSomeFunction_bug4333(T...)
{
/+###BUG4333###+/enum dummy__ = T.length;
static if (is(typeof(& T[0]) U : U*) && is(U == function))
// T is a function symbol.
enum bool isSomeFunction = true;
else static if (is(T[0] W) || is(typeof(T[0]) W))
// T is an expression or a type. Take the type of it and examine.
static if (is(W F : F*) && is(F == function))
enum bool isSomeFunction = true; // function pointer
else enum bool isSomeFunction = is(W == function) || is(W == delegate);
else enum bool isSomeFunction = false;
}
I think it might explain some things.
In other words:
void main()
{
static if (is(typeof(&main) T : T*)) static assert( is(T == function));
static if (is(typeof(&main) U)) static assert(!is(U == function));
}

What is the linq equivalent to the SQL IN operator

With linq I have to check if a value of a row is present in an array.
The equivalent of the sql query:
WHERE ID IN (2,3,4,5)
How can I do it?
.Contains
var resultset = from x in collection where new[] {2,3,4,5}.Contains(x) select x
Of course, with your simple problem, you could have something like:
var resultset = from x in collection where x >= 2 && x <= 5 select x
Perform the equivalent of an SQL IN with IEnumerable.Contains().
var idlist = new int[] { 2, 3, 4, 5 };
var result = from x in source
where idlist.Contains(x.Id)
select x;
db.SomeTable.Where(x => new[] {2,3,4,5}.Contains(x));
or
from x in db.SomeTable
where new[] {2,3,4,5}.Contains(x)
Intersect and Except are a little more concise and will probably be a bit faster too.
IN
collection.Intersect(new[] {2,3,4,5});
NOT IN
collection.Except(new[] {2,3,4,5});
or
Method syntax for IN
collection.Where(x => new[] {2,3,4,5}.Contains(x));
and NOT IN
collection.Where(x => !(new[] {2,3,4,5}.Contains(x)));
An IEnumerable<T>.Contains(T) statement should do what you're looking for.
A very basic example using .Contains()
List<int> list = new List<int>();
for (int k = 1; k < 10; k++)
{
list.Add(k);
}
int[] conditionList = new int[]{2,3,4};
var a = (from test in list
where conditionList.Contains(test)
select test);
The above situations work when the Contains function is used against primitives, but what if you are dealing with objects (e.g. myListOrArrayOfObjs.Contains(efObj))?
I found a solution! Convert your efObj into a string, thats separated by _ for each field (you can almost think of it as a CSV representation of your obj)
An example of such may look like this:
var reqAssetsDataStringRep = new List<string>();
foreach (var ra in onDemandQueueJobRequest.RequestedAssets)
{
reqAssetsDataStringRep.Add(ra.RequestedAssetId + "_" + ra.ImageId);
}
var requestedAssets = await (from reqAsset in DbContext.RequestedAssets
join image in DbContext.Images on reqAsset.ImageId equals image.Id
where reqAssetsDataStringRep.Contains(reqAsset.Id + "_" + image.Id)
select reqAsset
).ToListAsync();
You can write help-method:
public bool Contains(int x, params int[] set) {
return set.Contains(x);
}
and use short code:
var resultset = from x in collection
where Contains(x, 2, 3, 4, 5)
select x;
Following is a generic extension method that can be used to search a value within a list of values:
public static bool In<T>(this T searchValue, params T[] valuesToSearch)
{
if (valuesToSearch == null)
return false;
for (int i = 0; i < valuesToSearch.Length; i++)
if (searchValue.Equals(valuesToSearch[i]))
return true;
return false;
}
This can be used as:
int i = 5;
i.In(45, 44, 5, 234); // Returns true
string s = "test";
s.In("aa", "b", "c"); // Returns false
This is handy in conditional statements.