Click here to Skip to main content
15,881,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all
Iam in a small project for a transportation company my problem is to generate an alpha numeric code(jobcode) based on it will be all other functions and modules work and every time it should increment
its a a destktop application only so how to get the last numeric values only since the alphabetic combination is same for all jobcode (something like "NFT")
I know it be simple but since a beginner I find it difficult can anyone give an idea
Posted

In response to the solution by Simon and taking into account my notes (see my comments to his answer), here is a solution based on centralized repository which has its benefits:

You can have a value of some numeric type, sufficient to store as many IDs as you may need for the lifetime of the product installation, increment it on each ID generation and store the last value. You can nicely format the result to show some alphanumeric string.

This is an example of such formatting showing the number in hexadecimal format with groups delimited by '-':

C#
static string FormatId(ulong id) {
    byte[] serialized = System.BitConverter.GetBytes(id);
    object[] parameters =
        System.Array.ConvertAll<byte, object>
            (serialized, new System.Converter<byte, object>(
                    (byteValue) => { return byteValue; }
            ));
    return string.Format("NFT#{7:X}{6:X}-{5:X}{4:X}-{3:X}{2:X}-{1:X}{0:X}", parameters);
}


In case you still use C# v.2, this is the version without lambda notation and type inference (but with generics):
C#
static string FormatId(ulong id) {
    byte[] serialized = System.BitConverter.GetBytes(id);
    object[] parameters =
        System.Array.ConvertAll<byte, object>
            (serialized, new System.Converter<byte, object>(
                    delegate(byte byteValue) { return byteValue; }
            ));
    return string.Format("NFT#{7:X}{6:X}-{5:X}{4:X}-{3:X}{2:X}-{1:X}{0:X}", parameters);
}


This is a version of the same thing which might be not so good in performance but might be easier to understand. It also works with C# v.2:

C#
static string FormatId(ulong id) {
    byte[] serialized = System.BitConverter.GetBytes(id);
    object[] parameters = new object[serialized.Length];
    for(int index=0; index < serialized.Length; ++index)
        parameters[index] = serialized[index];
    return string.Format("NFT#{7:X}{6:X}-{5:X}{4:X}-{3:X}{2:X}-{1:X}{0:X}", parameters);
}


I don't know a simpler way to combine hexadecimal format with custom format specifiers. With decimal base it would simply look:
return "NFT#" + id.ToString("0000-0000-0000-0000").

You may want to use shorted strings and less range of IDs. Choose the numeric type and format you prefer and you're done.

[EDIT]

You can make ID generation usable in concurrent environment by using your database in transactional manner, incrementing and returning ID in one transaction. Without a database, you can persist the current numeric value and make the procedure of getting the ID thread-safe using a lock.

C#
class IdGenerator {
    void Load() { id = /*...*/ }
    void Store() { /*...*/ }
    static string FormatId(ulong id) { /*...*/ }

    //...

    string Id {
        get {
           ulong returnValue;
           lock (LockObject) {
              returnValue = ++id;
           }
           return FormatId(returnValue); //note: not under lock
        }
    }
    static ulong id;
    object LockObject = new object();
}


—SA
 
Share this answer
 
v3
Comments
Simon Bang Terkildsen 4-Oct-11 14:42pm    
good examples, my 5.
However it seems the OP needs these ids in the form of a string "NTF#" where # is incremented. And I believe the actual problem is how do it concurrently.
Simon Bang Terkildsen 4-Oct-11 14:47pm    
hmm I didn't know of Array.ConvertAll, well come to think of it I can't remember that I've ever used any of the static methods of Array. That seems like a good method to know thank you.
Sergey Alexandrovich Kryukov 4-Oct-11 14:56pm    
OK, I added "NFT#" (not "NTF#" though), note about concurrent use of ID using database and without it, see my update, after [EDIT].
As to System.Array, there are some more methods... :-)
--SA
Guid.NewGuid()
I realize it's alpha numeric as it contains - but so much easier. if a guid is not good enough for one or the other reason you'll need to have a centralized location where you generate the id/code, as you'll have to store the last id/code provided so you can increment it.
Here is some pseudocode of one possible implementation.
int currentSystemTime = GetCurrentSystemTimeInTicks()
int count

ProventAnyOtherThreadsOrProcessesFromAccessing_Counter()
count = ++counter
AllowOtherThreadsToOrProcessesAccessing_Counter()

return ConcatenateStrings(IntToHex(currentSystemTime), IntToString(count))
 
Share this answer
 
v2
Comments
SREENATH GANGA 4-Oct-11 13:36pm    
thank you sir but the problem is I want the alphanumeric value same for all and sorry tell that it is a little bit dificult in understanding ur answer as \iam a beginer can you explain simply plssss
Simon Bang Terkildsen 4-Oct-11 13:47pm    
ok, I'll try to guide you step by step here (more or less), first step, you'll have to explain the below quote a bit more, as it seems to contradict the unique value requirement you stated.
I want the alphanumeric value same for all

So step one
Please explain in detail what the requirements of your alphanumeric value is.
E.g.
- Has to be auto generated
- Most be of the format XXXX####, where X is a character and # is an integer.

Note however I'll not be providing any complete source code solutions, as you yourself state you're a beginner and programming is not really about knowing the syntax of a language or the types of any available frameworks (this comes automatically), it's a way of thinking so you would immediately see the solution in your head for a problem such as the one you posted.
SREENATH GANGA 4-Oct-11 13:59pm    
ya sir I know I have to get my own ideas I did it like this I created a autogenerating feild in database which get generated and incremented when i press the key "new jobcode" anf then I concatenate it to a string "NFT" so that the combination becomes NFT223 next one NFT224 etc but the thing is two data transaction is going on when i start creating jobcode (entering the database and finding last autoincremented value taking it to the application again) and again after data entry we have to submit back it will slow down athe application in future I think ANY WAAY THANK YOU FOR GUIDING
Simon Bang Terkildsen 4-Oct-11 14:31pm    
Ok, if I get it right, you have a const string "NTF" and then you do the following:
0) get integer value from database into i
1) create the jobcode ("NTF" + i)
2) increment i
3) update the integer value in the database to the value of i

And you have a problem as this might happen in different applications or threads at the same time, so the value retrieved in 0) might be the same for two or more concurrent calls.

As I don't know how your current implementation looks like the following might not be entirely applicable, but the idea is still valid.
This is a very common issue, What I suggest you do is to write an sql update statement which returns the value, instead of a select statement, so you let the database ensure that the value is unique.

Note in the end I would suggest that this were done using a stored procedure, but for now I suggest we avoid such things.

I've been looking for some articles that could help you understand ADO.NET and the usage of parameters especially output parameters, but haven't been able to find any.
So before I write some quick intro for you I would like to see the relevant parts of your source and how the value is stored in the database. This way I get a feel for what you already know, and can point to the relevant parts of your code in my intro.

you can click "Improve question" at the bottom of your question to add any relevant code, so it can be formatted and are easier to read.
Sergey Alexandrovich Kryukov 4-Oct-11 14:03pm    
Speaking strictly, GUID are not 100% unique, they are unique with very high probability, by the nature of their generation algorithm. From what I know, they are totally unique for all computers equipped with network cards with unique MAC addresses. Nevertheless, it's not too difficult to create additional safe guard against potential low-probability non-uniqueness putting all obtained GUIDs as keys in some dictionary. This still means centralized location though, which can be acceptable.

One other problem is that GUID are considered too long for many applications. Shorter strings sometimes required. This is another reason to use ID generator with centralized location. After all, I decided to vote 4 for this answer.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900