Where have I been!?!

Alright confession time. It's hard to keep a blog going. Yes it's been almost a year since I last wrote & I'm not happy about that. So far I've missed January but I'm going to try this again. Hopefully for the few people that do read this blog they will continue to visit. 

The biggest reason for my lack of blogging is the slump I recently went through as a developer. Much of this is attributed to work but I have new hope and desire to push forward with blogging. Hopefully the flame keeps burning longer & stronger.

I do have my Contact page working again. Please feel free to reach out to me with topics or just discussion in general. 

Thanks!

Ajax me!

One of my recent projects has been creating a code editor using ASP.Net MVC & Roslyn. Part of that project uses a library called ace.io. It's a really nice Javascript library that allows you to very quickly make an in-browser code editor for almost any language. 

One of the challenges I met was getting the code from the editor to the ASP.Net controller on the back end for processing. In comes jQuery Ajax. The $.ajax() function allows you to make asynchronous HTTP requests which in turn doesn't require a full page refresh. Once you have your code just send it to the controller. But let's look at the code first.
<script type="text/javascript">
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/cloud");
    editor.getSession().setMode("ace/mode/csharp");
 
    $("#btnSubmitCode").click(function () {
        var code = escape(editor.getValue());
        $.ajax({
            type: 'POST',
            url: "/Home/AnalyzeCode?Code=" + code,
            success: function (returnPayload) {
                $("#errorList").append("<li>" + returnPayload + "</li>");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console && console.log("request failed");
            },
            dataType: "text",
            contentType: "text/plain",
        });
    });
</script>
Really there are just a few simple parameters to set:
  1. type needs to be set to "POST" because we are sending data to the controller.
  2. url probably the most important. The format of the url is /{controller}/{action/method}?{parameters}. The parameters are the overload parameters for the action/method. One thing to note is that order does not mater for the parameters being sent in the Ajax call. Just make sure you spell them right! 
  3. success & error are simply what do you want to do if the call succeeds or fails. In this case with the editor we are returning diagnostics on the code from the editor & are displaying them as list items. 
  4. dataType &  contentType  are also pretty straight forward. Just set them as seen above because we are just passing text to the controller. 
As you can see getting data from Javascript to the back end in an ASP.Net MVC app is actually quite easy. One more tool in the toolbox!

Paging Doctor Roslyn!

Ever thought "Wow! It would be cool to be analyze code & get some feedback on it." Then you think "Wow! That would be insanely hard & complicated". Look no further. We now have Roslyn or better known as the .Net Compiler Platform. So where to start.

First, we need to get the Nuget package that will allow us to use the Roslyn APIs to do some code analysis & return diagnostics. You can either use the NuGet Package manager (below picture) or from the Package Manager Console & issue the following command: Install-Package Microsoft.CodeAnalysis.


Now that we have the package installed we need to include some libraries in our application. For this demo I'm just using a standard Console Application. You only need one using for Microsoft.CodeAnalysis.CSharp in your Program.cs file & you are ready to rock & roll. Below is the code to analyze a string & print out diagnostics

using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace CodeAnalyzer
{
    class Program
    {
        static void Main(string[] args)
        {
            var tree = CSharpSyntaxTree.ParseText(@"
                public void DoSomething()
                {
                
                ");
            var results = tree.GetDiagnostics().Where(x => x.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error);
 
            Console.WriteLine(results.FirstOrDefault().ToString());
            Console.ReadLine();
 
        }
    }
}
Seriously that is it. Simply create a syntax tree & get diagnostics. The compiler takes care of everything. Now in this case we are only grabbing the first error. Without the FirstOrDefault() we would get a collection (IEnumerable<Diagnostic>) of results. You can see that the above method does not have a closing bracket. So let's run the program & see what we get.
Now ain't that cool! The cool part is you could pass in any string to the ParseText() method for analysis. Say you have an ASP.Net MVC app that someone can insert custom logic. Simply call a method that has a string overload from an Controller & return the results to the user. 

Now if you want to see a pretty awesome example of using Roslyn, go to omealive.io. This is a plugin for Visual Studio that utilized Roslyn for real time code analysis without debugging or running the program. I'l let you see for youself.

Happy coding!