T4: Text Template Transformation Toolkit

•2 Luglio 2009 • Lascia un Commento

T4: Text Template Transformation Toolkit

Text Template Transformation Toolkit (T4) is a template-based code generation engine. It is included with Visual Studio 2008 and available as a download for Visual Studio 2005 in DSL and GAT toolkits. You can use T4 templates to generate Visual Basic, C#, T-SQL, XML or any other text files.

Syntax

T4 templates have ASP.NET-like syntax and consist of processing directives, text blocks and code blocks.

<#@ template language=C##>
Hello
<# Write(”World!”) #>

Processing directives provide template compilation and processing options. In the example above, <#@ template #> directive specifies that code blocks of this template are written in C#.

Text blocks are copied to the output “as is”. In the example above, Hello is a text block.

Code blocks contain Visual Basic or C# code that can manipulate text blocks or generate template output directly. In the example above, the code block calls Write method which writes “World!” to the output file. Code blocks can use any available .NET APIs. For example, a template can use SMO to generate CRUD stored procedures for a table in a SQL Server database.

How it works

T4 engine performs two steps to generate output from a template.

T4 Template Transformation Process

During the first step, T4 engine “compiles” the template: it parses the processing instructions, text and code blocks, generates a concrete TextTransformation class, and compiles it into a .NET assembly. During the second step, T4 engine creates an instance of the GeneratedTextTransformation class, calls its TransformText method and saves the string it returns to the output file.

Tutorial

This series of articles introduces code generation with C# and Text Templates in Visual Studio; explains how to create reusable templates and combine them in complex code generators.

Tools

Here are the tools you will be using when working with T4 text templates.

Visual Studio Custom Tool

T4 engine is integrated as a custom tool into Visual Studio 2008. When you add a text file with .tt extension to your project, Visual Studio assigns TextTemplatingFileGenerator as a custom tool and automatically generates output file from the template. This is similar to how Visual Studio generates strongly-typed datasets from .xsd files.

Command Line Utility

T4 also includes a command line utility, TextTransform.exe, which you can use to process templates outside of Visual Studio (similar to xsd.exe for strongly-typed datasets).

Editor

Text editing and debugging support for T4 templates is currently rather limited. I use T4 Editor from Tangible Engineering, which extends Visual Studio to provide IntelliSense and syntax highlighting for .tt files. Another option is the T4 Editor from Clarius Consulting, however functionality of its free edition is more limited.

Debugger

Debugging requires placing calls to Debugger.Break method in code blocks to set breakpoints. Check out this post by Gareth Jones for more details. Hopefully, future versions of Visual Studio will provide a better debugging experience for T4 templates.

Visual Studio Templates

Unfortunately, Visual Studio itself does not provide a specific item for T4 templates in the Add New Project Item dialog. This makes it difficult for developers to discover this code generation tool even exists. You can download T4 Toolbox from CodePlex, which adds several items to the Code Generation folder of the Add New Project Item dialog.

Details

Here are some articles that will help you understand how template transformation works by showing how specific blocks and processing directives are “compiled”. Examples in these articles include the original template text, compiled template code and output file it produces.

The following articles cover advanced topics of code generation with T4.

Videos

Examples

You can find some T4 examples on MSDN. You will notice that it has very limited information about use of T4 outside of DSL and Guidance packages. Here are some examples of standalone templates you can start using without having to build your own Software Factory.

Alternatives

As a code generation tool, T4’s purpose is similar to that of CodeDom (Code Document Object Model). CodeDom provides an API you can use to generate code in any .NET language from the same program. CodeDom API is low-level, complex, and has a steep learning curve. It is typically used for code generation in frameworks that need to to support multiple .NET languages. For example, T4 engine itself uses CodeDom; you have to use CodeDom to extend T4 with custom directives. Compared to CodeDom, T4 is easier to learn and use. However, T4 templates are language-specific. In other words, if you want to generate the same code code in C# and Visual Basic, you will need to create 2 separate T4 templates. Unlike CodeDom, T4 can generate any text files (XML, HTML, etc) and not just .cs or .vb files. This makes T4 a better fit for code generation in application development then CodeDom.

T4 engine is similar to CodeSmith, which has been around a lot longer, provides an excellent set of ready-to-use templates, better template editing and debugging experience for a reasonable price. Unlike CodeSmith, which was was designed to be a template-based code generation tool, T4 engine was designed as a supporting tool for Software Factories. T4 does not offer any reusable templates out of the box and provides rather limited documentation focused on use of T4 templates in DSL and Guidance packages. However, with inclusion in Visual Studio 2008, I think we will see more and more teams adopting T4 engine as a free alternative to CodeSmith.

T4 engine is also similar to NVelocity, an open-source template transformation engine. NVelocity was ported from Java and intends to stay as close to Jakarta Velocity as possible. This makes its template syntax different from ASP.NET and I would think that more people will prefer T4. I don’t know if a significant number of NVelocity templates are available at this time.

T4 Editor plus UML-Style modeling tools for Visual Studio 2008/2010

•2 Luglio 2009 • Lascia un Commento

T4 Editor plus UML-Style modeling tools
for Visual Studio 2008/2010

With tangible T4 Editor you can author your own Code Generator via Text-Templates (TT-Files) with Intelli-Sense & Syntax-Highlighting. T4 is a Microsoft Language for writing Code Generators which is similar to ASP.NET and is used by the Microsoft internally to build software and new features for .NET 4.0. The T4 Code Generation Engine is already built into Visual Studio – so the only thing that was missing was a great T4 Editor and some free UML-style modeling tools – so we shipped it.
Now it is up to you to accelerate your projects and start saving your company money by adopting T4 today and generate the code you need directly from diagrams, database schemas or xml files.


(Screenshot of features available in FREE EDITION)

In addition, with the free build-in tangible modeling tools you can directly create Software Diagrams like Use Case Diagrams, Component Diagrams, State Charts, Class Diagrams, Activity Diagrams and Persistent Object Models from within Visual Studio. (see below)

T4 Editor Features – T4 Code Generation simplified

The T4 Editor for Syntax Highlighting and Intelli-Sense allows you to author your own code generators in Visual Studio that read from diagrams, xml or any other data source.

  • T4 Syntax Highlighting for C#, VB.NET, Java, PHP, SQL, MSIL, Python, Batch Files, PASCAL, PowerShell, IL, JSCRIPT, VBSCRIPT, CSS in output text code and T4 Code Sections in C# or VB.NET

  • T4 Intelli-Sense, Intelli-Prompt and Statement Completition for T4 Code Sections. Intelli-Sense will look at all assemblies and namespaces indicated by the import and include pragma. *Limited support for namespaces in the FREE EDITION.

  • Syntax Error Reporting in ErrorList and via Text-Highlighting for errors inside the T4 text template

  • Template Gallery – Access & Share T4 Templates in our Gallery or in your Workgroup

  • Support for #Include Directive, this makes types visible to importing template’s Intelli-Sense

  • Support T4 Toolbox which includes XSD Directive, Multiple output files and more.

  • Drag and Drop XML Files and Diagrams onto T4 Editor get T4 Code to generate from them.


A Tour around T4 Editor

Double-click video for fullscreen.

Supported diagram types

With tangible modeling tools you can directly create Use Case Diagrams, Component Diagrams, State Charts, Class Diagrams, Activity Diagrams and Persistent Object Models. Which can also be used for code-generation by a T4 Template.


FREE EDITION Download

FREE EDITION DOWNLOAD is here.

Ongoing feedback-driven development

tangible modeling tools plus T4 Editor is an initiative we take to better support the .NET Community with precise modeling tools and code generation. It uses the same components we have built into our high-end code generator tangible architect. We are in the process of collecting your feature requests. Please provide us your feedback at info@tangible.de.

FAQs

Q: Will tangible modeling tools also be free in future? A: Yes, we stick to offering a FREE SKU. But we also offer enhanced SKUs with additional functionality.

Q: Which version of Visual Studio is supported? A:There are three Builds. For VS2005 we support Diagrams only. For VS 2008 we also included tangible’s new T4 Editor. Here is the tangible T4 Editor for Visual Studio 2010 (T4 Editor only as Beta1 includes MS Modelling Tools)

Refactorings in Alphabetical Order

•2 Luglio 2009 • Comments Off

From Martin Fowler.

Refactorings in Alphabetical Order

This is a simple list of refactorings both from the original book and some later sources. Sadly I haven’t had enough time and energy to keep this material up to date. Refactorings marked with with have some extra material to what’s in the Refactoring book. Refactorings marked with are in addition to those in the refactoring book. Refactorings with Link Only are references to refactorings described elsewhere.

| Russian | German |

Israel Kamakawiwo

•5 Giugno 2009 • Lascia un Commento

Somewhere Over the Rainbow by Israel Kamakawiwo’ole LYRICS

Troppo bella.

Framework Design Guidelines

•4 Giugno 2009 • Lascia un Commento

Dal blog di Brad Abrams linee guida per lo sviluppo con il framework Microsoft.

Web Deployment: Web.Config Transformation

•4 Giugno 2009 • Lascia un Commento

We have earlier discussed about Web Deployment and Web Packaging quite a bit, today I wanted to dive into web.config transformation. If you would like to check out the other topics please read through the earlier blog posts below:

 

 

 

Usually web applications go through a chain of server deployments before being finally being deployed to production environment. Some of these environments can be Developer box (Debug), QA Server, Staging/Pre-Production, Production (Release). While transitioning between these environments various settings of the web application residing in web.config file change, some of these settings can be items like application settings, connection strings, debug flags, web services end points etc.

 

 

 

VS10’s new web.config transformation model allows you to modify your web.config file in an automated fashion during deployment of your applications to various server environments. To help command line based deployments, Web.Config transformation is implemented as an MSBuild task behind the scene hence you can simply call it even outside of deployment realm.

 

 

 

I will try to go through below steps to explain web.config transformation in detail

 

 

 

  1. Creating a “Staging” Configuration on your developer box 
  2. Adding a “Staging” Web.Config Transform file to your project 
  3. Writing simple transforms to change developer box connection string settings into “Staging” environment settings 
  4. Generating a new transformed web.config file for “Staging” environment from command line 
  5. Generating a new transformed web.config file for “Staging” environment from VS UI 
  6. Understanding various available web.config Transforms and Locators 
  7. Using Web.config transformation toolset for config files in sub-folders within the project 

Step 1: Creating a “Staging” Configuration on your developer box

 

 

 

 

Debug and Release build configurations are available by default within Visual Studio but if you would like to add more build configurations (for various server environments like “Dev”, “QA”, “Staging”, “Production” etc then you can do so by going to the Project menu Build –> Configuration Manager… Learn more about creating build configurations.

 

 

 

Step 2: Adding a “Staging” Web.Config Transform file to your project

 

 

 

 

One of the goals while designing web.config transformation was to make sure that the original runtime web.config file does not need to be modified to ensure that there would be no performance impacts and also to make sure that the design time syntax is not mixed with runtime syntax. To support this goal the concept of Configuration specific web.config files was introduced.

 

 

 

These web.config files follow a naming convention of web.configuration.config. For example the web.config files for various Visual Studio + Custom configurations will look as below:

 

 

 

 

 

 

Any new Web Application Project (WAP) created in VS10 will by default have Web.Debug.config and Web.Release.config files added to the project. If you add new configurations (e.g. “Staging”) or if you upgrade pre-VS10 projects to VS10 then you will have to issue a command to VS to generate the Configuration specific Transform files as needed.

 

 

 

To add configuration specific transform file (e.g. Web.Staging.Config) you can right click the original web.config file and click the context menu command “Add Config Transforms” as shown below:

 

 

 

On clicking the “Add Config Transform” command VS10 will detect the configurations that do not have a transform associated with them and will automatically create the missing transform files. It will not overwrite an existing transform file. If you do not want a particular configuration transform file then you can feel free to delete it off.

 

 

 

Note: In case of VB Web Application Projects the web.configuration.config transform files will not be visible till you enable the hidden file views as shown below:

 

 

 

The transform files are design time files only and will not be deployed or packaged by VS10. If you are going to xCopy deploy your web application it is advised that you should explicitly leave out these files from deployment just like you do with project (.csproj/.vbproj) or user (.user) files…

 

 

 

Note: These transform files should not be harmful even if deployed as runtime does not use them in any fashion and additionally ASP.NET makes sure that .config files are not browsable in any way.

 

 

 

Step 3: Writing simple transforms to change developer box connection string settings into “Staging” environment settings

 

 

 

 

Web.Config Transformation Engine is a simple XML Transformation Engine which takes a source file (your project’s original web.config file) and a transform file (e.g. web.staging.config) and produces an output file (web.config ready for staging environment).

 

 

 

The Transform file (e.g. web.staging.config ) needs to have XML Document Transform namespace registered at the root node as shown below:

 

 

 

<?xml version=”1.0″?>
<configuration xmlns:xdt=”http://schemas.microsoft.com/XML-Document-Transform”>
</configuration>

 

 

 

Note: The transform web.config file needs to be a well formed XML.

 

 

 

Inside the XML-Document-Transform namespace two new attributes are defined. These attributes are important to understand as they drive the XML Transformation Engine.

 

 

 

Transform – This attribute inside the Web.Staging.config informs the Transformation engine the way to modify web.config file for specific configuration (i.e. staging). Some examples of what Transforms can do are:

 

 

 

  • Replacing a node 
  • Inserting a node 
  • Delete a node 
  • Removing Attributes 
  • Setting Attributes 

Locator – This attribute inside the web.staging.config helps the Transformation engine to exactly pin-point the web.config node that the transform from web.staging.config should be applied to. Some examples of what Locators can do are:

 

 

 

  • Match on value of a node’s attribute 
  • Exact XPath of where to find a node 
  • A condition match to find a node 

Based on the above basic understanding let us try to transform connection string from original web.config file to match Staging environment’s connection string

 

 

 

Let us examine the original web.config file and identify the items to replace… Let’s assume that the original Web Config file’s connection string section looks as below:

 

 

 

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
  <connectionStrings>
    <add name=”personalDB”
     connectionString=”Server=DevBox; Database=personal; User; password=P@ssw0rd” providerName=”System.Data.SqlClient” />
    <add name=”professionalDB”
     connectionString=”Server=DevBox; Database=professional; User; password=P@ssw0rd” providerName=”System.Data.SqlClient” />
</connectionStrings>
….
….
</configuration>

 

 

 
NOTE: It is not advisable to keep connection string unencrypted in the web.config file, my example is just for demonstration purposes.

 

 

 

Let us assume that we would like to make following changes to web.config file when moving to staging environment

 

 

 

  • For “personalDB” we would like to change the connectionString to reflect Server=StagingBox, UserId=admin, passoword=StagingPersonalPassword” 
  • For “professionalDB” we would like to change the connectionString to reflect Server=StagingBox, UserId=professional, passoword=StagingProfessionalPassword” 

To make the above change happen we will have to open web.Staging.Config file and write the below piece of code

 

 

 

<?xml version=”1.0″?>
<configuration xmlns:xdt=”http://schemas.microsoft.com/XML-Document-Transform”>
     <connectionStrings>
        <add name=”personalDB”
          connectionString=”Server=StagingBox; Database=personal; User Id=admin; password=StagingPersonalPassword”
          providerName=”System.Data.SqlClient” xdt:Transform=”Replace” xdt:Locator=”Match(name)” />
        <add name=”professionalDB”
         connectionString=”Server=StagingBox; Database=professional; User Id=professional; password=StagingProfessionalPassword”
         providerName=”System.Data.SqlClient” xdt:Transform=”Replace” xdt:Locator=”Match(name)”/>
       </connectionStrings>
</configuration>

 

 

 

The above syntax in web.staging.config has Transform and Locator attributes from the xdt namespace. If we analyze the connection string node syntax we can notice that the Transform used here is “Replace” which is instructing the Transformation Engine to Replace the entire node

 

 

 

Further if we notice the Locator used here is “Match” which is informing Transformation engine that among all the “configuration/connectionStrings/add” nodes that are found, pick up the node whose name attribute matches with the name attribute of <add> node in web.Staging.config.

 

 

 

Also if you notice web.Staging.config does not contain anything else but the connectionStrings section (i.e. it does not have <system.web> and various other sections that web.config file usually has, this is because of the fact that the Transformation Engine does not require a complete web.config file in web.staging.config. It does the merging for you thus saving you duplication of all the rest of the sections in web.config file.

 

 

 

Simplest Approach: If you do not mind replicating the entire web.config file in web.staging.config then you can certainly do so by copying the entire web.config content into web.staging.config and change the relevant nodes inside web.staging.config. In such a situation you will just have to put xdt:Transform=”Replace” attribute on the topmost node (i.e. configuration) of web.staging.config. You will not need xdt:Locator attribute at all as you are replacing your entire web.config file with web.staging.config without Matching anything.

 

 

 

So far we have seen one Transform (i.e. Replace) and one Locator (i.e. Match), we will see various other Transforms and Locators further in the post but first let us understand how we can produce the Transformed web.config file for the Staging environment after using original web.config and web.staging.config.

 

 

 

Step 4: Generating a new transformed web.config file for “Staging” environment from command line

 

 

 

 

Open Visual Studio Command prompt by going to Start –> Program Files –> Visual Studio v10.0 –> Visual Studio tools –> Visual Studio 10.0 Command Prompt

 

 

 

Type “MSBuild “Path to Application project file (.csproj/.vbproj) ” /t:TransformWebConfig /p:Configuration=Staging” and hit enter as shown below:

 

 

 

Once the transformation is successful the web.config for the “Staging” configuration will be stored under obj –>Staging folder under your project root (In solution explorer you can access this folder by first un-hiding the hidden files) :

 

 

 

  • In the solution explorer click the button to show hidden files
  • Open the Obj folder 
  • Navigate to your Active configuration (in our current case it is “Staging”) 
  • You can find the transformed web.config there 

You can now verify that the new staging web.config file generated has the changed connection string section.

 

 

 

Step 5: Generating a new transformed web.config file for “Staging” environment from VS UI

 

 

 

 

Right Click on your project and click Package –> Create Package

 

 

 

The Create Package step already does web.config transformation as one of its intermediate steps before creating a package and hence you should be able to find the transformed web.config file in the same place as described in Step 4

 

 

 

Step 6: Understanding various available web.config Transforms and Locators

 

 

 

 

xdt:Locators

 

 

 

 

The inbuilt xdt:Locators are discussed below.

 

 

 

  • Match – In the provided syntax sample below the Replace transform will occur only when the name Northwind matches in the list of connection strings in the source web.config.Do note that Match Locator can take multiple attributeNames as parameters e.g. Match(name, providerName) ] 

<connectionStrings>
     <add name=”Northwind” connectionString=”connectionString goes    here” providerName=”System.Data.SqlClient” xdt:Transform=”Replace” xdt:Locator=”Match(name)” />
</connectionStrings>

 

 

 

  • Condition – Condition Locator will create an XPath predicate which will be appended to current element’s XPath. The resultant XPath generated in the below example is “/configuration/connectionStrings/add[@name='Northwind or @providerName=’ System.Data.SqlClient’ ]”

 

 

 

This XPath is then used to search for the correct node in the source web.config file

 

 

 

<connectionStrings>
      <add name=”Northwind” connectionString=”connectionString goes here” providerName=”System.Data.SqlClient” xdt:Transform=”Replace” xdt:Locator=”Condition(@name=’Northwind or @providerName=’System.Data.SqlClient’)” />
</connectionStrings>

 

 

 

  • XPath- This Locator will support complicated XPath expressions to identify the source web.config nodes. In the syntax example we can see that the XPath provided will allow user to replace system.web section no matter where it is located inside the web.config (i.e. all the system.web sections under any location tag will be removed.)

 

 

 

<location path=”c:\MySite\Admin” >
    <system.web xdt:Transform=”RemoveAll” xdt:Locator=”XPath(//system.web)”>
    …
    </system.web>
</location>

 

 

 

xdt:Transform

 

 

 

 

  • Replace – Completely replaces the first matching element along with all of its children from the destination web.config (e.g. staging environment’s web.config file). Do note that transforms do not modify your source web.config file.
    <assemblies xdt:Transform=”Replace”>
        <add assembly=”System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089″ />
    </assemblies> 
  • Remove – Removes the first matching element along with all of its children
    <assemblies xdt:Transform=”Remove”></assemblies>

 

 

 

  • RemoveAll – Removes all the matching elements from the destination’s web.config (e.g. staging environment’s web.config file).

 

 

 

<connectionStrings>
    <add xdt:Transform=”RemoveAll”/>
</connectionStrings>

 

 

 

 

  • Insert – Inserts the element defined in web.staging.config at the bottom of the list of all the siblings in the destination web.config (e.g. staging environment’s web.config file).

 

 

 

<authorization>
     <deny users=”*” xdt:Transform=”Insert”/>
</authorization>

 

 

 

  • SetAttributes – Takes the value of the specified attributes from the web.staging.config and sets the attributes of the matching element in the destination web.config. This Transform takes a comma separated list of attributes which need to be set. If no attributes are given to SetAttributes transform then it assumes that you would like to Set all the attributes present on the corresponding node in web.staging.config
    <compilation batch=”false”xdt:Transform=”SetAttributes(batch)”>

   …

   </compilation>

 

 

 

  • RemoveAttributes – Removes the specified attributes from the destination web.config (i.e. staging environment’s web.config file). The syntax example shows how multiple attributes can be removed.

 

 

 

<compilation xdt:Transform=”RemoveAttributes(debug,batch)”>
</compilation>

 

 

 

  • InsertAfter (XPath) - Inserts the element defined in the web.staging.config exactly after the element defined by the specified XPath passed to “InsertAfter()” transform. In the syntax example the element <deny users=”Vishal” />will be exactly inserted after the element <allow roles=”Admins” /> in the destinationXML. 

<authorization>
     <deny users=”Vishal” xdt:Transform=”InsertAfter(/configuration/system.web/authorization/allow[@roles='Admins'])” />

</authorization>

 

 

 

  • InsertBefore (XPath) – Inserts the element defined in the web.staging.config exactly before the element defined by the specified XPath passed to “InsertBefore()” transform. In the syntax example the element <allow roles=”Admins” />will be exactly inserted before the element <deny users=”*” />in the destinationXML. 

<authorization>
      <allow roles=” Admins” xdt:Transform=”InsertBefore(/configuration/system.web/authorization/ deny[@users='*'])” />
</authorization>

 

 

 

Some advanced points to note:

 

 

 

  • If the Transformation Engine does not find a xdt:Transform attribute specified on a node in web.staging.config file then that node is ignored for Transformation and the Tranformation engine moves ahead traversing the rest of the web.staging.config. 
  • A xdt:Transform attribute on a parent can very easily impact child elements even if there is no Transform specified for child e.g. If xdt:Transform=”Replace” is put on <system.web> then everything underneath <system.web> node will be replaced with the content from web.staging.config 
  • It is completely valid to place xdt:Locators attributes on arbitrary nodes inside web.staging.config just for filtering purposes. xdt:Locator does not need to be accompanied with xdt:Transform attribute. (great example here is <location> tag which might just be used for filtering… The example code here would be: 

<location path=”c:\MySite\Admin” xdt:Locator=”Match(path)”>>
        <system.web>
          … Bunch of transforms written under here will
          …. only apply if location path = C:\MySite\Admin
        </system.web>
</location>

 

 

 

Step 7: Using Web.config transformation toolset for config files in sub-folders within the project

 

 

 

 

All of the above discussion directly applies to any web.config file present in sub folders of your project (e.g. if you have a separate web.config file for say “Admin” folder then VS 10 will support transforms for them too). You can add transform files within sub-folders and use the same packaging functionality mentioned in all of the above steps to create transformed web.config files for web.config files specific to the sub folders within your project.

 

 

 

I think this has become a rather long post; but I hope it helps!!

Vishal R. Joshi | Program Manager | Visual Studio Web Developer

YouTube XL

•4 Giugno 2009 • Lascia un Commento

C# 4.0 Optional Parameters and C# 4.0 Named Parameters

•4 Giugno 2009 • Lascia un Commento

I have to say I absolutely love the C# Language and am so happy that I decided to learn and embrace C# when .NET came on the scene and I transitioned from VB6. It is not to say VB is bad or inferior to C#, but that I really enjoy the tidiness and expressiveness of C#. It just speaks to me :)

With Visual Studio 2010 and the .NET Framework 4.0 we get a new version of the C# Language, C# 4.0.

 

C# 4.0 Optional Parameters and Named Parameters

A few of the interesting features in C# 4.0 are Optional Parameters, Default Values, and Named Parameters. The idea is that the arguments on a method may have “Default Values” and therefore it is unnecessary to supply those arguments in a method call if you are willing to accept those default values. This helps in those cases when we overload methods several times to help alleviate the caller from having to provide all values in a method. With Optional Parameters and Default Values you can now set Default Values to arguments on a method:

 

static void Write(string name, string address, string city = “Sarasota”) { … }

 

In the method above we have assigned the city parameter a default value of “Sarasota”, which means it can now be used optionally by the caller of the method:

 

Write(”David Hayden”, “1234 Broad Street”); city not specified, accept default.

 

or I can override the value by passing in the city as usual:

 

Write(“David Hayden“,“1234 Broad Street“,“Tampa“); // Overriding Default

 

Sometimes you may have multiple optional parameters:

 

static void Write(string name, string address, string city = “Sarasota”, string state=“Florida“) { … }

 

and the question becomes how do you specity a value for the state without specifying a value for the city? Named parameters, of course! We can now do the following:

 

Write(“David Hayden“,“1234 Broad Street“, state: “Hawaii“); 

 

Using the new “[parameter]:“ syntax is mind blowing and quite neat, no? :)

 

The only real convention here with optional parameters is that optional parameters must come at the end of the list of method arguments. Hence, you specify all your required arguments in the method first and then list the optional arguments last just like we did above.

The intellisense is pretty cool in Visual Studio 2010 for Optional Parameters, Default Values, and Named Parameters. Notice below how Visual Studio 2010 shows you the default values as well as pops-up the named parameter choices available for you to choose. Also notice in the screenshot that I chose to also use the named parameter syntax on the required zip parameter for kicks. That offers a bit of self-documenting code so you know what the values represent in the method call.

 

C# 4.0 Optional Parameters

 

Cool Stuff!!

 

Conclusion

Download Visual Studio 2010 Beta 1 and try out the C# 4.0 language features yourself.

 

David Hayden

A beginner’s guide for consuming a WCF service in JavaScript using ASP.NET AJAX

•24 Marzo 2009 • Comments Off

Preso da CodeProject articolo molto interessante.

Contents

Development Platform

  1. Visual Studio 2008 SP1
  2. .NET Framework 3.5 SP1
  3. ASP.NET AJAX
  4. IIS 7 or VS Integrated Web Server [WCF and SVS file configured]
  5. Windows Vista

ClientAjaxTodoApp.jpg

Introduction

WCF (Windows Communication Foundation) added a lot of new capabilities to the Microsoft application development platform, particularly in how applications communicate with each other. In this article, we are going to see how WCF can be used directly from a client-side JavaScript code. It is a very cool future provided by ASP.NET AJAX. In this article, we are not going to cover every theory about WCF internals, rather we only remain focused on how to use a service directly from JavaScript. So, no behind-the-scenes stuff on how ASP.NET or the .NET runtime manages this feature.

To demonstrate the ideas and facts, we are going create a demo solution with two projects. So, with no time waste, create a blank solution and save it. Now, add a Class Library project to the solution. Name the class library ServiceLibrary. Now, add a Web Application project to the solution and name it WEBUI. We are going to see two approaches to add a WCF Service that can be consumed from JavaScript.

  1. Using Ajax-Enable WCF Service item template
  2. Using Service Interface defined in a class library

Using an AJAX-Enabled WCF Service Item Template

Here, we will see a very straightforward way to use a WCF Service in JavaScript. Right click on the Web Application project and select Add New Item. Select AJAX-Enabled WCF Service Item Template, and name it “HelloWorldService.svc” and click OK. The wizard will add a HelloWorldService.svc file to the solution as expected. This file will have a code-behind file as well. If you open HelloWorldService.svc in an XML file editor, you will see a markup like this:

Collapse Copy Code
<%@ ServiceHost Language="C#" Debug="true"
  Service="WebUI.HelloWorldService" CodeBehind="HelloWorldService.svc.cs" %>

ChooseItemTemplate.jpg

If you open the code-behind file, you will see code like this:

Collapse Copy Code
namespace WebUI
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public class HelloWorldService
    {
        [OperationContract]
        public void DoWork()
        {
            return;
        }
    }
}

Visual Studio 2008 automatically adds the necessary configurations for you in the web.config file, so no need to configure any thing in the web.config. Now, go ahead and add a HelloWorld() method which returns a string “HelloWorld”, and add a [OperationContract] attribute to the method. We will explain what the attributes are later in this article. Now, add a page to the Web Application project and name it “HelloWorldTest.aspx”. Drag and drop a Script Manager item from the Visual Studio tool box. Inside the ScriptManager tag, add a service reference to the service. An example code is given below:

Collapse Copy Code
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/HelloWorldService.svc" />
    </Services>
</asp:ScriptManager>

Now, add a button and a textbox to the page, and on the button click event, use a JavaScript function to call the Service. When you write the service call function, the Visual Studio 2008 HTML Editor will provide intellisense to write the necessary function call. The full HTML code is give below:

Collapse Copy Code
<form id="form1" runat="server">
<div>
    <script language="javascript" type="text/javascript">
        function GetValueFromServer() {
            HelloWorldService.HelloWorld(onSuccess, onFailure);
        }

        function onSuccess(result) {
            document.getElementById('txtValueContainer').value = result;
        }

        function onFailure(result) {
            window.alert(result);
        }
    </script>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/HelloWorldService.svc" />
        </Services>
    </asp:ScriptManager>
    <input id="btnServiceCaller" type="button" value="Get Value"
           onclick="GetValueFromServer()"; />
    <input id="txtValueContainer" type="text" value="" />
</div>
</form>

Note that when calling the service, we have passed two methods: one for the callback and the other for the error callback. If we need to pass any parameters to the function, the parameters will go first and then the callback. So, if we have a function named getvalue which takes two string parameters as arguments, we are going to call the function as [NameSpaceName].[ServiceName].getvalue(“value one”,”value two”,on_success,on_error);, where on_sucess and on_error are the callback and the error callback, respectively.

Using a Service Interface Defined in the Class Library

So, we have looked at how to use an AJAX-enabled WCF Service using an item template. Now, we are going to see a more traditional WCF Service implementation, and we are also going to see how we can expose this service for ASP.NET AJAX. When we created the Class Library project, by default, it is not added with the service model and the runtime serialization support which is necessary to run WCF. So, we have to add the necessary service references. Go ahead and right click on the Class Library project and select Add Reference, and then select these references:

  • System.Runtime.Serialization
  • System.ServiceModel

ProjectOfTodo.png

In this phase, we are going to use a TODO Management example to demonstrate the whole idea. Add a Service based database, and then create a TODO table with ID, Description, and Status fields. Now, add a LINQ to SQL class file from the item template. Drag and drop the TODO table from database to the LINQ to SQL Class File Designer. Now, click on the designer surface and from the property window, change the serialization mode to Unidirectional. Now, our designer generated LINQ to SQL classes are ready to be used for WCF. If you want to use custom user defined types, you must set the [DataContract] class attribute to your class and you must add the [DataMember] property attribute to each property of the class you want to expose to WCF.

Now, we are going to add a service interface like this:

Collapse Copy Code
namespace ServiceLibrary
{
    [ServiceContract(Namespace = "ServiceLibrary")]
    interface IToDoService
    {
        [OperationContract]
        ToDo GetToDo(long ID);
        [OperationContract]
        ToDo AddToDo(ToDo toDo);
        [OperationContract]
        bool DeleteToDo(ToDo todo);
        [OperationContract]
        ToDo UpdateToDo(ToDo todo);
        [OperationContract]
        List<ToDo> GetAllToDo();
    }
}

Note that we have mentioned a namespace inside the ServiceContract interface attribute. This is very important. We are going to use this name as the service name inside the JavaScript code to access the services. Now, we are going to add the implementation to this service interface; the code is given below. Please note that in the code, I have used the [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] class attribute; this is a must requirement for exposing the service as an ASP.NET AJAX enabled WCF Service.

Collapse Copy Code
namespace ServiceLibrary
{
    [AspNetCompatibilityRequirements(RequirementsMode =
        AspNetCompatibilityRequirementsMode.Allowed)]
    public class ToDoService : IToDoService
    {
        #region IToDoService Members
        public ToDo GetToDo(long ID)
        {
            DataClasses1DataContext context = new DataClasses1DataContext();
            var toDos = from p in context.ToDos
                        where p.ID == ID
                        select p;
            List<ToDo> listTodos =  toDos.ToList();
            if (listTodos != null && listTodos.Count > 0)
            {
                return listTodos[0];
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}

Configure a Web Application to Use the TODO Service

Now that we have defined all the necessary stuff to run our TODO application, it is time to expose the Service to the client as an ASP.NET AJAX enabled WCF Service. For this, we are going to add an AJAX-enabled WCF Service .svc file. And, we will get rid of the code-behind file. Or, we can add an XML file or a text file and then rename it to ToDoService.svc. Open it with an XML editor and add a directive like shown below:

Collapse Copy Code
<%@ ServiceHost Language="C#" Debug="true" Service="ServiceLibrary.ToDoService" %>

Now, we are going to put the necessary configuration to run this service in web.config. The code is given below:

Collapse Copy Code
<system.serviceModel>
  <behaviors>
   <endpointBehaviors>
    <behavior name="AspNetAjaxBehavior">
     <enableWebScript />
    </behavior>
    <behavior name="WebUI.HelloWorldServiceAspNetAjaxBehavior">
     <enableWebScript />
    </behavior>
   </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  <services>
   <service name="ServiceLibrary.ToDoService">
    <endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding"
     contract="ServiceLibrary.IToDoService" />
   </service>
   <service name="WebUI.HelloWorldService">
    <endpoint address="" behaviorConfiguration="WebUI.HelloWorldServiceAspNetAjaxBehavior"
     binding="webHttpBinding" contract="WebUI.HelloWorldService" />
   </service>
  </services>
</system.serviceModel>

Now, right click on the file and select View in Browser to see the service up and running well. A few things must be mentioned before moving to the next phase. You must add a serviceHostingEnvironment and set aspNetCompatibilityEnabled="true" to be able to use a WCF Service in ASP.NET with its features like HTTP Context, Session etc.

Using the Service in JavaScript

Now, use the service just like the HelloWorldService we previously used. Below, I have given example code to make things clear. The ScriptManager markup is also shown. Note that we have added a clientServiceHelper.js file. We have put all the client to WCF communication JavaScript functions in that file.

Collapse Copy Code
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Script/ClientServiceHeler.js" />
    </Scripts>
    <Services>
        <asp:ServiceReference Path="~/ToDoService.svc" />
    </Services>
</asp:ScriptManager>

We have used an ASP.NET AJAX client-side object oriented model to write the JavaScript client-code which is part of clientServiceHelper.js.

Collapse Copy Code
Type.registerNamespace("ServiceClients");
    ServiceClients.ToDoClient = function() {
}

ServiceClients.ToDoClient.prototype = {

    AddToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.AddToDo(todo, callback, errorCallBack);
    },

    DeleteToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.DeleteToDo(todo, callback, errorCallBack);
    },

    UpdateToDo: function(todo, callback, errorCallBack) {
        ServiceLibrary.IToDoService.UpdateToDo(todo, callback, errorCallBack);
    },

    GetAllToDo: function(callback, errorCallBack) {
        ServiceLibrary.IToDoService.GetAllToDo(callback, errorCallBack);
    },

    dispose: function() {
    }
}

ServiceClients.ToDoClient.registerClass('ServiceClients.ToDoClient', null, Sys.IDisposable)

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Summary

In this article, we have seen how we can use an AJAX-enabled WCF Service Item Template. Then, we saw how we can use a service interface based WCF Service. We also saw how to configure the web.config to use the Services. Last of all, we saw how we to add a service reference in ScriptManager. A few things must be mentioned before ending this article. We can also add a service reference in the C# code. A simple code example is given below:.

Collapse Copy Code
ScriptManager manager = ScriptManager.GetCurrent(Page);
ServiceReference reference = new ServiceReference("ToDoService.svc");
manager.Services.Add(reference);

If beginners encounter problems or do not understand any particular portion of the article, please drop me a message. You can learn the ABCs of WCF here. If you have any difficulty configuring WCF in IIS, please see the article here.

References

•11 Marzo 2009 • Lascia un Commento

James Last – Romance

bellissima