This kind question may be asked before, but I can't get my head around it, so I'll appreciate any help.
I have a message box where a type of error that i'm receiving by modbus communication is stored.
MessageBox.Show(String.Format("Error uploading: {0}", e.ReceivedData[0]));
e.ReceivedData[0] is holding the data that I want to show on the message box.
So, it might be 1 2 3 4 5 6 7. Those numbers represent type of operation failure.
However, I want to show the exact error message
1 - "UR_NOT_ACTIVE",
2 - "UR_OUT_OF_BOUND",
3 - "UR_INVALID_COMMAND"
and so on.
My plan was to store it in an enum, but I have no previous experience with c#, so it it more confusing than I thought.
Yes, use an enum:
public enum OperationFailureType
{
UR_NOT_ACTIVE = 1,
UR_OUT_OF_BOUND = 2,
UR_INVALID_COMMAND = 3
}
Now you can use enumValue.ToString to get the text and you can cast it to int to get the number.
MessageBox.Show($"Error uploading: {e.ReceivedData[0].ToString()}");
Presuming ReceivedData is now an array of this enum. If it's just an int[] and you can't change it you can cast it to the OperationFailureType:
OperationFailureType failureType = (OperationFailureType) e.ReceivedData[0];
MessageBox.Show($"Error uploading: {failureType.ToString()}");
Related
the thing I'm having the most trouble with is understanding the assignment here. I don't know if it's the fact if it's worded weird or that I'm just stupid. I'm not asking for you to do my assignment for me I just want to know if someone would explain what it's asking for.
UPDATE: apparently I now have to use enum on this so now I'm screwed
Please post the content of the question in your post, i.e. copy and past the text.
Secondly, break it down into sections.
1) You must write a program called IntArrayDemo.
2) The program must contain an array that stores 10 Integers (int).
int[] valueArray = new int[10] {1,2,3,4,5,6,7,8,9,10 };
3) The program will run until a sentinal value is entered (i.e. you type something that causes the program to quite, say 'q' or '-1').
while (Console.ReadKey().Key != ConsoleKey.Q) {
ConsoleKey k = Console.ReadKey().Key;
//Check the key here
}
4) The program will have 3 options -
4.1) View the entire array of integers from 0 to 9 (i.e. forwards)
4.2) View the entire array of integers from 9 to 0 (i.e. backwards)
4.3) View a specific location (i.e. you enter a number from 0 to 9, and you are shown the value at that point in the array.
You will need to display some sort of menu on the screen listing the options.
For each of the parts where you need to show the content of the array, use a for loop. While loops, or ForEach loops should never be used of you have a fixed number of things to iterate over.
"I don't know if it's the fact if it's worded weird or that I'm just stupid"
In this case, I'm not sure either of those options is accurate. Programming questions are worded quite carefully to force you to think about breaking the task into sections.
In professional programming, you will get all sorts of weirdly worded questions about how something can be done, and you must break down the problem into steps and solve each one.
It's easy to feel a little overwhelmed when you get a single paragraph with a lot of information in it, but breaking it down makes it much more manageable.
Always start with what you know for certain has to be done - in this case, the program must be called IntArrayDemo, so that's a good starting point.
'that stores an array of 10 integers' - good, more information! The program must have an array, which stores ints, and can hold 10 values.
We can infer from this (knowing that arrays start from 0) that our array must count from 0 to 9.
Enums
You mention that you need to use enums. Enums are just a data type, which you can define yourself.
Supposing you were writing a server program, and needed to easily see what state it was in.
The server can be in the following states at any time - Starting, Running, Stopping, Stopped.
You could use a string easily enough - String state = "Starting" would do the trick, but a string can hold any value.
As the server HAS to be in one of those states, an enum is better, as you can specify what those states are.
To declare an enum, you create it as follows...
enum SERVER_STATE { Starting, Running, Stopping, Stopped };
Then to use it....
SERVER_STATE CurrentServerState = SERVER_STATE.Stopped;
if (CurrentServerState == SERVER_STATE.Running) {
//Do something here only if the enum is set to 'Running'
}
If you wanted to use an enum to decide which option was chosen, you would need to do the following.
1) Get some text of the keyboard (the example using ReadChar above shows you how to do that)
2) Set an enum value based on what was entered
enum ACTION = { ListValuesForward, ListValueBackward, ListSpecificValue };
ACTION WhichOption;
//Our ConsoleKey object is called 'k', so....
if (k == ConsoleKey.F) {
WhichOption = ACTION.ListValuesForward;
}
if (WhichOption == Action.ListValuesForward) {
//Print out the array forwards
}
Knowing that we have an array, that counts from 0 to 9, we can work out that the best loop here is a for loop, as it's controlled by a counter variable.
If you always break a problem down like this, it becomes a lot less daunting.
Hopefully, this should explain the question clearly enough to get you started.
This question already has answers here:
how to implement non uniform probability distribution?
(3 answers)
Closed 9 years ago.
For example, I want to get random number from set S = {0, 1, 2, 3}. But instead of each number has same probability to shown (which is 25%), now I have different probability for each number, let say {50%, 30%, 20%, 10%}.
How do I code this? In Java or C# (I prefer C#).
The Alias Method is by far my favorite for doing this.
http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/
I haven't reviewed this code but it is a top google result.
Here is another much better explanation
http://pandasthumb.org/archives/2012/08/lab-notes-the-a.html
I actually use this question for interviews quite often since if you have never seen it before it can be pretty puzzling.
If the above is too much for you to implement there is a simpler one loop through the input solution.
Using PHP since it is easier to just show the code.
function getNumberFromDistribution($dist) {
$totalProbability = 0;
$randomNumber = mt_rand(0, mt_getrandmax()) / mt_getrandmax(); //uniform random number between 0-1
foreach($dist as $number => $chance) {
if (($totalProbability += $chance) <= $randomNumber) {
return $number;
}
}
return null; //only reachable on bad input
}
If the set is small you can build an array that contains the right number of each value you need to get your distribution eg. 1 1 1 2 2 3 would provide 3 times the likelihood of getting a 1 as it does of getting a 3. You would then use the length of the array to determine the random number that you use as an index.
I am getting this error when trying to serialize.
The answer to this question:
How to map System Enum's in Protobuf.Net
indicates that this is related to a Flags Enum and that it should be handled in V2. The Enum being reported here is not a Flags Enum:
public enum RunwayDesignator {
NONE = 0,
LEFT = 1,
RIGHT = 2,
CENTER = 3,
WATER = 4,
C = 5,
L = 6,
R = 7,
W = 8,
A = 9,
B = 10,
NOT_APP = 99
}
I assume the '16' refers to something in the Enum although there are not 16 values. I checked also to see if there are any ProtoMember IDs of 16 related to unsages of this enum - there are not. All usages of this enum that are serialized are private fields.
I would appreciate some guidance on how to deal with this.
Mant Thanks
Well - this is embarrassing. The problem is that the value of 16 is indeed being generated. So it looks like this is some sort of programming error on my part. The error message is saying there is no value for 16 in the enum and that is true.
So I can now go back and try and fix my code. Protobuf-Net is nowhere at fault.
I guess this might be useful for others who see this error. Find out where the enum value is being used and see if the code is sending an invalid value. What I don't understand is why I am not seeing some sort of runtime error when trying to set an invalid index for the enum. I need to investigate that now. And here is an answer to that
Why does casting int to invalid enum value NOT throw exception?
It seems that there is no error generated for invalid enum values but protobuf-net does find them
I have the following enum definition (in C#):
public enum ELogLevel
{
General = -1, // Should only be used in drop-down box in Merlinia Administrator log settings
All = 0, // Should not be used as a level, only as a threshold, effectively same as Trace
Trace = 1,
Debug = 2,
Info = 3,
Warn = 4,
Error = 5,
Fatal = 6,
Off = 7 // Should not be used as a level, only as a threshold
}
Now, when I do an Enum.GetNames() on this type I get a string array with 9 elements as expected, but the order is All, Trace, ... , Off, General, which is not what I was expecting.
Here's the MSDN documentation for Enum.GetNames():
"Remarks: The elements of the return value array are sorted by the
values of the enumerated constants."
What's going on here? I can change my program to take this "functionality" into account, but I'd kind of like to know why .NET is doing what it's doing.
This is a known bug with both GetNames() and GetValues() that was reported here, but ended up getting closed as won't fix:
Yes, this method indeed has a bug where it returns the array of enum values sorted as unsigned-types (-2 is 0xFFFFFFFE and -1 is 0xFFFFFFFF in two's complement, that's why they are showing up at the end of the list) instead of returning values sorted by their signed-types.
Unfortunately, we cannot change the sort order of GetValues because we will break all existing .NET programs that have been written to depend on the current sorting behavior [...]
Looks like you'll have to reorder the values yourself.
Depending on how the sorting occurs, it may be that it is sorting the values as if they were unsigned, in which case, -1 = 0xffffffff, which is of course greater than 7.
I am working on the front end of an application. I have to introduce one more filter criteria LoanNumber. Now loan number is E-100. Business layer and domain object is not in my control. So i cannot change it. Domain object which holds loannumber is integer, I have to do
ingeoFilterData.intLoanNumber="E-100"
ingeoFilterData is the domain object. intLoanNumber is declared as Nullable Int32 Now this domainobject is very critical and it goes to some external engine,so i cannot change it.
Please suggest some workaround.
Edit-
I am copying down loannumber from database table.
RT1
RT2
PT1
pt10
PT11
PT12
PT13
PT14
PT15
pt16
pt17
pt8
pt9
MDR1
MDR2
MDR3
If you have only one character, you can do this:
multiply your int by 100. (for example E-51 -> 5100)
Then keep the char as int in the rest of the number (for example 5106).
Do the reverse when you need to show the UI id (E-51).
If you have no limitations (as you mentioned) then you can have your int as a protocol (according to me that is even harder because you are limited by Int32 - 4,294,967,296).
You can set your number to something like
<meaning><number><meaning><number>
and meaning is - 1 - number, 2 - letter, 3 - hyphon.
then 11 will mean 1; 201 will mean A, 3 will mean hyphon, and 113201 will mean 1-A;
It's complicated and not very likely to be usable...
This solution limits your id to length of 5 numbers or 3 letters and 1 number. You can squeez some more by using your int bit-wize and optimize your "protocol" as much as possible.
I hope this helps,
Danail
Is "E-100" a string. ie. E is not a variable?
No, you can't set an int to a string value.
No, an int type cannot store a string. But you can parse your value to an int, before passing this to your domain object for filtering.
If the "prefix" of the loan number is always "E-" you could just exclude it.
Otherwise maybe you could add a property "LoanNumberPrefix" and store the "E-" in it.
Unfortunately at some point, bad design will give you unsolvable problems.
I don't know if this is one of them, but if the domain model has specified that loan numbers are integers, then either you, or the people that made that model clearly hasn't done their job.
Why the E in there? What does it signify? Is it just a prefix, can you remove it when storing it and put it back before displaying it?
Unfortunately, if the prefix can change, so that at some point you will have F-100 and so on, then you need to find a way to encode that into the integer you send to the domain model and business logic.
If you can't do that, you need to find a different place to store that prefix, or possibly the entire code.
If you can't do that, well, then you're screwed.
But to be blunt, this smells badly of someone who has been asleep while designing.
"Yeah, that's a good idea, we'll make the loan identification number an integer. I know somewhere, someplace, that someone has an example of what those loan identification numbers look like, but it's just numbers right? I mean, what could go wrong...?"
i think thats possible if you can convert the char into ASCII code.
string --- ASCII
0-10---48-57
A-Z----65-90
a-z----97-122
check out the ASCII table for more info..
Conversion:
so you can convert
RT1 to 082084049
RT2 to 082084050 and
MDR3 to 077068082051
i just prepend 0's to each character if the value is not 3 digit one(because max possible ASCII (z) value is in 3 digits ). R is actually 82, it becomes 082. And the final integer (no of digits) would be in multiples of 3.
Extraction:
This helps to extract the info in the other end. just split this into seperate 3 digit values and convert them to char and append them. you wil get the final string.
082,084,049 - R,T,1. thats all.
p.s: this method may end up in arithmetic overflow problem for large strings
I suggest that you talk to someone in the business/domain layer, or who is responsible for the design of the system, and point out to them that loannumber need to be changed to a string. No one will thank you for bodging your code to get around what is a design flaw--it can only lead to trouble and confusion later.