2

I'd like to search all the places like following where the Anonymous types in Controllers is being used as follows.

if(success) {
    returnData = JsonConvert.SerializeObject(new { Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new { Success = false, Message = "Operation failed" });
}

In above case the returnData is a JsonResult and its used in our Razor views to parse the status of the AJAX requests.

I want to minimize the usage of Anonymous types in such case as this could be maintenance issue as compiler would not raise any warning/errors if any of the line is written as new { Succes = true, Message = "Operation completed successfully"} and it would result into run-time error in the client-side scripts.

Any insights on restricting such situation or detecting such instances would be appreciated.

3 Answers 3

4

Why not search in solution/project for this with option "Use Regular Expressions" on?

\bnew\s*{
Sign up to request clarification or add additional context in comments.

1 Comment

yes, I've already done that, but I'd like to have something which can be used in automated reports like TFS Build Warnings.
2

Just don't use an anonymous type. Create a new concrete type with the data you plan to use:

public class JSONMessage
{
    public string Message { get; set; }
    public bool Success { get; set; }
}

Then those lines can be changed to:

if(success) {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = true, Message = "Operation completed successfully" });
}
else {
    returnData = JsonConvert.SerializeObject(new JSONMessage(){ Success = false, Message = "Operation failed" });
}

8 Comments

While I'm marking your suggestion as answer to my question, what I'd like to know is is there any way to detect usage of Anonymous types by any of compiler switches or something like that so that if a developer is bypassing the guideline they get to know immediately.
@SudevG The compiler wouldn't be able to tell you that, but you could potentially use a 3rd party code analysis tool, such as Resharper. I'm not very familiar with it, but I know you can use it to write validation scripts for things like this. Not sure if it's scripting framework is powerful enough, or if it would be easy/hard for something like this.
Question was about searching and restricting anonymous types usage. Your answer should be a comment.
@lazyberezovsky I find it hilarious that you had to start searching through all of my answers in an attempt to find a NAA just because I called you out on one of your inappropriate answers. As for this answer, the OP felt marking it as the answer was appropriate, so clearly it wasn't a completely irrelevant tangent. You should really learn to take critiques in stride better, and learn to admit when you've done something wrong.
@Servy that what I was talking about - it's up to OP to decide how answer helpful for task he wants to complete. And for beginners it is extremely useful to show other solutions, which they don't know about. I never downvote other's answers, if I find them helpful. If answer is incorrect, then yes, it worth downvoting. PS it took less then a minute to find such answer in your history (and anyone has such answers). So, it's time for you to admit you've done something wrong :)
|
1

How about wrapping up the json call so you can have run time error/assert:

First an extension to detect anonymous from here: Determining whether a Type is an Anonymous Type

public static class TypeExtension {

    public static Boolean IsAnonymousType(this Type type) {
        var hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
        var nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
        var isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;    
        return isAnonymousType;
    }
}

Then use that it your new method.

 public static object JsonSeralize(object obj)
   {
      Debug.Assert(!obj.getType().IsAnonymousType());     
      return JsonConvert.SerializeObject(obj);
   }

Now you can easily search for places that illegally call JsonConvert.SerializeObject directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.