0

I need to do this steps:

  • parse a c# .cs file
  • find all public class methods who return JsonResult
  • if JsonResult is created with a dynamic object, create a cs file with class definition who map dynamic object

For example from this cs code file:

public partial class HomeController: Controller
{
   public JsonResult MyMethod()
   {
      var result = new 
      {
         Result = false,
         ErrorMessage = "Test"
      };

      return Json(result);
   }
}

I need to produce another cs file as below:

public partial class HomeController: Controller
{
   public class MyMethodResult
   {
      public bool Result {get;set;}
      public string ErrorMessage {get;set;}
   }
}

Can be done with T4 template or Roslyn?

How to convert a dynamic object to a strongly typed class definition?

Thanks

Claudio
  • 133
  • 2
  • 11
  • 1
    What do you do when the function returns an `object` that *could* be a `json` object...? – Trevor May 17 '19 at 20:05
  • Possible duplicate of [Parser for C#](https://stackoverflow.com/questions/81406/parser-for-c-sharp) – gunr2171 May 17 '19 at 20:13
  • 1
    @Çöđěxěŕ Then it doesn't fit the pattern and it's ignored. Claudio, I'd look at doing this with [Roslyn](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/) and T4. – 15ee8f99-57ff-4f92-890c-b56153 May 17 '19 at 20:22
  • @EdPlunkett as i have no experience on roslyn or t4, can you give me a sample code? Expecially.. can be possible to parse a dynamic object and convert to class code? Thanks – Claudio May 17 '19 at 20:38
  • @Claudio Sadly, I have little experience with either. – 15ee8f99-57ff-4f92-890c-b56153 May 17 '19 at 20:38
  • @gunr2171 my question is more specific, and not about c# parses – Claudio May 17 '19 at 20:39
  • This can be achieved with a propper combination of T4 Templating, C# file parser and good use of RegEx where you read your .CS files' lines, with RegEx filter out your public methods with specific JsonResult, and let your T4 write output to a new file or multiple files. – Tim Maes May 20 '19 at 07:28

0 Answers0