Convert string value back to GUID value - c#

i have a guid value that i store in my hidden variable.
say for eg (303427ca-2a5c-df11-a391-005056b73dd7)
now how do i convert the value from this hidden field back to GUID value (because the method i would be calling expects a GUID value).
thank you.

Just use the overloaded constructor:
try
{
Guid guid = new Guid("{D843D80B-F77D-4655-8A3E-684CC35B26CB}");
}
catch (Exception ex) // There might be a more appropriate exception to catch
{
// Do something here in case the parsing fails.
}

You are making it pretty easy on an attacker by storing the Guid in a string. Trivial to find back in, say, the paging file. Store it in a Guid and kill two birds with one stone.

string strGuid;
strGuid = (your guid here);
Guid guid = new Guid(strGuid);
For more info, MSDN

Guid has a constructor for string Guids.
Guid guid = new Guid(myStringGuid);

new Guid(myHiddenFieldString)

I think it can be done simply as following:
Guid MyGuid = new Guid(stringValue);

In .NET4 onwards you can also use:
Guid myGuid = Guid.Parse(myGuidString);
Just a matter of coding preference, but some people find this more intuitive.

Related

I have an Attribute called "public" and i have to access it [duplicate]

a bit of an unusual one.. but I was wondering if anyone knew how I could declare a reserved word as a variable. I have the following code, but it does not like my use of the long variable name. I know I could rename it, but for instrest sakes I would like to know if this is at all possible.
private string lat;
private string long;
public string Lat
{
get
{
return lat;
}
}
public string Long
{
get
{
return long;
}
}
Yes, you can if you really want to:
private string #long;
The actual name of the variable (as reported by reflection etc) is just long; the # sign tells the compiler to ignore the fact that it's also a keyword.
I would very strongly advise against this, however.
As others have mentioned, you can escape a reserved word with #.
In your example you don't really need to, I would write the property like this:
private string _long;
public string Long
{
get
{
return _long;
}
}
And the underscore and the capital L make it compile.
But it's kind of a tradition to call them Lat and Lon, or even better: Latitude and Longitude.
Yes, you can. Using the # symbol.
This will work, for example: private string #long;
Doing this is highly not recommended, but it is possible.
Not an answer I know as I would steer clear of using reserved words as variable names, but if you insist then at least use the following:
private string lat;
private string #long;
public string Lat
{
get
{
return this.lat;
}
}
public string Long
{
get
{
return this.long;
}
}
I may be late to this party, but I thought I would throw in another place where using a reserved word as a variable name is a good idea!!
I am writing a web control, where I want one of the properties to be "class" in a similar manner as other elements have a "class" property.
So, indeed I will make my property be: "public string #class {get{} set{}}"

Convert a string Id to unique Guid (or from md5 to Guid)?

I would like to create a system to convert an existing id (integer id or custom string id)
I would like to create a helper or extension method that generate a Guid from any int, long or string value. The idea is to update a database but keep some tracking from my old database. Each time I convert a string id like "O-2019-10-15" the system generate the same unique Guid. Let's focus on string here.
public static Guid GenerateGuid(string input)
{
// Convertion
byte[] _byteIds = Encoding.UTF8.GetBytes(input);
//What about using MD5?
MD5CryptoServiceProvider _md5 = new MD5CryptoServiceProvider();
byte[] _checksum = _md5.ComputeHash(_byteIds);
// Convert ?
string part1 = /* ??? */;
string part2 = /* ??? */;
string part3 = /* ??? */;
string part4 = /* ??? */;
string part5 = /* ??? */;
//Concat these 4 part into one string
return Guid.Parse("{0}-{1}-{2}-{3}-{4}", part1, part2, part3, part4, part5);
}
What do you think? Is md5 a correct start? Is there any rule in Guid() representation?
The idea of md5 is that I can convert everything to a 16 byte signature. From there I just need to convert it as Guid(). But I don't know the details about the Guid. Is there any rules already existing, reserved position for any data or other information?
I wouldn't do it like this.
I would use Guid.NewGuid() for new id and then keep the old id alongside it (or in a translation table).
Next time I need the new id I would look for the old id and see if I already have a guid for it.
If it is critical to keep one Id, which I don't recommend, I would have it as a $"{guid}+{oldid}".
For the moment I did this
Guid GenerateGuid(string input)
{
byte[] _byteIds = Encoding.UTF8.GetBytes(input);
MD5CryptoServiceProvider _md5 = new MD5CryptoServiceProvider();
byte[] _checksum = _md5.ComputeHash(_byteIds);
//Convert checksum into 4 ulong parts and use BASE36 to encode both
string part1 = BitConverter.ToString(_checksum, 0, 4).Replace("-", string.Empty);
string part2 = BitConverter.ToString(_checksum, 4, 2).Replace("-", string.Empty);
string part3 = BitConverter.ToString(_checksum, 6, 2).Replace("-", string.Empty);
string part4 = BitConverter.ToString(_checksum, 8, 2).Replace("-", string.Empty);
string part5 = BitConverter.ToString(_checksum, 10, 6).Replace("-", string.Empty);
return Guid.Parse($"{part1}-{part2}-{part3}-{part4}-{part5}");
}
To avoid collision the input must be unique too in my environment. I will prefix it with a namespace.
Creating deterministic UUIDs based on an existing namespace is exactly what UUIDv3/v5 are intended for. However, first you will need a namespace UUID.
A convenient (and valid) way to accomplish this is hierarchical namespaces. First, use the standard DNS namespace UUID plus your domain name to generate your root namespace:
Guid nsDNS = new Guid("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
Guid nsRoot = Guid.Create(nsDNS, "myapp.example.com", 5);
Then create a namespace UUID for your string:
Guid nsFoo = Guid.Create(nsRoot, "Foo", 5);
Now you're ready to use your new Foo namespace UUID with individual names:
Guid bar = Guid.Create(nsFoo, "Bar", 5);
The benefit of this is that anyone else will get completely different UUIDs than you, even if their strings (other than the domain, obviously) are identical to yours, preventing collisions if your data sets are ever merged, yet it's completely deterministic, logical and self-documenting.
(Note: I've never actually used C#, so if I got the syntax slightly wrong, feel free to edit. I think the pattern is clear regardless.)

Cannot convert string to GUID in C#.NET [duplicate]

This question already has answers here:
Test if string is a guid without throwing exceptions?
(19 answers)
Closed 5 years ago.
Why would the cast (to a System.Guid type) statement be invalid (second line in try block)?
For example, suppose I have a string with a value of "5DD52908-34FF-44F8-99B9-0038AFEFDB81". I'd like to convert that to a GUID. Is that not possible?
Guid ownerIdGuid = Guid.Empty;
try
{
string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString();
ownerIdGuid = (Guid)ownerId;
}
catch
{
// Implement catch
}
Try this:
Guid ownerIdGuid = Guid.Empty;
try
{
string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString();
ownerIdGuid = new Guid(ownerId);
}
catch
{
// implement catch
}
Try this:
ownerIdGuid = Guid.Parse(ownerId);
ownerId is a string, you cannot cast it to a Guid directly.
You cannot cast directly from string to Guid. Instead, use either:
Guid.Parse (throws FormatException on invalid format); or
Guid.TryParse (returns false on invalid format)
Try one of these:
Guid.Parse
Guid.TryParse
Gruid.TryParseExact
in .NET 4.0 (or 3.5)
You need to use Guid.Parse to convert from string to Guid
System.Guid x = new System.Guid("5DD52908-34FF-44F8-99B9-0038AFEFDB81") works and answers what's being asked
(I know this is an old post)

Need help with error:: The best overloaded method match for 'int.Parse(string)' has some invalid arguments

dsgetQuesTypeID = objdalQuesTypeID.GetQuesTypeID(int.Parse(QuesTypeID)); //error here
Whats wrong ?
if you see the int.Parse in metadata explorer
//
// Summary:
// Converts the string representation of a number to its 32-bit signed integer
// equivalent.
//
// **Parameters:
// s:
// A string containing a number to convert.**
//
// Returns:
// A 32-bit signed integer equivalent to the number contained in s.
//
public static int Parse(string s);
it requires a string input to be parsed , but QuesTypeID is int so that's why no overloaded method is found so to correct the problem , you need to do following
int.Parse(QuesTypeID.ToString());
You have a member with the same name QuesTypeID as the name of the variable passed to the method. One is int and one is String. Try to rename the variable from the method to something else, like: quesTypeID. I think this would solve your problem. Also you should use Int.TryParse instead of Int.Parse.
You maybe passing null value into GetQuesTypeID(string QuesTypeID)

Why is my enum.Parse method failing?

I'm trying to dynamically set an enum based on the value in a string so far so good I don't know what I've been doing wrong. I have the following code:
public enum TagLabels : long
{
TurnLeft = 0x0000000000000000000030A38DB1,
TurnRight = 0x00000000000000000000307346CC,
LiftApproach = 0x0000000000000000000012107A8D
}
TagLabels IDs;
string someID = "0x0000000000000000000012107A8D";
IDs = (TagLabels)Enum.Parse(typeof(TagLabels), someID ); //<== I get runtime error on this line
I cannot see what's wrong with what I'm doing.
Enum.Parse is intended to convert a string representation of the symbolic name into an enum val, as in Enum.Parse("TurnLeft"). If what you have is a string giving the numeric value, then you should just parse the string as the corresponding integer type and cast it to the Enum val.
IDs = (TagLabels)long.Parse("0x0000000000000000000012107A8D");
IDs = (TagLabels)Convert.ToInt64(someID, 16);
EDIT: You have a string that is in hex format and not a direct number. So, it needs conversion to int first.
If the Enum value exists, you can cast an int value to Enum type.
EDIT2: Changed after Marc's suggestion from Convert.ToInt32 to Convert.ToInt64
SomeID is a string and your enum is a long.
Try using TurnLeft instead of "0x0000000000000000000012107A8D"
Where is the string you're parsing? Aren't you trying to turn a string like "TurnLeft" into TagLabels.TurnLeft?
MSDN

Categories