Showing posts with label C# 5. Show all posts
Showing posts with label C# 5. Show all posts

Tuesday, September 17, 2013

Using Microsoft Roslyn





Microsoft Roslyn is an API which exposes C# compiler as a service or one can say now the whole compiler is exposed in a form of a library which can be included in your project or application, earlier you used to write code in c# and build that code, if it is successful you get the compiled code in the form of assembly, but now you can actually build or compile the code dynamically from within your .Net applications. You can now have Build process information or compile process information which was not available earlier. So now you can pass in your code as string to the API and it will provide you with the code in Intermediate Language (IL) with syntactic and semantic information regarding your code. So the major advantage we get is one can do the Code Analysis with the help of Roslyn.

Roslyn has nothing to do with the CLR, Roslyn can do same for you as any other compiler can do, that is it can compile your code and return it in Intermediate Language which can then be passed to CLR (As we know CLR don't understand any particular language like C# or VB, so the role of every language compiler (.Net Compliant Language) is to produce a code in IL which is very well understood by the CLR)

With introduction of Roslyn (Right now Roslyn is available a Community Technology Preview) now the compilers are no more the blackbox (which earlier takes in the code writhen in managed language and outputs it as an assembly), now one can get the entire Syntax tree of the code in the form of object (API(s) are exposed to get the Syntax tree).

One of the major advantage which I see now is that you can produce code from User interface, it means that suppose your application is in Production environment and now you need to write some code, earlier you need to do the code changes and build the code again but now you can create a User Interface in your application (UI can have a textarea and a button) and you can actually write code on UI and get it compiled at runtime without doing the deployment again. But yes you have to make your application intelligent enough.

Roslyn API(s) are available as NuGet Packages; you can anytime, so one can install it very easily by Package manager.

Here is a sample code showing some of the features of Roslyn C# compiler.

First of all you need Roslyn Libraries which are available as NuGet Package which can be installed with the help of Package Manager in .Net Visual Studio. For Installing a Roslyn libraries, just open the Package manager console and type in the following command:

PM> Install-Package Roslyn.Compilers.Common

Once the installation is successful, create a sample console application or a Web Application as per your need and add the reference to the two libraries, which you have got from the above installation. Two libraries are:

Roslyn.Compilers
Roslyn.Compilers.CSharp

And you are ready to go.

Firstly we will see how to output the syntax tree or the code as the DLL. You can find the details of what the code do as inline comments within the code.
using System;
using System.IO;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

namespace SampleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            //Syntax tree is the code you want to compile at runtime
            var syntaxTree = SyntaxTree.ParseText(@"using System;
                class TestClass
                {
                    static void Main()
                    {
                        Console.WriteLine(""Testing Rolyn"");
                        Console.ReadLine();
                    }
                }");

            //Creates the copimlation, Here we are setting that compile it to a dll for the syntax tree defined above, adding references at runtime, here we are adding metadata
            //reference of System library at runtime
            var compilation = Compilation.Create("RoslynSampleApplication.dll",
                references: new[]
                {
                    new MetadataFileReference(typeof(object).Assembly.Location)
                },
                syntaxTrees: new[] { syntaxTree });

            //Here we are getting the Diagnostic results for a particular syntax tree on copilation, so if there are any errors we will get a list of that errors which can be
            //used to show it to user, These errors are just the same as we see in the Error list of Visual Studio.
            var diagnostics = compilation.GetDiagnostics();

            //Here i am prinitng the errors if any
            foreach (var diagnostic in diagnostics)
            {
                //You can also get the line number here on which the error has occurred. Code goes something like this: diagnostic.Location.GetLineSpan(usePreprocessorDirectives: true).StartLinePosition.Line
                Console.WriteLine("Error: {0}", diagnostic.Info.GetMessage());
            }

            //If we want to generate a DLL for the above syntax tree we can emit the compilation to a DLL by the following code.
            EmitResult result;
            using (var file = new FileStream("RoslynSampleApplication.dll", FileMode.Create))
            {
                result = compilation.Emit(file);
            }
        }
    }
}

The sample code I provided above does not have any errors, if you want to see some errors which are caught by the Compilation diagnostic, you can make some invalid changes in the Syntax tree and you can see the errors in the console window.
The DLL created above can now be consumed in the application. So this the way in which you can create DLL(s) at runtime, now let's see how to write a piece of code at runtime, compile it and produce the output:
 
//Syntax tree is the code you want to compile at runtime
            var syntaxTree = SyntaxTree.ParseText(@"using System;
                class TestClass
                {
                    public static string GetWelcomeMessage()
                    {
                        return ""Welcome! Abhishek Jain"";
                    }
                }");

            //Creates the copimlation, Here we are setting that compile it to a dll for the syntax tree defined above, adding references at runtime, here we are adding metadata
            //reference of System library at runtime
            var compilation = Compilation.Create("RoslynSampleApplication.dll",
                options: new CompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary),
                references: new[]
                {
                    new MetadataFileReference(typeof(object).Assembly.Location)
                },
                syntaxTrees: new[] { syntaxTree });

            //Here we are getting the Diagnostic results for a particular syntax tree on copilation, so if there are any errors we will get a list of that errors which can be
            //used to show it to user, These errors are just the same as we see in the Error list of Visual Studio.
            var diagnostics = compilation.GetDiagnostics();

            //Here i am printng the errors if any
            foreach (var diagnostic in diagnostics)
            {
                //var lineSpan = diagnostic.Location.GetLineSpan(usePreprocessorDirectives: true);
                //var startLine = lineSpan.StartLinePosition.Line;
                Console.WriteLine("Error: {0}", diagnostic.Info.GetMessage());
            }

            //Here the compiled code is emitted into memory stream which is used to create a assembly at runtime, and we are using this assembly at runtime only to invoke a
            //method present in one of the class of this assembly.
            Assembly assembly;
            using (var stream = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(stream);
                assembly = Assembly.Load(stream.GetBuffer());
            }

            //Type of class is retrieved and for that type, method is retrieved from it using reflection, Method is invoked also by using reflection
            Type testClass = assembly.GetType("TestClass");
            MethodInfo methodInfo = testClass.GetMethod("GetWelcomeMessage");
            string welcomeMessage = methodInfo.Invoke(null, null).ToString();

            Console.WriteLine(welcomeMessage);
            Console.ReadLine();
So these are the very basic samples, I am also attaching the source code, if needed you can also try at your end.

Saturday, August 17, 2013

New Features of Entity Framework 6



Introduction

In this article I provide some exciting and useful features of Entity Framework 6 beta release. Currently EF 6's beta release is available. The Beta release can be downloaded from NuGet. These features will be really useful and when the final release is available you will really find them useful and more powerful than the previous versions. So without wasting time I will proceed to discussing some key features.

  1. Asynchronous pattern Support The .NET Framework 4.5 introduced the Task-Based Asynchronous Pattern that uses the async modifier and the await operator to provide asynchronous programming. This feature is now supported by EF6. So database calls that fetch a large amount of data, made through EF can be processed asynchronously. By using the asynchronous pattern we can avoid blocking the responsiveness of our application.

    Let's have at look some code snippets without and with the asynchronous pattern and how to use this pattern with EF6.

    a. Without Asynchronous Patterns
     
    privatestatic void SaveInput(string question,string answer)
    {
        using (var ctx = new AnswersContext())
        {
            ctx.Questions.Add(new Question()
            {
                Content = question,
                Answers =new List<Answer> { new Answer { Content = answer } }
            });
            ctx.SaveChanges();
        }
    }

    b. With Asynchronous Patterns
    privatestatic void PrintQuestions()
    {
        using (var ctx = new AnswersContext())
        {
            foreach (var q in ctx.Questions)
            {
                Console.WriteLine(q.Content);
                foreach (var a in q.Answers)
                {
                    Console.WriteLine(" -" + a.Content);
                }
            }
        }
    }

    As you can see, I have used async and await, two new keywords. If we are using the await operator then it is necessary to use async with the method signature. Since we are calling the ToListAsync method, as soon as this method is called, the thread won't block until the task finishes.
     
  2. Custom ConventionsWhen we use the code first approach in Entity Framework, classes are mapped with the database using a set of conventions that are defined in EF, such as which property becomes the primary key, which name of in the table maps with an entity name etcetera. We must use some custom code conventions for that. Sometimes these default conventions are not perfect for our model and we must do configuration using Data annotation and other ways.
     
  3. Code First Mapping to Insert/Update/Delete Stored Procedures When we use code first entities, it is easy to select data using Stored Procedures but there was no way to delete, update and insert data using Stored Procedures.

    EF 6 provides this ability to insert, update and delete using a Stored Procedure. So you can do that as in the following:
     
    mBuilder .Entity<Users>() .MapToStoredProcedures(s => {
    s.Update(u => u.HasName("modify_User"));
    s.Delete(d => d.HasName("delete_User"));
    s.Insert(i => i.HasName("insert_User"));
    });
     
  4. Connection ResiliencySince we know that currently most database servers are a cloud, such as an Azure Database. So the chances of connection failures are greater. This could be because of some defensive techniques used by the cloud database because of how the cloud database maintains its consistency, so to maintain that, sometimes it closes the connection explicitly.

    EF 6 provides many ways to retry actions to be performed on the database and to minimize the number of failures and the effect of defensive code. Even users can create their own retry strategies and decide which action should be performed if an exception occurs.
     
  5. Better supports of POCO entitiesNow we can make nesting of entities and complex types inside classes. We can also have Custom Equal and GetHashCode Method implementations.
     
  6. Multiple Context Per DatabaseIn EF 5, when we use Migration or a Code first database created automatically then we can have only one code first model per database. But In EF 6 , we will be able to have multiple code first models per database.
     
  7. Default Isolation levelDefault isolation level has been changed for databases created using code first in EF6. In EF 5 it was Serializable so now it has been changed to READ_COMMITTED_SNAPSHOT. So because of this isolation level the database becomes more scalable and there are very few chances of deadlock.
     
  8. Supports Enum and Spatial data types :EF 6 now provides support of Enum and Spatial Data Types.
     
  9. Now easy to set default schema at one placeEF 6 provides the DbModelBuilder.HasDefaultSchema Code first API that allows configuration of a default database schema for the code fist model in one place. Previously this default schema was hard-coded to dbo and if we needed to change it , we needed to do a lot of work.

Summary

In this article I have discussed some key features that have been introduced in the Beta release of Entity Framework 6 . There are many other features also introduced in EF 6. For more information you can refer to the following Codeplex website. 

Wednesday, August 14, 2013

C# 5.0 New Features


1. Key Features Matrix: Microsoft has published a new version of C# 5.0 beta with CLR version 4.5.




C# 5.0 introduces mainly two key features: Async Programming and Caller Information.


2. Asynchronous functions (Async and Await): Using Async and Await, you can use resources in the .NET Framework, to create an asynchronous method as easily as you create a synchronous method.
Asynchronous methods are the methods that you define using async and await.


3. Caller Information: Caller Information attributes provide the information about the caller to a method. You can obtain the file path of the source code, the line number in the source code, and the member name of the caller. Caller Information helps us in tracing, debugging, and creating diagnostic tools.
CallerFilePathAttribute - Full path of the source file that contains the caller. This is the file path used at compile time.
CallerLineNumberAttribute - Line number in the source file on which the method is called.
CallerMemberNameAttribute - Method or property name of the caller.


4. Windows Runtime Support: C# and .NET now have deep integration with the Windows Runtime. C# project can compiled into a WinMD file and then referenced from a HTML/JavaScript project. WinRT’s flavor of COM uses the same metadata format used by the Common Language Runtime. This information is stored in WINMD files that show the structure, though not the implementation, of all the public classes. Windows Runtime returns an HRESULT instead of throwing an exception. For well-known HRESULT values, the corresponding exception is thrown, otherwise a COMException is used.


5. Compiler APIs: This feature is supposed to come after C# 5.0 – the APIs will expose whatever knowledge the compiler has about the code to the IDE and the developers, through Syntax Tree APIs, Symbol APIs, Binding and Flow analysis APIs and Emit APIs.

References:

Tuesday, August 13, 2013

Introducing the Microsoft “Roslyn” CTP



What is Roslyn?

In the past, our compilers have acted as black boxes – you put source text in and out the other end comes an assembly. All of that rich knowledge and information that the compiler produces is thrown away and unavailable for anyone else to use.
As Soma mentions in his blog, a part of the Visual Studio languages team is working on a project called Roslyn with a goal to rewrite the C# and VB compilers and language services in managed code. With a clean, modern, managed codebase our team can be more productive, innovate faster, and deliver more features sooner and with better quality.
More importantly, we are opening up the C# and Visual Basic compilers and exposing all that rich information and code analysis to be available for your use. We expose a public API surface and provide extension points in the C# and VB language services.
This opens up new opportunities for VS extenders to write powerful refactorings and language analysis tools, as well as allow anyone to incorporate our parsers, semantic engines, code generators and scripting in their own applications.

 Download the October 2011 CTP

The CTP and supporting materials can be downloaded from:
http://msdn.com/roslyn
The main goal of this early preview is to gather feedback on the API design and to introduce the C# Interactive window (also known as REPL, or Read-Eval-Print-Loop).
This first CTP is intended for preview-use only and does not allow redistribution of the Roslyn components or allow use in a production environment.
The CTP installs on Visual Studio 2010 SP1. It also requires the Visual Studio 2010 SP1 SDK.

Getting Started

After the installation succeeds, the best place to start is to open Start Menu -> Microsoft Codename Roslyn CTP -> Getting Started.
To get started, the “Roslyn Project Overview” document gives a look at the compiler API – how to work with syntax and semantics of your program. Several walkthrough documents are also included to provide a deep dive into various aspects of the Roslyn APIs.
The CTP ships with quite a few samples for Visual Studio Extensions, compiler API, code issues, refactorings and so on. Most of the samples are provided for both C# and Visual Basic. You can open the sample source code from the Getting Started page.
We also install several new project templates available in the New Project dialog:

ProjectTemplatesVB

ProjectTemplatesCSharp

These templates will help you to get started on a new Visual Studio extension that uses Roslyn.

Reference Assemblies

References

The Roslyn assemblies are also installed in the GAC. Switch to the Full Profile (instead of the Client Profile) to be able to also reference the Services assemblies (which contain the IDE support).

C# Interactive window

InteractiveWindow

You can invoke the C# Interactive window from View -> Other Windows -> C# Interactive Window. The Interactive window is powered by the new C# language service. The architecture of Roslyn is flexible enough to allow many of the IDE features such as IntelliSense and refactorings to work the same in a normal editor and in the Interactive window.
At this time, the Interactive window is only available for C#. We’re working hard on providing the VB Interactive at a future time.

C# Script File (.csx) Editing Support

The CTP introduces a concept of a C# Script File. You can create a .csx file through File -> New File (or also use any other editor such as notepad):

NewCSharpScriptFile

CSXScriptEditor

You can run scripts using the new rcsi.exe, which installs into %ProgramFiles(x86)%\Microsoft Codename Roslyn CTP\Binaries\rcsi.exe. You can add rcsi.exe to the path and then type rcsi <scriptfilename>.csx.
You can also copy chunks of code from a script file and send them to the C# Interactive Window (using the right-click context menu or a keyboard shortcut).
The editor for the script files is also powered by the new language services. Hence it is important to keep in mind that .csx scripts will only support the part of the language already implemented in the Roslyn compilers. For more details, see the "Introduction to Scripting" walkthrough.

Quick sample of the Roslyn API

Here’s a sample of compiling and executing a small program using the Roslyn API.


using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

...

var text = @"class Calc { public static object Eval() { return 42; } }";
 
var tree = SyntaxTree.ParseCompilationUnit(text);
var compilation = Compilation.Create(
    "calc.dll",
    options: new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary),
    syntaxTrees: new[] { tree },
    references: new[] { new AssemblyFileReference(typeof(object).Assembly.Location) });
 
Assembly compiledAssembly;
using (var stream = new MemoryStream())
{
    EmitResult compileResult = compilation.Emit(stream);
    compiledAssembly = Assembly.Load(stream.GetBuffer());
}
 
Type calc = compiledAssembly.GetType("Calc");
MethodInfo eval = calc.GetMethod("Eval");
string answer = eval.Invoke(null, null).ToString();
 
Assert.AreEqual("42", answer);