How to generate a document ID or Report ID of 8 characters in .net - guid

Can someone point me to the preferred method for generating a report or document ID? I have been looking at maybe using a guid that would be reduced down to a shorter length. We have an application that creates an ID for reports that is about 8 characters long. They appear to be using some type of hash code. Probably using a base 36 encoding scheme. But I cant seem to find a way to make the hash code come out to a length of 8 characters since people have to use them to refer to the documents. They would also be used in a disconnected environment, so you couldnt look up the next usable serialized number in the chain. Just wondering what some of you use in applications like this?

The .net Framwork provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers. Although I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length.
private string GetUniqueKey()
{
int maxSize = 8 ;
int minSize = 5 ;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize ;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data) ;
size = maxSize ;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size) ;
foreach(byte b in data )
{ result.Append(chars[__b % (chars.Length - )>); }
<span class="code-keyword">return result.ToString();
}
http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net

This is what I ended up using. It is a base36 encoding. I borrowed parts of the code from other people, so I cant claim that I wrote it all, but I hope this helps others. This will produce about a 12 digit record ID, or unique ID for databases etc. It uses only the last 2 digits of the year, so it should be good for 100 years.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Base36Converter
{
public partial class Form1 : Form
{
private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Form1()
{
InitializeComponent();
}
//Base 36 number consists of only numbers and uppercase letters only.
private void button1_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length > 0)
{
label3.Text = "";
//Get Date and Time Stamp
string temp1 = GetTimestamp(DateTime.Now);
//Turn it into a long number
long l = Convert.ToInt64(temp1);
//Now encode it as a base36 number.
string s1 = Encode(l);
//Get userID as a number, i.e. 1055 (User's index number) and create as a long type.
long l1 = Convert.ToInt64(textBox2.Text);
//Encode it as a base36 number.
string s2 = Encode(l1);
//Now display it as the encoded user number + datetime encoded number (Concatenated)
textBox1.Text = s2 + s1;
}
else
{
label3.Text = "User Number must be greater than 0. ie 1055";
}
}
public static String Encode(long input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray());
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyMMddHHmmssffff");
}
private void Form1_Load(object sender, EventArgs e)
{
label3.Text = "";
}
}
}

Related

Are Guids unique when using a U-SQL Extractor?

As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors

How to parse specific data from query string in a url in C#?

I want to parse the data from a URL query string and store it. Given below is my sample URL. From this I want to parse the data and store somewhere
http://www.example.com/default.aspx?VN=919999999999&Rawmessage=urlTest&Time=2013-04-08 12:32:04&Send=919000000002&MID=101878052
I want to store VN and Rawmessage into these strings,
string x = Request.QueryString["VN"]
string y = Request.QueryString["Rawmessage"]
Please help me find a solution.
Place this code in the Page_Load() function in Default.aspx.cs file.
protected void Page_Load(object sender, EventArgs e)
{
string x = Request.QueryString["VN"];
string y = Request.QueryString["Rawmessage"];
}
With reference to the discussion we had, I think you want to parse the query string key-value pair and use the values somewhere else.
Also, ASP.Net doesn't have to do anything with parsing, It's a pure C# problem.
I'm giving the sample solution to the problem in the context of a Console App, you're free to reuse the codes as per your taste.
var inputUrl =
#"http://www.example.com/default.aspx?VN=919999999999&Rawmessage=urlTest&Time=2013-04-08 12:32:04&Send=919000000002&MID=101878052";
int index = inputUrl.IndexOf("?");
var queryString = inputUrl
.Substring(index + 1)
.Split('&');
foreach (var strKeyValuePair in queryString)
{
var keyValPair = strKeyValuePair.Split('=');
Console.WriteLine("Key: {0}, Value:
{1}",keyValPair[0],keyValPair[1]);
}
Console.WriteLine("\n============================================\n\n");
string VN = queryString.FirstOrDefault(x => x.StartsWith("VN"));
string RawMessage = queryString.FirstOrDefault(x =>
x.StartsWith("Rawmessage"));
Console.WriteLine("VN: {0}",VN.Split('=')[1]);
Console.WriteLine("RawMessage: {0}", RawMessage.Split('=')[1]);
Console.ReadLine(); // just to halt the console

Alphabet Encryption

Right now I cant even compile this program. Im trying to write a program that takes a inputted string and then encrypts the letters by swapping them out with another letter predetermined in a array and then shows you again the original text. any help would be appreciated.
import java.util.Scanner;
public class Array {
private char [] alphabet = new char [25];
private char [] crypt = new char [25];
String oldMessage;
public Array()
{ char[] alphabet = "abcdefghijklmnoptqrstuvwxyz".toCharArray();
char[] crypt = "qwertyuiopasdfghjklzxcvbnm|".toCharArray();
}
public static void run(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a message that you would like to encrypt\n");
oldMessage = scan.nextLine();
String newMessage = "";
for (int i=0; i<oldMessage.length(); ++i) {
int index = alphabet.indexOf(old.charAt(i));
if (index == -1)
newMessage +="?";
else
newMessage += crypt.charAt(index);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {Array myApplication = new Array(); myApplication.run();}
First off, when encountering errors, it's always best to include the error in your question--often it will point you right to the source of the error. What does your compiler say when the build fails?
Next, I'm on my phone right now and can't verify that I've found all the problems, but remember that strings in Java are immutable, meaning that they can't be changed after creation. This means that you can't append to them in the way you're doing. Try using the StringBuilder class to accomplish what you're looking for here, or filling a new array as you go and converting to String at the end.
Also, it looks like you're missing two end braces (the for loop and the run method).
From static method run() you are referring to non-static variables like alphabet, crypt, oldMessage.
This is first that comes into mind

Get a Number from String with no default decimal separator

I have a TextInput where a need to return a Number.
My problem is that entered value is localized to a logged in user and that effects the decimal separator.
I seem to always get a NaN when i try to get a Number from a Polish user but it works great for English users:
Input example:
English: 23.5
Polish: 23,5
Is there a workaround for this? I have the following that doesn't work:
public function get myValue():Number {
var value:Number = new Number(StringUtil.trim(text)); //NaN with Polish
return value;
}
I have also tried the following but it also gives a NaN:
private function myValue(number:Number, precision:Number=2):Number{
var numberFormatter:NumberFormatter = getNumberFormatter(precision);
return new Number(numberFormatter.formatNumber(number));
}
private function getNumberFormatter(precision:Number=2):NumberFormatter{
var iso:String = ClientInfo.instance.language.ISOCode;
var formattedIso:String = iso.substr(0, 2)+'_'+iso.substr(2,2);
var numberFormatter:NumberFormatter = new NumberFormatter(formattedIso);
numberFormatter.fractionalDigits = precision;
numberFormatter.trailingZeros = true;
return numberFormatter;
}
When I debug the code I can see that the NumberFormatter works correctly but its always the call to new Number("23,5") that gives a NaN.
Can't test it now, but I guess it should work:
public function get myValue():Number
{
var value:Number = getNumberFormatter.parseNumber(StringUtil.trim(text));
return value;
}
I think the key is, that you should use parseNumber()!
[Update]
Here is a FlexUnit test for better understanding:
[Test]
public function test(): void
{
var number: Number = new NumberFormatter("de-DE").parseNumber("23,5");
assertEquals(23.5, number);
number = new NumberFormatter("en-US").parseNumber("23.5");
assertEquals(23.5, number);
number = new NumberFormatter("de-DE").parseNumber("1.023,456");
assertEquals(1023.456, number);
number = new NumberFormatter("pl-PL").parseNumber("1023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber("1.023,45");
assertTrue(isNaN(number));
number = new NumberFormatter("pl-PL").parseNumber("1 023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber(" 10 531 023,45 ");
assertEquals(10531023.45, number);
}
As you can see NumberFormatter handles decimal and thousands separator correctly.
If you want to format it back, then you could use it like this:
var numFmt: NumberFormatter = new NumberFormatter("pl-PL");
assertEquals("23,50", numFmt.formatNumber(numFmt.parseNumber(" 23,5 ")));
numFmt.fractionalDigits = 1;
assertEquals("23,6", numFmt.formatNumber(numFmt.parseNumber(" 23,57 ")));
Assuming your numbers are not being returned with commas between each 10^3 number group (i.e. 1,000,000 for 1 million), you could just use a replace on the commas.
Number("23,5".replace(",","."); // output Number( "23.5" ) = 23.5
That will replace all commas in the number with a period and should be read as a normal number by the system.

How to generate random unique 16 digit number in asp.net without collision

how can i generate 16 digit unique random numbers without any repetition in c# asp.net, as i have read the concept of GUID which generate characters along with numbers but i don't want characters
kindly suggest is there any way to acheive it
You can create a random number using the Random class:
private static Random RNG = new Random();
public string Create16DigitString()
{
var builder = new StringBuilder();
while (builder.Length < 16)
{
builder.Append(RNG.Next(10).ToString());
}
return builder.ToString();
}
Ensuring that there are no collisions requires you to track all results that you have previously returned, which is in effect a memory leak (NB I do not recommend that you use this - keeping track of all previous results is a bad idea, rely on the entropy of a random string of up to 16 characters, if you want more uniqueness, increase the entropy, but I shall include it to show how it could be done):
private static HashSet<string> Results = new HashSet<string>();
public string CreateUnique16DigitString()
{
var result = Create16DigitString();
while (!Results.Add(result))
{
result = Create16DigitString();
}
return result;
}

Resources