10

I have a few [Flags] enums in my code I'd like to expose to JavaScript without copy&pasting. SignalR seems to be doing something similar for their Hub-proxies by mapping an URL to an Action returning the JavaScript stubs generated by reflection. Since the code is generated at runtime, it doesn't seem possible to be included into the Bundles.

As an alternative, I implemented a T4 template to generate a js file at design time:

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="EnvDte" #>
<#@ import namespace="EnvDTE" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".js" #>
Enums = {
<#
    var visualStudio = (Host as IServiceProvider).GetService(typeof(EnvDTE.DTE))
                        as EnvDTE.DTE;
    var project = visualStudio.Solution.FindProjectItem(this.Host.TemplateFile)
                                        .ContainingProject as EnvDTE.Project;

    foreach(EnvDTE.ProjectItem item in GetProjectItemsRecursively(project.ProjectItems))
    {
        if (item.FileCodeModel == null) continue;
        foreach(EnvDTE.CodeElement elem in item.FileCodeModel.CodeElements)
        {
            if (elem.Kind == EnvDTE.vsCMElement.vsCMElementNamespace)
            {
                foreach (CodeElement innerElement in elem.Children)
                {
                    if (innerElement.Kind == vsCMElement.vsCMElementEnum)
                    {
                        CodeEnum enu = (CodeEnum)innerElement;
#>  <#= enu.Name #>: {
<#
        Dictionary<string, string> values = new Dictionary<string, string>();
        foreach (CodeElement child in enu.Members)
        {
            CodeVariable value = child as CodeVariable;

            if (value != null) {
                string init = value.InitExpression as string;
                int unused;
                if (!int.TryParse(init, out unused))
                {
                    foreach (KeyValuePair<string, string> entry in values) {
                        init = init.Replace(entry.Key, entry.Value);
                    }
                    init = "(" + init + ")"; 
                }
                values.Add(value.Name, init);
                WriteLine("\t\t" + value.Name + ": " + init + ",");
            }
        }
#>
    },
<#
                    }
                }
            }
        }
    }
#>
};
<#+
  public List<EnvDTE.ProjectItem> GetProjectItemsRecursively(EnvDTE.ProjectItems items)
  {
      var ret = new List<EnvDTE.ProjectItem>();
      if (items == null) return ret;
      foreach(EnvDTE.ProjectItem item in items)
      {
        ret.Add(item);
        ret.AddRange(GetProjectItemsRecursively(item.ProjectItems));
      }
      return ret;
  }
#>

However this feels fragile with EnvDTE. Especially the logic to handle enums like:

[Flags]
public enum Access
{
    None = 0,
    Read = 1,
    Write = 2,

    ReadWrite = Read | Write
}

with composite values is a dirty hack with string replacements. The T4 template above will generate:

Enums = {
    Access: {
        None: 0,
        Read: 1,
        Write: 2,
        ReadWrite: (1 | 2),
    },
};

Is there a cleaner way to achieve this? Ideally some kind of design-time reflection to generate the js file so it is available for bundling.

0

2 Answers 2

1
+50

I think you can use Bundle Transforms to accomplish this...

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

You can define a bundle and attach an IBundleTransform class which interpolates the content of the source files. You should be able to use reflection to write the JavaScript to the output stream.

If you wanted to do it in a hacky way this would be fairly easy to do. You could just feed it an empty file and hard-code your class to use reflection to write the JavaScript you want.

Now, if you want to design it in a way that you don't need to modify your IBundleTransform class in order to add additional enums to your javascript output, you'd need to put some extra work into a real structure. For example, let's say you have all your enums in a file called Enums.cs, you could add that file to the Include list of your bundle and you could dynamically parse it for enum declarations and then use reflection to find them by name in order to output each one in the resulting JavaScript file.

0

I like to use custom attributes and a controller action in my app. During development, I add an enum value and hit 'Run'. I browse to my controller action (a link that's only available during debugging). The controller crawls all of my enums that implement the custom [GenerateJavascriptEnum] attribute and voila, I see a popup browser window with all the nice javascript. I copy/paste and refresh the browser to get the changes on the client. It's been very comfortable with minimal fuss.

2
  • I'd consider that even worse than the T4-based approach I meantioned in the question, since you not only have to copy&paste stuff around, but have to visit a magic URL in the browser and then recompile (!) after copy&pasting, where T4 just needs rightclick->run custom tool
    – mensi
    May 21, 2013 at 20:26
  • No recompile. Just a browser refresh. No magic URL, a link that's visible when debugging. This has actually worked really well and has been well-received by a few teams I've worked on. T4 template code tends to be pretty esoteric, fragile, and hard to maintain. I've used both approaches and have found custom attribute solution to be far more efficient.
    – M Smearer
    May 22, 2013 at 16:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.