Get Guid with query string - asp.net

I get a Guid value in a variable like that
var getvalueGuid = db.Clients.Where(u => u.Numero_telephone ==
TextBox_numero_telephone.Text).Select(u => u.GuID).FirstOrDefault();
And i would like to convert it in a query string like that:
getvalueGuid = Request.QueryString["id"];
How to do?

You can use Guid.TryParse:
Guid getvalueGuid;
if(Guid.TryParse(Request.QueryString["id"], out getvalueGuid))
{
// successfully parsed
}

You will be able to get that inside a QueryString, only if you're having the url like
www.example.com/page?id=[guid_here]
Then when you'll use the code, it would provide you with a String which would contain the Query String provided in the URL.

It's hard to understand your question as you're missing a lot of detail, but I think you want to get a strongly-typed GUID value from the querystring?
System.Guid doesn't have a TryParse method, so you'll have to use the constructor and catch any exceptions thrown:
If so, then do this:
String guidStr = Request.QueryString["id"];
Guid guid = null;
try {
guid = new Guid( guidStr );
} catch(ArgumentNullException) {
} catch(FormatException) {
} catch(OverflowException) {
}
if( guid == null {
// Inform user that the GUID specified was not valid.
}
The three exceptions (ArgumentNullException, FormatException, and OverflowException are documented in the notes for the Guid(String) constructor here: http://msdn.microsoft.com/en-us/library/96ff78dc%28v=vs.110%29.aspx
Update:
I forgot that .NET 4.0 introduced the TryParse method. Use that instead if you're using .NET 4.0 or later: http://msdn.microsoft.com/en-us/library/system.guid.tryparse%28v=vs.110%29.aspx

Guid requestGuid;
if (Guid.TryParse(Request.QueryString["id"], out requestGuid))
{
// Do logic here with requestGuid
}

Related

ASP.NET Core 2 IFormCollection returning StringValues

Recently the IFormCollection in the platform I'm building started returning values of the type Microsoft.Extensions.Primitives.StringValues. when it used to return strings.
The controllers were made with strings in mind and now that are a lot of forms that are not working.
Is there any explanation to this, or a way to revert it?
As far as I'm aware ASP.NET Core's IFormCollection has always been a collection of StringValues. The reason is simple: multiple values can be posted for any particular key, making it potentially impossible to set the value if the type was merely string. There is no way to "revert" this. Change your code accordingly.
Or, better yet, stop using IFormCollection. Bind to strongly-typed models. That's always the best way.
For others coming here also confused by seeing IFormCollection giving StringValues. You may be familiar with .NET Frameworks FormCollection class, which gives strings. The reason for the change is valid and explained by #Chris Pratt in his answer here.
To make IFormCollection and StringValues feel familiar again consider any of these simple extensions:
// Example: var name = collection["name"].FirstOrNull();
// Equal to (.NET Framework): var name = collection["name"];
public static string FirstOrNull(this StringValues values)
{
if (values.Count > 0)
{
return values[0];
}
return null;
}
// Example: var name = collection["name"].FirstOr("John Doe");
// Equal to (.NET Framework): var name = collection["name"] ?? "John Doe";
public static string FirstOr(this StringValues values, string fallback)
{
if (values.Count > 0)
{
return values[0];
}
return fallback;
}
// Example: var name = collection.ValueOrFallback("name", "John Doe");
// Equal to (.NET Framework): var name = collection["name"] ?? "John Doe";
public static string ValueOrFallback(this IFormCollection collection, string key, string fallback)
{
if (collection[key].Count > 0)
{
return collection[key][0];
}
return fallback;
}
Also consider the built-in TryGetValue:
if (collection.TryGetValue("name", out var name))
{
// at least one name did exist
}
Alt.
var name = collection.TryGetValue("name", out var names) ? names[0] : "John Doe";

How can the Identity.GetUserId() be made to return a Guid instead of a string?

I am using ASP.Net Identity 2 but soon hope to change to Identity 3 when it becomes more stable (anyone know when that might be?). Here's a sample of my code:
content.ModifiedBy = User.Identity.GetUserId();
The Content table stores ModifedBy as a UNIQUEIDENTIFIER and the Content object assigns a datatype of Guid to ModifiedBy
When I look at the signature for GetUserId() it returns a string.
So how can I take the users UserId and put it into the ModifiedBy which is a Guid?
A guid can take a string as a constructor
content.ModifiedBy = new Guid( User.Identity.GetUserId());
You can use Guid.Parse() or Guid.TryParse()
content.ModifiedBy = Guid.Parse(User.Identity.GetUserId());
https://msdn.microsoft.com/en-us/library/system.guid.parse%28v=vs.110%29.aspx
As I was using same method over and over I added the following extension:
public static class ExtensionMethods
{
public static Guid ToGuid(this string value)
{
Guid result= Guid.Empty;
Guid.TryParse(value, out result);
return result;
}
}
and then I used this:
User.Identity.GetUserId().ToGuid()

Validate a string to be json or not in asp.net

is there any way to validate a string to be json or not ? other than try/catch .
I'm using ServiceStack Json Serializer and couldn't find a method related to validation .
Probably the quickest and dirtiest way is to check if the string starts with '{':
public static bool IsJson(string input){
input = input.Trim();
return input.StartsWith("{") && input.EndsWith("}")
|| input.StartsWith("[") && input.EndsWith("]");
}
Another option is that you could try using the JavascriptSerializer class:
JavaScriptSerializer ser = new JavaScriptSerializer();
SomeJSONClass = ser.Deserialize<SomeJSONClass >(json);
Or you could have a look at JSON.NET:
http://james.newtonking.com/projects/json-net.aspx
http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
A working code snippet
public bool isValidJSON(String json)
{
try
{
JToken token = JObject.Parse(json);
return true;
}
catch (Exception ex)
{
return false;
}
}
Source
You can find a couple of regular expressions to validate JSON over here: Regex to validate JSON
It's written in PHP but should be adaptable to C#.

In asp.net is there a function to validate an email address?

I've noticed that if you try to send an email to an invalid address, an exception is raised:
MailAddress To=new MailAddress("invalidemailaddress","recipientname");
throws:
"The specified string is not in the form required for an e-mail address"
This means that there must be a .Net function which is executed in MailAddress to check if the email address is valid or not. Is there a way to call this 'validate' function directly? This way I won't need to create my own IsValid function.
No but you can make one:
public bool ValidateEmailAddress (string email)
{
if (string.IsNullOrEmpty (email)) return false;
try
{
MailAddress to = new MailAddress (email);
return true;
}
catch (WhateverException e)
{
return false;
}
}
Answering comments. I am aware this technique is regarded as a bad one and with reason. What I would like to point out is that this approach will give you 100% guarantee the .NET mailing library will be able to send to a validated address lately. The problem with Regexes (of which there are plenty) is that each one addresses one particular subset of the set of technically correct addresses as per specification. One would be narrower, the other one would be wider than the subset defined internally in .NET. If you were to use Regex validation, then in the first case your Regex would cut off a portion of the valid addresses (as seen by .NET), in the latter case the validaton will let through addresses that the .NET mailing library won't treat as invalid per its own internal validation. The one true way to make sure you valid set 100% matches the .NET set (or of any other third party library you would use) is to fall for the try/catch approach, unless of course this third party library offers some validation method already.
Yes, there is such a .Net function, but its functionality is unaccessible by "standard" means: MailAdress uses a private ParseAddress method, which in turn uses System.Net.Mime.MailBnfHelper. The latter is an internal class, so it's not (easily) accessible outside the framework itself.
Thus, the only way to use these functions would be to use reflection, which I strongly advise against. Since these functions are undocumented and unaccessible without reflection, their implementation might change and your code might break in future versions of the framework.
There's a good example of an email validation function on CodeProject.
Original Source Code written by Vasudevan Deepak Kumar:
public static bool isEmail(string inputEmail)
{
inputEmail = NulltoString(inputEmail);
string strRegex = #"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Unfortunately, there is no way to get at that functionality without reverse-engineering it or using that specific exception, sadly.
The traditional way to validate an email address has always been with regular expressions, but there are lengths you can go beyond that to validate emails even further, if you so wish:
The Forgotten Art of Email Address Validation
You could write your own class:
class EmailAddress
{
private MailAddress _email;
public string Address
{
get
{
return _email == null ? string.Empty : _email.Address;
}
}
public string DisplayName
{
get
{
return _email == null ? string.Empty : _email.DisplayName;
}
}
public string Host
{
get
{
return _email == null ? string.Empty : _email.Host;
}
}
public string User
{
get
{
return _email == null ? string.Empty : _email.User;
}
}
public EmailAddress(string email)
{
try {
_email = new MailAddress(email);
}
catch (Exception) {
_email = null;
}
}
public EmailAddress(string email, string displayName)
{
try {
_email = new MailAddress(email, displayName);
}
catch (Exception) {
_email = null;
}
}
public EmailAddress(string email, string displayName, Encoding displayNameEncoding)
{
try {
_email = new MailAddress(email, displayName, displayNameEncoding);
}
catch (Exception) {
_email = null;
}
}
public bool IsValid()
{
return _email == null ? false : true;
}
public override string ToString()
{
return this.Address;
}
}
Now you use it just as MailAddress but there is now no exception when the Email address is not valid. Instead you call the IsValid method:
var email = new EmailAddress("user#host.com");
if (email.IsValid()) {
...
}
else {
...
}

Caching Patterns in ASP.NET

So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myObject.someValue != cache.Get("myObjectKey").someValue)
myObject.SaveToDatabase();
So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one.
My question is: is there a better way to do this, some pattern, that you could recommend? I can't be the only person that's done this before :)
Dirty tracking is the normal way to handle this, I think. Something like:
class MyObject {
public string SomeValue {
get { return _someValue; }
set {
if (value != SomeValue) {
IsDirty = true;
_someValue = value;
}
}
public bool IsDirty {
get;
private set;
}
void SaveToDatabase() {
base.SaveToDatabase();
IsDirty = false;
}
}
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myNewObject.IsDirty)
myNewObject.SaveToDatabase();
I've done similar things, but I got around it by cloning too. The difference is that I had the cache do the cloning. When you put an object into the cache, the cache will clone the object first and store the cloned version (so you can mutate the original object without poisoning the cache). When you get an object from the cache, the cache returns a clone of the object instead of the stored object (again so that the caller can mutate the object without effecting the cached/canonical object).
I think that this is perfectly acceptable as long as the data you're storing/duping is small.
A little improvement on Marks anwser when using linq:
When using Linq, fetching entities from DB will mark every object as IsDirty.
I made a workaround for this, by not setting IsDirty when the value is not set; for this instance: when null. For ints, I sat the orig-value to -1, and then checked for that. This will not work, however, if the saved value is the same as the uninitialized value (null in my example).
private string _name;
[Column]
public string Name
{
get { return _name; }
set
{
if (value != _name)
{
if (_name != null)
{
IsDirty = true;
}
_name = value;
}
}
}
Could probably be improved further by setting IsDirty after initialization somehow.

Resources