Validate a string to be json or not in asp.net - 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#.

Related

WEB.API returning string property as json

We have a fun situation where we are storing json as a string in SQL Server. We don't not care what is in this object its pretty much a passthrough property. Passthrough meaning we just save it for clients and return it as is. We never read it in C#. I'm storing it as a nvarchar in the database but I'm trying to figure out how i can automagically serialize that string into a json object to return to the client. I dont want to have to in javascript call fromJson.
We are using Newtonsoft as our Json Serializer. Here is the highlevel setup:
DTO:
public class MyDto{
public dynamic SessionBag { get;set;}
}
Entity Framework Entity:
public class My{
public string SessionBag { get;set;}
}
A client would post/put us:
{"SessionBag":{"Name":"test"}}
We would then save it in the db as a string:
"{"Name":"test"}"
How can I serialize this so when it returns from Web.API it looks like:
{
SessionBag:{
Name: "test"
}
}
I'm currently messing around trying to get it to save using dynamic / object. But i can't figure how how to return it as a json object. I would love to figure out how to do this with just annotations.
Here is how I convert it to a string to save:
if (dto.SessionBag != null){
var serializer = JsonSerializer.Create(new JsonSerializerSettings(){
NullValueHandling = NullValueHandling.Ignore
});
using (var writer = new StringWriter()){
serializer.Serialize(writer, dto.SessionBag);
entity.SessionData = writer.ToString();
}
}
In case its helpful our WebApiControllers are pretty simple and just return an IHttpActionResult with the dto. All feedback is welcome.
So I think i figured it out. In my dto:
[JsonIgnore]
public string SessionBagString { get; set; }
public JObject SessionBag
{
get
{
if (!string.IsNullOrEmpty(SessionBagString))
{
return JObject.Parse(SessionBagString);
}
return null;
}
set
{
if(value != null)
{
SessionBagString = value.ToString();
}
}
}
In my repo code I now have:
if (dto.SessionBag != null)
{
entity.SessionBagString = dto.SessionBagString;
}
That pretty much worked for me. Let me know if there is a better way to do it.

How to deserialize

How to deserialize Task response using Json .
public HttpResponseMessage Put(int id, ModelClass modelbject)
{
if (ModelState.IsValid && id == modelbject.modelbjectID)
{
db.Entry(modelbject).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
I want to derialize this and check the IsSuccessStatusCode in my class where i am calling this put method. How can i achieve ?
I want to derialize this and check the IsSuccessStatusCode in my class where i am calling this put method.
You don't have to "deserialize" anything. The method returns an HttpResponseMessage, which has the property you're looking for.
var result = yourController.Put(someId, someObject);
var success = result.IsSuccessStatusCode;
Perhaps the fact that this is a web application is adding some confusion to how you're picturing it. But if you have a class which directly calls this method, then what you get back is simply an HttpResponseMessage object. Which can be inspected just like any other object. No actual web layer is involved in that interaction.

Get Guid with query string

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
}

web-services-enhancements: ASP.NET - Missing nodes at SOAPEXTENSION

I want to manipulate the soapbody before sending it.
I have inherited SoapExtension in myExtension class.
But, when i see the soapbody, some of the nodes were missing.
Code snippet:
public override void ProcessMessage(SoapMessage message)
{
StreamReader readStr;
StreamWriter writeStr;
string soapMsg1;
// System.Diagnostics.Debugger.Break();
XmlDocument xDoc = new XmlDocument();
// a SOAP message has 4 stages. Weare interested in .AfterSerialize
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
{
// Get the SOAP body as a string, so we can manipulate...
String soapBodyString = getXMLFromCache();
.
.
.
.
Can anybody tell me the reason why they are missing ....
Thanks in advance,
Suresh
The problem is not with buffer/caching the object.
ex:
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool MOCEventStatusSpecified {
get {
return this.mOCEventStatusFieldSpecified;
}
set {
this.mOCEventStatusFieldSpecified = value;
}
}
This should be made true if we are sending the mOCEventStatus field. Otherwise, mOCEventStatus field won't appear in the output xml.

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 {
...
}

Resources