I found an article about an interesting new project Microsoft is undertaking beginning with VS2012. The Roslyn Project as it is called will expose the APIs used by Visual Studio to compile code as services for open consumption. This
transition will basically open the door for more openly creating code focused tools and applications. This will undoubtedly lead to new innovation in code
generation, transformation and interaction with the C# and VB
languages.
The Roslyn project will expose the following layers as services: the Compiler APIs, the Services APIs, and the Editor Services APIs. By exposing these APIs, IDE development and IDE focused tools will be more widely developed as well as more functional. Anyone with a good idea will be able to spin up a compiler add-on or IDE. This will allow many small players to hit home runs on pitches Microsoft would never even swing at.
We will have the ability to analyze and transform our syntax automatically as well as customize our IDE to specific standards. I have just begun looking into this, but some of the ideas that come to mind immediately are having the ability to enforce, coach and correct our coding guidelines with things like namespace restrictions on developer and build machines. We would have the ability develop 'standard specific' functionality that mimics other profilers on the market but would be geared to individual team / company standards.
The concept is very interesting and exciting. It is a very good read if you have the time. More information can be found here
Friday, November 9, 2012
Wednesday, October 31, 2012
C# 5: Caller Information
.NET 4.5 has introduced a few new classes that will enable more detailed logging, debugging and tracing through your code. Today, I will focus on the following classes:
1. The CallerMemberNameAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the method or property name which made the current call into this method.
2. The CallerFilePathAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the code file path to the C# source code file that made the current call into this method.
3. The CallerLineNumberAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the code file line number within the C# source code file that made the current call into this method.
Grabbing all of this information will enable you to create very detailed logging and trace statements. This will ultimately aid you in trouble-shooting code issues or errors encountered by users running your application. Below is a usage example of these attributes and the run-time logging potential they make available.
In the output from this application, notice that the calls to MethodB() both form the Main method as well as MethodA() contains the correct information regarding the source object, file and line number.
While possible to rely upon your exception handling plan to provide call stack information, you are also able to build on the base for your own purposes. By accessing these values as well as any local data, variable values and session specific information, you can build and handle messages that present you with all of the information needed to troubleshoot user errors, debug intricate processes or supply more complex audit trail logging within your system.
1. The CallerMemberNameAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the method or property name which made the current call into this method.
2. The CallerFilePathAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the code file path to the C# source code file that made the current call into this method.
3. The CallerLineNumberAttribute class is used by appending it as an optional parameter on a method. When the method is called, it will contain the code file line number within the C# source code file that made the current call into this method.
Grabbing all of this information will enable you to create very detailed logging and trace statements. This will ultimately aid you in trouble-shooting code issues or errors encountered by users running your application. Below is a usage example of these attributes and the run-time logging potential they make available.
namespace CallerInformation { class Program { static void Main(string[] args) { MethodA(); MethodB(); Console.ReadLine(); } static void MethodA([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { InsertLog(memberName, "MethodA", sourceFilePath, sourceLineNumber); MethodB(); } static void MethodB( [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { InsertLog(memberName, "MethodB", sourceFilePath, sourceLineNumber); } static void InsertLog(string methodName, String calledMethodName, String sourceFilePath, Int32 sourceLineNumber) { Console.WriteLine("{0} called {1} from file:'{2}' line: {3}", methodName, calledMethodName, sourceFilePath, sourceLineNumber.ToString()); } } }
In the output from this application, notice that the calls to MethodB() both form the Main method as well as MethodA() contains the correct information regarding the source object, file and line number.
While possible to rely upon your exception handling plan to provide call stack information, you are also able to build on the base for your own purposes. By accessing these values as well as any local data, variable values and session specific information, you can build and handle messages that present you with all of the information needed to troubleshoot user errors, debug intricate processes or supply more complex audit trail logging within your system.
Wednesday, October 24, 2012
.NET 4.5 - Simplified WCF Configuration
A WCF configuration file is basically a markup file used to communicate to the hosting environment how a WCF service is configured and should behave. The configuration files have historically required an exhaustive explanation of each aspect of configuration and behavior. To illustrate this, consider a standard config file. Notice that the file contains a <system.serviceModel> section which contains a <service> element for each service hosted. The <service> element contains a listing of <endpoint> elements that outline the endpoints for each service and a set of service behaviors. The <endpoint>
elements specify the address, binding and contract exposed by the
endpoint, and optional binding and endpoint configuration. The <system.serviceModel> section also contains a <behaviors> element that allows you to specify service or endpoint behaviors. The following example shows the <system.serviceModel> section of a configuration file.
To take this further, if you have no need to specify endpoints, modify behaviors or customize the binding, The config file is not needed at all. For example, if a service implements x contracts and the host enables both HTTP and TCP, the service host creates x*2 default endpoints as a straight contract:endpoint. To create default endpoints the service host must know what bindings to use. These settings are specified in a <protocolMappings> section within the <system.serviceModel> section. The <protocolMappings> section contains a list of transport protocol schemes mapped to binding types. The service host uses the base addresses passed to it to determine which binding to use. The following example uses the <protocolMappings> element.
Service behaviors are configured for the default endpoints by using anonymous <behavior> sections within <serviceBehaviors> sections. Any unnamed <behavior> elements within <serviceBehaviors> are used to configure service behaviors. For example, the following configuration file enables service metadata publishing for all services within the host.
Here is the configuration file from the top of this post modified to use the simplified model.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true">
<serviceDebug includeExceptionDetailInFaults="false">
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name=MyBindingConfig"
maxBufferSize="100"
maxReceiveBufferSize="100" />
</basicHttpBinding>
</bindings> <services>
<service behaviorConfiguration="MyServiceBehavior"
name="MyService">
<endpoint address=""
binding="basicHttpBinding"
contract="ICalculator"
bindingConfiguration="MyBindingConfig" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
In 4.5, the configuration has been simplified by no longer requiring a <service> element. When the <service> section is absent, or a <service>
section defines no endpoints (and your service does not programmatically define any
endpoints), default endpoints with default configurations are automatically added to each service. These defaults are added for each service base address and for each contract
implemented by the service. In the default endpoints, the endpoint
address relates the base address, the binding is determined by
the base address scheme and the contract is the one implemented by the service.To take this further, if you have no need to specify endpoints, modify behaviors or customize the binding, The config file is not needed at all. For example, if a service implements x contracts and the host enables both HTTP and TCP, the service host creates x*2 default endpoints as a straight contract:endpoint. To create default endpoints the service host must know what bindings to use. These settings are specified in a <protocolMappings> section within the <system.serviceModel> section. The <protocolMappings> section contains a list of transport protocol schemes mapped to binding types. The service host uses the base addresses passed to it to determine which binding to use. The following example uses the <protocolMappings> element.
<protocolMapping>
<add scheme="http" binding="basicHttpBinding" bindingConfiguration="MyBindingConfiguration"/>
<add scheme="net.tcp" binding="netTcpBinding"/>
<add scheme="net.pipe" binding="netNamedPipeBinding"/>
<add scheme="net.msmq" binding="netMSMQBinding"/>
</protocolMapping>
Service behaviors are configured for the default endpoints by using anonymous <behavior> sections within <serviceBehaviors> sections. Any unnamed <behavior> elements within <serviceBehaviors> are used to configure service behaviors. For example, the following configuration file enables service metadata publishing for all services within the host.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Here is the configuration file from the top of this post modified to use the simplified model.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="100"
maxReceiveBufferSize="100" />
</basicHttpBinding>
</bindings>
<protocolMapping>
<add scheme="http" binding="basicHttpBinding" />
</protocolMapping>
</system.serviceModel>
Labels:
.NET 4.5,
Architecture,
WCF
Thursday, October 11, 2012
Async in C#
C# 5 adds some powerful asynchronous functionality as an expansion to the Task and Task<TResult> aspects of .NET 4. The old model seemed to focus on the Asynchronous Pattern and the Event-based Asynchronous Pattern but the framework itself didn't bring much to the table for allowing developers with varied levels of knowledge access to an easily adopted methodology. With the roll out of C# 5,
.NET has provided us with a wrapped API for all asynchronous programming via library based method calls. This is the
first building block of the new features for asynchronous programming and it has been said that going forward, all asynchronous operations will work via a method that returns Task or Task<TResult>.
The await keyword expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off. An await expression can occur only in the body of an immediately enclosing method, lambda expression, or anonymous method that is marked by an async modifier. The term await serves as a keyword only in that context. Elsewhere, it is interpreted as an identifier. Within the method, lambda expression, or anonymous method, an await expression cannot occur in the body of a synchronous function, in a query expression, in the catch or finally block of an exception handling statement, in the block of a lock statement, or in an unsafe context.
Here is a simple example, suppose we want to download a webpage as a string so we can check to see if it supports XHTML 1.0,. There is a new method added to WebClient: Task<string> WebClient.DownloadStringTaskAsync(Uri). Since this returns a Task<string> we can use it within an asynchronous function. We could do this entire process with jsut a few lines of code.
By adding the async contextual keyword to the method definition, we are able to use the await keyword on our WebClient.DownloadStringTaskAsync method call. This means that when the user clicks the new method (Task<string> WebClient.DownloadStringTaskAsync(string)) is called. By adding the await keyword, the runtime will call this method that returns Task<string> and execution will return to the UI. This means that our UI is not blocked while the webpage is downloaded. Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously. When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task<string> returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable, thus allowing us to report it in the text box.
Notice how the code is obviously shorter and simpler because the initial synchronization context is used to continue the execution of this function. Meaning, we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread, it is just picked up via the framework. This sort of abstraction of the difficulty is a strong step toward enabling a wide range of developers the ability to leverage asynchronous programming. The will ultimately, as always, result in better software for the users.
A key change for this version is the addition of the async keyword. This contextual keyword enables an easy declaration of an asynchronous function. Note that all asynchronous functions must return either void, a Task, or a Task<T>. When declaring a function with async, it is also required that there must be at least one await expression inside the function itself.
The await keyword expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off. An await expression can occur only in the body of an immediately enclosing method, lambda expression, or anonymous method that is marked by an async modifier. The term await serves as a keyword only in that context. Elsewhere, it is interpreted as an identifier. Within the method, lambda expression, or anonymous method, an await expression cannot occur in the body of a synchronous function, in a query expression, in the catch or finally block of an exception handling statement, in the block of a lock statement, or in an unsafe context.
// Keyword await used with a method that returns a Task<result>. TResult result = await AsyncMethodThatReturnsTaskTResult(); // Keyword await used with a method that returns a Task. await AsyncMethodThatReturnsTask();
Here is a simple example, suppose we want to download a webpage as a string so we can check to see if it supports XHTML 1.0,. There is a new method added to WebClient: Task<string> WebClient.DownloadStringTaskAsync(Uri). Since this returns a Task<string> we can use it within an asynchronous function. We could do this entire process with jsut a few lines of code.
private void button1_Click(object sender, RoutedEventArgs e) { String url = "http://devstorm.blogspot.com"; String content = await new WebClient().DownloadStringTaskAsync(url); textBox1.Text = String.Format("Page {0} supports XHTML 1.0: {1}", url, content.Contains("XHTML 1.0")); }
By adding the async contextual keyword to the method definition, we are able to use the await keyword on our WebClient.DownloadStringTaskAsync method call. This means that when the user clicks the new method (Task<string> WebClient.DownloadStringTaskAsync(string)) is called. By adding the await keyword, the runtime will call this method that returns Task<string> and execution will return to the UI. This means that our UI is not blocked while the webpage is downloaded. Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously. When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task<string> returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable, thus allowing us to report it in the text box.
Notice how the code is obviously shorter and simpler because the initial synchronization context is used to continue the execution of this function. Meaning, we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread, it is just picked up via the framework. This sort of abstraction of the difficulty is a strong step toward enabling a wide range of developers the ability to leverage asynchronous programming. The will ultimately, as always, result in better software for the users.
Labels:
.NET,
.NET 4.5,
Async,
Syntax,
Visual Studio
Thursday, September 13, 2012
Windows Azure Mobile Services
On August 28th, Microsoft announced an addition to the Azure platform, Windows Azure Mobile Services. The capabilities seem very powerful and target easy development and deployment of mobile applications with a cloud-based backend service hosted on Azure. While this is targeted at Windows 8 applications exclusively, it appears to scale very well into using a mobile-first approach to all of your Windows 8 applications, desktop or mobile. The backend framework allows for direct access to SQLAzure data via the mobile service. In fact, when you create a Windows Azure Mobile Service, it is automatically associated with a SQL Database inside Windows Azure. This all happens without creating any custom server code. The management portal includes the ability to create new tables, control access, view data and other administrative items. By leveraging this infrastructure, developers can connect directly to their cloud-based data very easily without having any insight into the server side code. The data can be automatically accessed and stored via a secure RESTful interface. This allows a client side developer to quickly and easily connect any Windows 8 application to the new mobile platform and its data.
Here is a code snippet showing the mechanism for directly consuming mobile cloud based data. The native interface supports LINQ based queries of POCO objects (strongly typed) via the RESTful interface. This code will populate a presentation layer asynchronously without creating ANY server side code to handle it.
At this point, you have built a data driven SOA that is able to be consumed directly by any windows 8 presentation layer.
Other items that are directly supported via the Azure Mobile Services are: push notifications, user authentication and paged queries -- all with the native services provided. It seems to be quite easy to directly connect your Windows 8 application to the mobile services in Azure. The upside being that it makes developing a Windows 8 client based on a cloud solution very quick and easy. The unanswered question is still how easily you can use this to consume data in cloud style without using a Windows 8 application. It appears that it would be possible to directly hit this service from any application able to read JSON from a REST service, but all of the supporting documentation is focused on a Windows 8 client. Either way, this is an exciting addition that should be investigated by those of us using Azure.
Here is a code snippet showing the mechanism for directly consuming mobile cloud based data. The native interface supports LINQ based queries of POCO objects (strongly typed) via the RESTful interface. This code will populate a presentation layer asynchronously without creating ANY server side code to handle it.
private void RefreshTodoItems() { items = App.MobileService.GetTable< TodoItem >() .Where(todoItem => todoItem.Complete == false) .ToCollectionView(); ListItems.ItemsSource = items; }
At this point, you have built a data driven SOA that is able to be consumed directly by any windows 8 presentation layer.
Other items that are directly supported via the Azure Mobile Services are: push notifications, user authentication and paged queries -- all with the native services provided. It seems to be quite easy to directly connect your Windows 8 application to the mobile services in Azure. The upside being that it makes developing a Windows 8 client based on a cloud solution very quick and easy. The unanswered question is still how easily you can use this to consume data in cloud style without using a Windows 8 application. It appears that it would be possible to directly hit this service from any application able to read JSON from a REST service, but all of the supporting documentation is focused on a Windows 8 client. Either way, this is an exciting addition that should be investigated by those of us using Azure.
Friday, August 24, 2012
Web API in ASP.NET MVC4
In the new version of ASP.NET, Microsoft has introduced some framework extension that has exciting possibilities. Google, FaceBook, and the like have been exposing web API in some fashion for a while now, but it has always seemed limited to certain platforms. It appears at a glance that we will be able to provide the same functionality with native ASP.NET and MVC4 applications. This basically allows you to expose web service over straight up HTTP instead of traditional service hosting/messaging.
The gain is that you can create web-based integration points by leveraging a native ASP.NET architecture at the same time. This allows you to provide a user-story-based integration routine (ala FaceBook, Twitter) as a wrapper of /or in addition to any service layer integrations that may be exposed.
Here are some points I read from Scott Gu's Blog on the topic. He outlines the highlights and additions to the framework. I think the real excitement is in the realization of the walls that are coming down on platform dependence and ease of developing rich client experiences with web services in a Windows environment.
Our new ASP.NET Web API support enables you to easily create powerful Web APIs that can be accessed from a broad range of clients (ranging from browsers using JavaScript, to native apps on any mobile/client platform). It provides the following support:
The gain is that you can create web-based integration points by leveraging a native ASP.NET architecture at the same time. This allows you to provide a user-story-based integration routine (ala FaceBook, Twitter) as a wrapper of /or in addition to any service layer integrations that may be exposed.
Here are some points I read from Scott Gu's Blog on the topic. He outlines the highlights and additions to the framework. I think the real excitement is in the realization of the walls that are coming down on platform dependence and ease of developing rich client experiences with web services in a Windows environment.
Our new ASP.NET Web API support enables you to easily create powerful Web APIs that can be accessed from a broad range of clients (ranging from browsers using JavaScript, to native apps on any mobile/client platform). It provides the following support:
- Modern HTTP programming model: Directly access and manipulate HTTP requests and responses in your Web APIs using a clean, strongly typed HTTP object model. In addition to supporting this HTTP programming model on the server, we also support the same programming model on the client with the new HttpClient API that can be used to call Web APIs from any .NET application.
- Content negotiation: Web API has built-in support for content negotiation – which enables the client and server to work together to determine the right format for data being returned from an API. We provide default support for JSON, XML and Form URL-encoded formats, and you can extend this support by adding your own formatters, or even replace the default content negotiation strategy with one of your own.
- Query composition: Web API enables you to easily support querying via the OData URL conventions. When you return a type of IQueryable<T> from your Web API, the framework will automatically provide OData query support over it – making it easy to implement paging and sorting.
- Model binding and validation: Model binders provide an easy way to extract data from various parts of an HTTP request and convert those message parts into .NET objects which can be used by Web API actions. Web API supports the same model binding and validation infrastructure that ASP.NET MVC supports today.
- Routes: Web APIs support the full set of routing capabilities supported within ASP.NET MVC and ASP.NET today, including route parameters and constraints. Web API also provides smart conventions by default, enabling you to easily create classes that implement Web APIs without having to apply attributes to your classes or methods. Web API configuration is accomplished solely through code – leaving your config files clean.
- Filters: Web APIs enables you to easily use and create filters (for example: [authorization]) that enable you to encapsulate and apply cross-cutting behavior.
- Improved testability: Rather than setting HTTP details in static context objects, Web API actions can now work with instances of HttpRequestMessage and HttpResponseMessage – two new HTTP objects that (among other things) make testing much easier. As an example, you can unit test your Web APIs without having to use a Mocking framework.
- IoC Support: Web API supports the service locator pattern implemented by ASP.NET MVC, which enables you to resolve dependencies for many different facilities. You can easily integrate this with an IoC container or dependency injection framework to enable clean resolution of dependencies.
- Flexible Hosting: Web APIs can be hosted within any type of ASP.NET application (including both ASP.NET MVC and ASP.NET Web Forms based applications). We’ve also designed the Web API support so that you can also optionally host/expose them within your own process if you don’t want to use ASP.NET/IIS to do so. This gives you maximum flexibility in how and where you use it.
Labels:
.NET,
.NET 4.5,
asp.net,
Services,
Visual Studio
Subscribe to:
Posts (Atom)