I have a program for parsing GS1 Barcodes (with Zebra scanner), which worked just fine, atleast I thought it was OK...
Until I came across one box with 2 GS1 barcodes.. one "linear" and one data matrix (UDI). For linear, it worked just fine, I successfully got out the GTIN and Serial. But datamatrix is different. For some reason, its content is a bit longer than linear code, it has some production date and something else at the end.
This is the Linear code: (01)00380652555852(17)260221(21)25146965079(30)1
This is data matrix: (01)00380652555852(17)260221(21)2514696507911210222240SA60AT225
I have problems with parsing out the Serial number - 25146965079.
Serial number in GS1 has a length of 1-20 characters. This one has 11, but How can I make it stop after the 9 characters? How can I know that the serial ends there?
I tried transforming each character to UDI, but it seems that there is no special separating character or anything.. so I honestly donjt know what to do. Does anyone have any idea?
This the code, if anyone wanna try anything https://prnt.sc/1x2sw8l
Those codes/products came right from the manufacturer, so there shouldnt be anything wrong with the code, I guess...
If you verify the barcode with a scanner that is designed to interpret a GS1 structure, you will see that the generated barcode is in fact incorrect.
You are missing a GS after the serial number, these codes MUST end a variable-length field if it's not the last one. This is specified in GS1 general specifications section 7.8.5.2
Without this separator you can't know where the serial ends - or, a machine interpreting the code can't know.
Tell the manufacturer that they need to study the GS1 specs.
Edit: the "correct" version would be:
(01)00380652555852(17)260221(21)25146965079<GS>(11)210222(240)SA60AT225
The parentheses and group separator <GS> are not included literally in the code.
Since you have two variable-length identifiers (21) and (240) you need a GS no matter what you do. Only alternative would be to have some padding for serial number, then you could do without separator.
According to the GS1 documentation (page 156 and forwards)
All the fields are correct
(01)00380652555852 --> GTIN
(17)260221 --> Expiration date
(21)25146965079 --> Serial Number
(11)210222 --> Production Date
(240)SA60AT225 --> Additional Product Identification
I tried scanning the image but the result was the same as yours.
So the problem is that the separators are not there. Which is a problem for you, and there is no way to know where the serial number ends without the separator.
I am sorry my English is not good
The reason of this problem is group separetors are unreadable character for example if you focus on text box and press capslock button or shift button nothing appear in text box the same in gs
To solve this problem
Public l as integer
And put the following code in keyup event
If textbox1.textlenght = l then
My.combuter.keybord.sendkeys({enter})
L= textbox1.textlenght
End if
This code will give space after each litter (because each litter combined with cabslock button) and five spaces in groub space
store raw input in KeyPress event and then read the character for Letter Or Digit.
if (e.KeyChar != 13)
{
int asci = Convert.ToInt32(e.KeyChar);
if (asci > 31 && asci < 128) // numeric and chars only
rawbcode += Convert.ToChar((int)(e.KeyChar & 0xffff));
else
{
if (asci == 29)
{
rawbcode += "<GS>"; // GS1 Seperator
}
}
}
I have a form which I read data to textbox from a barcode reader.
and there are some codded barcodes like this
W12346S1 is first step of a work
W12346S2 is second step of a work
W12346S3 is third step of a work
...
U123 is a user he read his code to make process
M456 is a machine user do the work on this machine.
so I want to write data to true textboxes from firs char (W, U, M) in form_KeyDown() event or one different.
(
true textboxes mean if user read a barcode which start with W key let the program write the barcode data to "work tekxtbox" or if he read abarcode which start with U program will write the barcode data to user textbox etc...
)
I wanna make this let the codes select its own textboxes. what is the way?
note: if I use textbox1.Text += e.KeyData.ToString();
the output is : ShiftKey, ShiftW, ShiftD1D2D3D4D6ShiftKey, ShiftS, ShiftD2 W12346S2
for W12346S2
Can't you just read in the text and have something like this:
string FirstChar = BarcodeString.Substring(0,1);
if (FirstChar.Equals("W"))
WorkTextBox.Text = BarcodeString;
if (FirstChar.Equals("U"))
UserTextBox.Text = BarcodeString;
Can input from your barcode reader be distinguished from typed keystrokes? If so, I would recommend that incoming barcodes not be handled by the keystroke handler, but instead use their own special handler which will wait until it has scanned an entire barcodes and then stick it in an appropriate box.
If the input from your reader looks like keystrokes, things are apt to be a little more tricky. You may want to intercept all keystrokes going to your form, look at each keystroke, determine whether it looks like it might be part of a barcode, and buffer it if so. Any time you determine that the buffered data isn't part of a barcode, either because of following characters or because a timer expires, fire your own keystroke events to re-issue the keystrokes. Ensuring that all keystrokes are handled in order may be a little tricky, but hopefully not too bad. It will probably be easier to prevent keystrokes from the barcode reader from going into an inappropriate field, than to provide a good user experience after they do.
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
How to handle when the backspace button is pressed and the input panel has digit grouped numbers. E.g. 434,343,334.232.
Basically the question says it all, I'm making a calculator in c# and I'm stuck on this problem. When digit grouping is hit the numbers get separated by commas, when the user hits the backspace button, the commas act like characters that get deleted.
inputPanelTextBox.Text = inputPanelTextBox.Text.Replace(",", "") I put this piece of code under my backspace click event. The problem is that say the panel has 234,232 and the user presses the backspace button, the comma is gone as well as the 2 on the far right.
What I want to happen is the same way the windows 7 calculator does when the digit grouped menu is checked and the user hits the backspace.
Any idea of how to go about this? Thank you so much in advance.
How about you store the number just as a number then format the number to look nice when you output it. The same thing will work with string.Format(). You could reformat the number into the display string every time the user hits backspace or adds a new digit. There are lots of the string format modifiers listed here.
int numWithComma = 3000;
int numWithoutComma = 50;
Console.WriteLine("numWithComma: {0:n}", numWithComma);
Console.WriteLine("numWithoutComma: {0:n}", numWithoutComma);
// prints:
// numWithComma: 3,000.00
// numWithoutComma: 50.00
If I were making this calculator, I would save the number in a double, then when the number needs to be displayed I would run it through a function like this and display the string to the user:
private static string FormatForDisplay(double number)
{
return string.Format("{0:n}", number);
}
How about using a format string when you output the number, that way you don't have to manage commas at all.
double myDouble = 500000.012345
inputPanelTextBox.Text = myDouble.ToString("N", CultureInfo.InvariantCulture);
Its been a while since I've used Visual Studio but I'm pretty sure you can set these format strings directly on text boxes so its simply automatically handled when they type. And its easy as pie to set in the properties if I remember correctly. Check out Standard Numeric Format Strings for a bit more on it.
Also a MaskedTextBox might work as well, set the mask to something like "999,999,999,999.99" and see how that formats different numbers.
Good Luck! :D
Many times, when generating messages to show to the user, the message will contain a number of something that I want to inform the customer about.
I'll give an example: The customer has selected a number of items from 1 and up, and has clicked delete. Now I want to give a confirmation message to the customer, and I want to mention the number of items he has selected to minimize the chance of him making a mistake by selecting a bunch of items and clicking delete when he only wants to delete one of them.
One way is to make the generic message like this:
int noofitemsselected = SomeFunction();
string message = "You have selected " + noofitemsselected + " item(s). Are you sure you want to delete it/them?";
The "problem" here is the case where noofitemselected is 1, and we have to write item and it instead of items and them.
My normal solution will be something like this
int noofitemsselected = SomeFunction();
string message = "You have selected " + noofitemsselected + " " + (noofitemsselected==1?"item" : "items") + ". Are you sure you want to delete " + (noofitemsselected==1?"it" : "them") + "?";
This gets quite long and quite nasty really fast if there are many references to the numbers plurality inside the code, and the actual message gets hard to read.
So my questions is simply. Are there any better ways of generating messages like this?
EDIT
I see a lot of persons has got very hung up in the case that I mentioned that the message should be displayed inside a message box, and has simply given an answer of how to avoid using the message box at all, and that is all good.
But remember that the problem of pluralization also apply to texts other places in the program in addition to message boxes. For example, a label alongside a grid displaying the number of lines selected in the grid will have the same problem regarding pluralization.
So this basically apply to most text that is outputted in some way from programs, and then the solution is not as simple as to just change the program to not output text anymore :)
You can avoid all of this messy plurality by just deleting the items without any message and giving the user a really good Undo facility. Users never read anything. You should build a good Undo facility as part of your program anyway.
You actually get 2 benefits when you createe a comprehensive Undo facility. The first benefit makes the user's life easier by allowing him/her to reverse mistakes and minimise reading. The second benefit is that your app is reflecting real life by allowing the reversal of non-trivial workflow (not just mistakes).
I once wrote an app without using a single dialog or confirmation message. It took some serious thinking and was significantly harder to implement than using confirmation-type messages. But the end result was rather nice to use according to its end-users.
If there is ever any chance, no matter how small, that this app will need to be translated to other languages then both are wrong. The correct way of doing this is:
string message = ( noofitemsselected==1 ?
"You have selected " + noofitemsselected + " item. Are you sure you want to delete it?":
"You have selected " + noofitemsselected + " items. Are you sure you want to delete them?"
);
This is because different languages handle plurality differently. Some like Malay don't even have syntactic plurals so the strings would generally be identical. Separating the two strings makes it easier to support other languages later on.
Otherwise if this app is meant to be consumed by the general public and is supposed to be user friendly then the second method is preferable. Sorry but I don't really know a shorter way of doing this.
If this app is meant to be consumed only internally by your company then do the shortcut "item(s)" thing. You don't really have to impress anybody when writing enterprisy code. But I'd advise against doing this for publicly consumed app because this gives the impression that the programmer is lazy and thus lower their opinion of the quality of the app. Trust me, small things like this matter.
How about just:
string message = "Are you sure you want to delete " + noofitemsselected + " item(s)?"
That way, you eliminate the number agreement difficulties, and end up with an even shorter, more to-the-point error message for the user as a bonus. We all know users don't read error messages anyway. The shorter they are, the more likely they are to at least glance at the text.
Or, armed with this knowledge that users don't read error messages, you could approach this a different way. Skip the confirmation message altogether, and just provide an undo feature that Just Works, regardless of what was deleted. Most users are already accustomed to undoing an operation when they notice it was not what they wanted, and are likely to find this behavior more natural than having to deal with another annoying pop-up.
What about what Java has had for years: java.text.MessageFormat and ChoiceFormat? See http://download.oracle.com/javase/1.4.2/docs/api/java/text/MessageFormat.html for more information.
MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
form.applyPattern(
"There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
Object[] testArgs = {new Long(12373), "MyDisk"};
System.out.println(form.format(testArgs));
// output, with different testArgs
output: The disk "MyDisk" are no files.
output: The disk "MyDisk" is one file.
output: The disk "MyDisk" are 1,273 files.
In your case you want something somewhat simpler:
MessageFormat form = new MessageFormat("Are you sure you want to delete {0,choice,1#one item,1<{0,number.integer} files}?");
The advantage of this approach is that it works well with the i18n bundles, and you can provide translations properly for languages (like Japanese) that have no concept of plural or singular words.
I'd go with not hardcoding the message, but providing two messages in an seperate Resource file. Like
string DELETE_SINGLE = "You have selected {0} item. Are you sure you want to delete it?";
string DELETE_MULTI = "You have selected {0} items. Are you sure you want to delete them?";
and then feeding them into String.Format like
if(noofitemsselected == 1)
messageTemplate = MessageResources.DELETE_SINGLE;
else
messageTemplate = MessageResources.DELETE_MULTI;
string message = String.Format(messageTemplate, noofitemsselected)
I think that this approach is easier to localize and maintain. All UI messages would be at a single locaion.
You can sidestep the issue entirely by phrasing the message differently.
string message = "The number of selected items is " + noofitemsselected + ". Are you sure you want to delete everything in this selection?";
The first thing I'd suggest is: use string.Format. That allows you to do something like this:
int numOfItems = GetNumOfItems();
string msgTemplate;
msgTemplate = numOfItems == 1 ? "You selected only {0} item." : "Wow, you selected {0} items!";
string msg = string.Format(msgTemplate, numOfItems);
Further, in WPF apps, I've seen systems where a resource string would be pipe-delimited to have two messages: a singular and a plural message (or a zero/single/many message, even). A custom converter could then be used to parse this resource and use the relevant (formatted) string, so your Xaml is something like this:
<TextBlock Text="{Binding numOfItems, Converter={StaticResource c:NumericMessageFormatter}, ConverterParameter={StaticResource s:SuitableMessageTemplate}}" />
For English, plenty of answers above. For other languages it is more difficult, as plurals depend on the gender of the noun and the word ending. Some examples in French:
Regular masculine:
Vous avez choisi 1 compte. Voulez-vous vraiment le supprimer.
Vous avez choisi 2 comptes. Voulez-vous vraiment les supprimer.
Regular feminine
Vous avez choisi 1 table. Voulez-vous vraiment la supprimer.
Vous avez choisi 2 tables. Voulez-vous vraiment les supprimer.
Irregular masculine (finishes with 's')
Vous avez choisi 1 pays. Voulez-vous vraiment le supprimer.
Vous avez choisi 2 pays. Voulez-vous vraiment les supprimer?
The same problem exists in most Latin languages and gets worse in German or Russian, where there are 3 genders (maculine, feminine and neuter).
You'll need to take care if your objective is to handle more than just English.
To be able to have pluralized messages which will be possible to localize properly, my opinion is that it would be wise to first create a layer of indirection between the number and a message.
For example, use a constant of some sort to specify which message you want to display. Fetch the message using some function that will hide the implementation details.
get_message(DELETE_WARNING, quantity)
Next, create a dictionary that holds the possible messages and variations, and make variations know when they should be used.
DELETE_WARNING = {
1: 'Are you sure you want to delete %s item',
>1: 'Are you sure you want to delete %s items'
>5: 'My language has special plural above five, do you wish to delete it?'
}
Now you could simply find the key that corresponds to the quantity and interpolate the value of the quantity with that message.
This oversimplified and naive example, but I don't really see any other sane way to do this and be able to provide good support for L10N and I18N.
You'll have to translate the function below from VBA to C#, but your usage would change to:
int noofitemsselected = SomeFunction();
string message = Pluralize("You have selected # item[s]. Are you sure you want to delete [it/them]?", noofitemsselected);
I have a VBA function that I use in MS Access to do exactly what you are talking about. I know I'll get hacked to pieces for posting VBA, but here goes anyway. The algorithm should be apparent from the comments:
'---------------------------------------------------------------------------------------'
' Procedure : Pluralize'
' Purpose : Formats an English phrase to make verbs agree in number.'
' Usage : Msg = "There [is/are] # record[s]. [It/They] consist[s/] of # part[y/ies] each."'
' Pluralize(Msg, 1) --> "There is 1 record. It consists of 1 party each."'
' Pluralize(Msg, 6) --> "There are 6 records. They consist of 6 parties each."'
'---------------------------------------------------------------------------------------'
''
Function Pluralize(Text As String, Num As Variant, Optional NumToken As String = "#")
Const OpeningBracket = "\["
Const ClosingBracket = "\]"
Const DividingSlash = "/"
Const CharGroup = "([^\]]*)" 'Group of 0 or more characters not equal to closing bracket'
Dim IsPlural As Boolean, Msg As String, Pattern As String
On Error GoTo Err_Pluralize
If IsNumeric(Num) Then
IsPlural = (Num <> 1)
End If
Msg = Text
'Replace the number token with the actual number'
Msg = Replace(Msg, NumToken, Num)
'Replace [y/ies] style references'
Pattern = OpeningBracket & CharGroup & DividingSlash & CharGroup & ClosingBracket
Msg = RegExReplace(Pattern, Msg, "$" & IIf(IsPlural, 2, 1))
'Replace [s] style references'
Pattern = OpeningBracket & CharGroup & ClosingBracket
Msg = RegExReplace(Pattern, Msg, IIf(IsPlural, "$1", ""))
'Return the modified message'
Pluralize = Msg
End Function
Function RegExReplace(SearchPattern As String, _
TextToSearch As String, _
ReplacePattern As String) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.MultiLine = False
.Global = True
.IgnoreCase = False
.Pattern = SearchPattern
End With
RegExReplace = RE.Replace(TextToSearch, ReplacePattern)
End Function
The usage got cut off a bit in the code comments above, so I'll repeat it here:
Msg = "There [is/are] # record[s]. [It/They] consist[s/] of # part[y/ies] each."
Pluralize(Msg, 1) --> "There is 1 record. It consists of 1 party each."
Pluralize(Msg, 6) --> "There are 6 records. They consist of 6 parties each."
Yes, this solution ignores languages that are not English. Whether that matters depends on your requirements.
You could generate the plural automatically, see eg. plural generator.
For plural generating rules see wikipedia
string msg = "Do you want to delete " + numItems + GetPlural(" item", numItems) + "?";
How about a more generic way. Avoid pluralization in the second sentence:
Number of selected items to be deleted: noofitemsselected.
Are you sure?
I find out that doing it this way puts the number at the end of the line which is really easy to spot. This solution would work with the same logic in any language.
My general approach is to write a "single/plural function", like this:
public static string noun(int n, string single, string plural)
{
if (n==1)
return single;
else
return plural;
}
Then in the body of the message I call this function:
string message="Congratulations! You have won "+n+" "+noun(n, "foobar", "foobars")+"!";
This isn't a whole lot better, but at least it, (a) puts the decision in a function and so unclutters the code a little, and (b) is flexible enough to handle irregular plurals. i.e. it's easy enough to say noun(n, "child", "children") and the like.
Of course this only works for English, but the concept is readily extensible to languages with more complex endings.
It occurs to me that you could make the last parameter optional for the easy case:
public static string noun(int n, string single, string plural=null)
{
if (n==1)
return single;
else if (plural==null)
return single+"s";
else
return plural;
}
Internationalization
I assume you want internationalization support, in which case different languages have different patterns for plurals (e.g. a special plural form for 2 of something, or more complicated languages like Polish), and you can't rely on applying some simple pattern to your string to fix it.
You can use GNU Gettext's ngettext function and provide two English messages in your source code. Gettext will provide the infrastructure to choose from other (potentially more) messages when translated into other languages. See http://www.gnu.org/software/hello/manual/gettext/Plural-forms.html for a full description of GNU gettext's plural support.
GNU Gettext is under the LGPL. ngettext is named GettextResourceManager.GetPluralString in the C# port of Gettext.
(If you don't need localization support, and don't want to use Gettext right away, then write your own function that does this for English, and pass two full messages to it, that way if you need l10n later, you can add by rewriting a single function.)
How about to write function like
string GetOutputMessage(int count, string oneItemMsg, string multiItemMsg)
{
return string.Format("{0} {1}", count, count > 1 ? multiItemMsg : oneItemMsg);
}
.. and use it whenever you need?
string message = "You have selected " + GetOutputMessage(noofitemsselected,"item","items") + ". Are you sure you want to delete it/them?";
For the first problem , I mean Pluralize, you can use Inflector.
And for the second, you can use a string representation extension with a name such as ToPronounString.
I had this exact same question posed to me yesterday by a member of our team.
Since it came up again here on StackOverflow I figured the universe was telling me to have a bash at producing a decent solution.
I've quickly put something together and it's by no means perfect however it might be of use or spark some discussion/development.
This code is based on the idea that there can be 3 messages. One for zero items, one for one item and one for more than one item which follow the following structure:
singlePropertyName
singlePropertyName_Zero
singlePropertyName_Plural
I've created an internal class to test with in order to mimick the resource class. I haven't tested this using an actual resource file yet so I'm yet to see the full result.
Here's the code (currently i've included some generics where I know I could have specified the third param simply as a Type and also the second param is a string, I think there's a way to combine these two parameters into something better but I'll come back to that when I have a spare moment.
public static string GetMessage<T>(int count, string resourceSingularName, T resourceType) where T : Type
{
var resourcePluralName = resourceSingularName + "_Plural";
var resourceZeroName = resourceSingularName + "_Zero";
string resource = string.Empty;
if(count == 0)
{
resource = resourceZeroName;
}
else{
resource = (count <= 1)? resourceSingularName : resourcePluralName;
}
var x = resourceType.GetProperty(resource).GetValue(Activator.CreateInstance(resourceType),null);
return x.ToString();
}
Test resource class:
internal class TestMessenger
{
public string Tester{get{
return "Hello World of one";}}
public string Tester_Zero{get{
return "Hello no world";}}
public string Tester_Plural{get{
return "Hello Worlds";}}
}
and my quick executing method
void Main()
{
var message = GetMessage(56, "Tester",typeof(TestMessenger));
message.Dump();
}
From my point of view, your first solution is the most suited one. Why I say that is, in case you need the application to support multiple languages, the second option can be painstaking. With the fist approach it is easy to localize the text without much effort.
You could go for a more generic message like 'Are you sure you want to delete the selected item(s)'.
I depends on how nice a message you want to have. From easiest to hardest:
Re-write your error message to avoid pluralization. Not as nice for your user, but faster.
Use more general language but still include the number(s).
Use a "pluralization" and inflector system ala Rails, so you can say pluralize(5,'bunch') and get 5 bunches. Rails has a good pattern for this.
For internationalization, you need to look at what Java provides. That will support a wide variety of languages, including those that have different forms of adjectives with 2 or 3 items. The "s" solution is very English centric.
Which option you go with depends on your product goals. - ndp
Why would you want to present a message the users can actually understand? It goes against 40 years of programing history. Nooooo, we have a good thing going on, don't spoil it with understandable messages.
(j/k)
Do it like it's done in World of Warcraft:
BILLING_NAG_WARNING = "Your play time expires in %d |4minute:minutes;";
It gets a little bit shorter with
string message = "Are you sure you want to delete " + noofitemsselected + " item" + (noofitemsselected>1 ? "s" : "") + "?";
One approach I haven't seen mentioned would be the use of a substitution/select tag (e.g. something like "You are about to squash {0} [?i({0}=1):/cactus/cacti/]". (in other words, have a format-like expression specify the substitution based upon whether argument zero, taken as an integer, equals 1). I've seen such tags used in the days before .net; I'm not aware of any standard for them in .net, nor do I know the best way to format them.
I would think out of the box for a minute, all of the suggestions here are either do the pluralization (and worry about more than 1 level of pluralization, gender, etc) or not use it at all and provide a nice undo.
I would go the non lingual way and use visual queues for that. e.g. imagine an Iphone app you select items by wiping your finger. before deleting them using the master delete button, it will "shake" the selected items and show you a question mark titled box with a V (ok) or X (cancel) buttons...
Or, in the 3D world of Kinekt / Move / Wii - imagine selecting the files, moving your hand to the delete button and be told to move your hand above your head to confirm (using the same visual symbols as I mentioned before. e.g. instead of asking you delete 3 files? it will show you 3 files with a hovering half transparent red X on and tell you to do something to confirm.