Can't output Guid Hashcode

125 views Asked by At

I'm trying to use the hashcode of a guid as a random voucher name for a website, and have been trying to write new records to a SQL table with the Hashcode variable but it doesn't work.

command.Parameters.Add("@voucherName", SqlDbType.NVarChar)
    command.Parameters("@voucherName").Value = Guid.NewGuid().GetHashCode()

When using that code it just puts a whole Guid in the field. How can I make sure it's only going to use a hashcode instead?

Edit

This is the full function used to add the record to my database. It is passed a guid from another function to act as strID

Dim connect As New SqlConnection
    Dim query As String = ""
    connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection = yes; DATABASE = GlobalPCSQL"
    connect.Open()
    query = "INSERT into dbo.X_WW_VOUCHER_DETAILS (vID, voucherName, expiryDate, validUses, cartOrItem, validStockCode, discountAmount, dollarOrPercent, freebieStockCode, chkCartTotal, cartTotalOverUnder, cartTotalAmount, chkItemPrice, itemPriceOverUnder, itemPriceAmount, chkNoInCart, noInCartOverUnder, noInCartAmount, chkNoOfProduct, noOfProductOverUnder, noOfProductAmount, chkRequiredStockCode, requiredStockCode, category, description) "
    query += "VALUES(@vID, @voucherName, @expiryDate, 1, 0, , 10, 1, , 1, 0, 200, 0,  ,  , 0, , , 0, , , 0, , , Welcome Voucher, 10% off first order over $200. Valid 7 days.)"

    Dim command As New SqlCommand(query, connect)
    command.Parameters.Add("@vID", SqlDbType.UniqueIdentifier)
    command.Parameters("@vID").Value = strID
    command.Parameters.Add("@voucherName", SqlDbType.NVarChar)
    command.Parameters("@voucherName").Value = Guid.NewGuid.ToString().GetHashCode()
    command.Parameters.Add("@expiryDate", SqlDbType.DateTime)
    Dim exDate As DateTime = DateTime.Now
    exDate.AddDays(7)
    command.Parameters("@expiryDate").Value = exDate

    command.ExecuteNonQuery()
    connect.Close()

What's really weird is that whether I use guid.newguid().toString() or strID.toString() to start things off... both vID and voucherName end up with the same guid as their value.

1

There are 1 answers

3
Fabian Bigler On BEST ANSWER

Well, are you looking for a hashcode like this?

"OZVV5TpP4U6wJthaCORZEQ"

Then this answer might be useful:

Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=","");
GuidString = GuidString.Replace("+","");

Extracted from here. On the linked post there are many other useful answers. Please take a look!

Other useful links:

Edit: Doublechecking your code, you might change it from Guid.NewGuid.ToString().GetHashCode()

to

Guid.NewGuid.GetHashCode().ToString()