Creating a Guid -> conversion from VB to C# - c#

I have the following code in VB.Net and I'm trying to convert it to C#.
listContacts = ACT_FRAMEWORK.Contacts.GetContactsByID(Nothing, New Guid() {New Guid(ContactID)})
Below is my attempt so far:
Guid[] test = new Guid[1];
test[0] = Guid.NewGuid(ContactID);
contactList = actApp.Contacts.GetContactsByID(null, test);
The abover errors because NewGuid() takes no arguments. I have also tried.
test[0] = contactID1;
However, you can't convert from string to Guid. Can anyone help with this?

Guid.NewGuid is a method, and you're not calling that method from your VB code - you're calling the constructor accepting a string. You can call that same constructor in C#:
// Using an array initializer for simplicity
Guid[] test = { new Guid(ContactID) };
Or if you want to make the call in one line as per your VB code:
contactList = actApp.Contacts.GetContactsByID(null, new[] { new Guid(ContactID) });
I think it's a shame that NewGuid has that name rather than CreateGuid, but such is life :(
Using Guid.Parse will work too of course - judging by the .NET Core source code they behave extremely similarly; the constructor just handles overflow exceptions slightly differently.

Try Guid.Parse(ContactID.ToString());
if ContactID is actually a string , simple write Guid.Parse(ContactID);

Related

Reduce duplication - Create delegate from an instance method

I am working with an existing, slightly complex relationship between objects. After some refactoring for the sake of understandability, my code now looks like this:
TemplateColorList colors = new TemplateColorList();
var template = new Template {
TextElements = CreateTextElements(textElementData,
/* -> */ (textElement, colorParam1, colorParam2) => colors.AddTextColor(textElement, colorParam1, colorParam2)
),
ClipArtElements = CreateClipArtElements(clipArtElementData,
/* -> */ (clipArtElement, colorParam) => colors.AddClipArtColor(clipArtElement, colorParam)
),
Colors = colors,
};
I see duplication that I think can be removed, though - The delegates are just passing parameters as-is to colors methods. Is there a way to create a delegate from an instance method (not static) without duplicating the parameters?
Converting comments into an answer...
"Isn't it just CreateTextElements( textElementData, colors.AddTextColor ) without this extra delegate?" - #WiktorZychla
"If you've ever forgotten the parenthesis on a method call, you might have gotten a compiler error: Cannot convert method group to something. This is the opposite. Now you want to refer to the method without parenthesis or arguments because the method is the argument." - #ScottHannen (emphasis mine)
Thanks for the help! I was wrongly making an assumption that the types wouldn't work out here. Taking their advice, my code now looks like:
TemplateColorList colors = new TemplateColorList();
var template = new Template {
TextElements = CreateTextElements(textElementData, colors.AddTextColor),
ClipArtElements = CreateClipArtElements(clipArtElementData, colors.AddClipArtColor),
Colors = colors,
};

Declare variable inside String.format in c#

How can i declare a variable inside String.format and use it again like :
String.Format("{0} {1}", int t = 1, new string[] { "a", "b" }.ElementAt(t));
update
I just want to learn something new and type the code in one line.
It is not necessary in this case, but useful in others.
update
I found another solution :
int indx;
var st = String.Format("{0} {1}", (indx=1), new string[] { "a", "b" }.ElementAt(indx));
It would be good if you would share reason why you try to do it this way, and maybe tell us what are you working on.
Your code to work should look like this
int t = 1;
string[] myArray = new string[] { "a", "b" };
Console.WriteLine(string.Format("{0} {1}", t, myArray[t]));
What you are attempting to do seems to be without any sense, first of all it will not work. Doing stuff your way makes it impossible to access t and array you created and even if it worked it would be same as static string string myString = "1 b". Your way you make it impossible to manipulate these variables because they would only exist in context of that one line and would be back to their initial value when it gets executed each time.
It is not possible. Consider string.format as a method with few overloads, which takes few set of parameters as mentioned in MSDN link. Your way of calling the method does not satisfy your intent hence it would fail.
I don't understand any reason why you would try to do something like this.

Can I GET and SET an array in C#?

HOMEWORK QUESTION:
I need to create a simple trivia game that reads from a CSV file. My data for a particular question is structured as follows: "Question;AnswerA;AnswerB;AnswerC;AnswerD;CorrectAnswerLetter".
We're using a series of getters and setters to hold all the relevant data for a single question object, and I'm running into a problem with the array I've created to hold the four answers.
In my constructor, I'm using this code--which I believe instantiates the Answer array in question:
class TriviaQuestionUnit
{
...
const int NUM_ANSWERS = 4;
string[] m_Answers = new String[NUM_ANSWERS];
public string[] Answer
{
get { return m_Answers[]; }
set { m_Answers = value[];
}
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
}
I'm accessing the getter and setter from my TriviaQuestionBank method, which includes this code:
...
const int NUM_QUESTIONS = 15;
TriviaQuestionUnit[] m_Questions = new TriviaQuestionUnit[NUM_QUESTIONS];
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
I'm using using StreamReader to read a line of input from my file
...
char delim = ';';
String[] inputValues = inputText.Split(delim);
...
parses the input in an array from which I create the question data. For my four answers, index 1 through 4 in the inputValues array, I populate this question's array with four answers.
...
for (int i = 0; i < NUM_ANSWERS; i++)
{
m_Questions[questionCounter].Answer[i] = inputValues[i + 1];
}
...
I'm getting errors of Syntax code, value expected on the getters/setters in my constructor, and if I change the variable to m_Answers[NUM_QUESTIONS] I get an error that I can't implicitly convert string to String[].
Hopefully I've posted enough code for someone to help point me in the right direction. I feel like I'm missing something obvious, but I just cannot make this work.
Your code has some errors that will cause compilation errors, so my first lesson for you is going to be: listen to the compiler. Some of the errors might seem a bit hard to understand sometimes, but I can ensure you that a lot of other people have had the same problems before; googling a compiler error often gives you examples from other people that are similar to your issue.
You say "In my constructor", but the problem is that your code does not have a constructor. You do however initialize fields and properties on your class and surely enough, the compiler will create a default constructor for you, but you have not defined one yourself. I am not saying that your code does not work because you do not have a constructor, but you might be using the wrong terms.
The first problem is in your first code snippet inside TriviaQuestionUnit. Your first two lines are working correctly, you are creating a constant integer with the value 4 that you use to determine how large your array is going to be and then you initialize the array with that given number.
When you do new string[NUM_ANSWERS] this will create an array, with default (empty) values.
The first problem that arises in your code is the getters and setters. The property expects you to return an array of strings which the method signature in fact is telling us:
public string[] Answer
However, looking at the getter and setter, what is it that you return?
m_Answers is a "reference" to your array, hence that whenever you write m_Answers you are referring to that array. So what happens when we add the square brackets?
Adding [] after the variable name of an array indicates that we want to retrieve a value from within the array. This is called the indexer, we supply it with an index of where we want to retrieve the value from within the array (first value starts at index 0). However, you don't supply it with a value? So what is returned?
Listen to the compiler!
Indexer has 1 parameter(s) but is invoked with (0) argument(s)
What does this tell you? It tells you that it doesn't expect the empty [] but it would expect you to supply the indexer with a number, for instance 0 like this: [0]. The problem with doing that here though, is that this would be a miss-match to the method signature.
So what is it that we want?
We simply want to return the array that we created, so just remove [] and return m_Answers directly like this:
public string[] Answer
{
get { return m_Answers; }
set { m_Answers = value; }
}
Note that you were also missing a curly bracket at the end if the set.
When fixing this, there might be more issues in your code, but trust the compiler and try to listen to it!

Compile a C# Array at runtime and use it in code?

I know C# code can be compiled at runtime using C#. However I'm very very shaky at it since I just read about it a few minutes ago. I learn a lot better by examples. So tell me. If I want to compile something like:
// MapScript.CS
String[] LevelMap = {
"WWWWWWWWWWWWWWWWWWW",
"WGGGGGGGGGGGGGGGGGW",
"WGGGGGGGGGGGGGGGGGW",
"WWWWWWWWWWWWWWWWWWW" };
and use this array in my code, how would I go about it?
In pseudocode I want to do something like this:
Open("MapScript.CS");
String[] levelMap = CompileArray("levelMap");
// use the array
LINQ Expression trees are probably the friendliest way of doing this: Perhaps something like:
http://msdn.microsoft.com/en-us/library/system.linq.expressions.newarrayexpression.aspx
http://msdn.microsoft.com/en-us/library/bb357903.aspx
You can also generate the IL using OpCodes (OpCodes.Newarr). Easy if you are comfortable with stack-based programming (otherwise, can be challenging).
Lastly, you can use the CodeDom (which your pseudocode resembles), but--while the most powerful tool--it is less ideal for quick dynamic methods. It requires file system permissions and manual reference resolution since you are working closely with the compiler.
Sample from MSDN
var ca1 = new CodeArrayCreateExpression("System.Int32", 10);
var cv1 = new CodeVariableDeclarationStatement("System.Int32[]", "x", ca1);
Source - Creating Arrays with the Code DOM
If you want a straight up raw compile of a string, you can omit the object-oriented treatment of the statements and instead just build a big string. Something like:
var csc = new CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } } );
var cp = new CompilerParameters() {
GenerateExecutable = false,
OutputAssembly = outputAssemblyName,
GenerateInMemory = true
};
cp.ReferencedAssemblies.Add( "mscorlib.dll" );
cp.ReferencedAssemblies.Add( "System.dll" );
cp.ReferencedAssemblies.Add( "System.Core.dll" );
StringBuilder sb = new StringBuilder();
// The string can contain any valid c# code, but remember to resolve your references
sb.Append( "namespace Foo{" );
sb.Append( "using System;" );
sb.Append( "public static class MyClass{");
// your specific scenario
sb.Append( #"public static readonly string[] LevelMap = {
""WWWWWWWWWWWWWWWWWWW"",
""WGGGGGGGGGGGGGGGGGW"",
""WGGGGGGGGGGGGGGGGGW"",
""WWWWWWWWWWWWWWWWWWW"" };" );
sb.Append( "}}" );
// "results" will usually contain very detailed error messages
var results = csc.CompileAssemblyFromSource( cp, sb.ToString() );
It appears that you are wanting to compile C# code in order to load a list of strings in a text (C#) file into a string array variable.
You don't need a c# compiler to load a list of strings from a text file into an array in memory. Just put one string per line in your text file, and read the file line by line in your code, adding each line to a List<String>. When you're done, list.ToArray() will produce your array of strings.
You can create a class CompiledLevel that inherits from ILevel which proposes a static property Level of type String[].
Then, before compiling, create a fake CompiledLevel.cs file built from a template of class filled with content of LevelMap (wwwggg...) (sort of concatenation).
One compiled, call Level property on the compiled class.
Create a service/factory/whatever to make it fancy :)

Method returns a dynamic array of structs in c#, I Can't consume its return value

I'm trying to consume a DLL-located method in C#, which returns a dynamic array of structs. What ever I do, I receive the well-know "Object reference not set to an instance of an object" error, Here is my last code and it still tells that error:
string v_user = "kish";
string v_pass = "u";
string v_number = "p";
string v_address = "url has been replaced with this string";
string v_cid = "abc";
Cls_SMS.SMSReceive.STC_SMSReceive[] xts;
Cls_SMS.SMSReceive px = new Cls_SMS.SMSReceive();
// *** is the below line
xts = px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid);
int upper_bound = xts.GetUpperBound(0);
for (int counter = 0; counter < upper_bound; counter++)
{
Response.Write(xts[counter].Message.ToString());
Response.Write("<br>");
}
please note that my main problem is about receiving a dynamic array of structs with struct type name (Cls_SMS.SMSReceive.STC_SMSReceive) and other aspects such as connecting to the remote server is not my problem. I just want to allocate a dynamic array of vendor-defined structs to the left side of the assignment opeator in * line.
Please help me.
Thank you very much.
It is not clear how the px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid); method assigns the array, it probably doesn't assign it at all because of the exception. Here's how you could assign a dynamic array and return it:
public STC_SMSReceive[] ExtendReceiveSMS()
{
STC_SMSReceive[] result = new STC_SMSReceive[2];
result[0] = new STC_SMSReceive();
result[1] = new STC_SMSReceive();
return result;
}
Also if it is dynamic you might also take a look at List<T>:
public IList<STC_SMSReceive> ExtendReceiveSMS()
{
IList<STC_SMSReceive> result = new List<STC_SMSReceive>();
list.Add(new STC_SMSReceive());
list.Add(new STC_SMSReceive());
return result;
}
This has nothing to do with the strict array; simply, the library method you are using is returning null.
There are various possibilities here:
maybe returning null is an expected return value for some scenarios; check the documentation
maybe you need some additional configuration, or maybe you need to call some additional method (GetTheData() would be too hopeful ;p), or wait for some other event before this data is available - check the documentation
maybe it is simply a library bug; contact the vendor
If all 3 routes fail, personally I'd just open it reflector and look for a scenario that might return null. Then tell the vendor to fix the bug or clarify the documentation as appropriate.
If you replace your separate declaration of xts with:
var xts = px.ExtendReceiveSMS(v_user, v_pass, v_number, v_address, v_cid);
what type does Visual Studio now report xts to be?
You can tell by hovering over xts with your cursor and reading it off the tooltip.
Other than that if the vendor is reporting that it works for other users, you must have one (or more) of the arguments wrong. Ask the vendor for some example code that works so you can check to see if that connects to the server properly. If it does then the error is in the other arguments, if not then it's a problem with your connection to the server.

Categories

Resources