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.

Sudev G
  • 55
  • 6

3 Answers3

4

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

\bnew\s*{
deerchao
  • 10,454
  • 9
  • 55
  • 60
  • yes, I've already done that, but I'd like to have something which can be used in automated reports like TFS Build Warnings. – Sudev G Nov 21 '12 at 14:53
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" });
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Servy
  • 202,030
  • 26
  • 332
  • 449
  • 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. – Sudev G Nov 21 '12 at 15:02
  • @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. – Servy Nov 21 '12 at 15:05
  • Question was about searching and restricting anonymous types usage. Your answer should be a comment. – Sergey Berezovskiy Nov 27 '12 at 16:11
  • @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 Nov 27 '12 at 16:22
  • @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 :) – Sergey Berezovskiy Nov 27 '12 at 16:32
  • @Servy PS I removed downvote, and more - upvoted your answer, because it is a solution to problem of OP – Sergey Berezovskiy Nov 27 '12 at 16:34
  • @lazyberezovsky You really needed to edit the post just to add in a few spaces? It's not a *problem*, but why? As to the other point. SO is designed such that an answer should *answer the question or solve the problem*. It shouldn't be used for interesting tangents or possible improvements that aren't germane to the issue at hand. This answer was an attempt to solve the problem the OP had in a different manor than they had considered. Your answer was attempting to "fix" code that was already working, and didn't help solve the OP's underlying problem (even in a way they didn't expect). – Servy Nov 27 '12 at 16:38
  • @Servy I edited post to remove downvote and replace it with upvote. Have a nice day. – Sergey Berezovskiy Nov 27 '12 at 16:53
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.

Community
  • 1
  • 1
weston
  • 54,145
  • 21
  • 145
  • 203