2005 2006 2007 2008 2009 2010 2011 2015 2016 aspnet azure csharp debugging exceptions firefox javascriptajax linux llblgen powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

New XAG Feature: Support for C# 3.0 Automatic Properties

One of the nicest features of C# 3.0 is one of the most subtle: automatic properties.  It's really nothing more than syntactical sugar and saves us a little bit of typing, but it's been a big help in making my code more self-documenting.  If you're unfamiliar with automatic properties, here is what one looks like:

public Int32 Id { get; set; }

When that single line is compiled and viewed in Reflector, you get the following:

[CompilerGenerated]
private int <Id>k__BackingField;

public int Id
{
    [CompilerGenerated]
    get
    {
        return this.<Id>k__BackingField;
    }
    [CompilerGenerated]
    set
    {
        this.<Id>k__BackingField = value;
    }
}

The new syntax is equivalent to a classic C# property.  Note that this property has a get accessor and a set accessor.  This is the only type of automatic property you will be able to create.  You need the full {get; set; } for the automatic property to compile.  { get; } or { set; } won't cut it.  If you need a property with only a get or set accessor, then you need to use a classic C# property.  However, you can use { get; private set; } for a read-only property.  It will create both accessors, but only the get accessor will be public.  Also keep in mind that the Visual Studio 2008 code-snippet shortcut "prop" now creates an automatic property and "propg" creates an automatic property with a private set accessor.

Since this feature helps so greatly in the readability of the code, I have added a new feature to XAG: minimized properties.  Here is what the classical C# 2.0 syntax would look like for simple DTO (data transfer object) using XAG:

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/">
    <SimpleType x:Key="ClassKey" Type="Class" AutoGenerateConstructorsByProperties="True" Namespace="ClassNamespace"  AccessModifier="Public">
        <Properties AccessModifier="Public">
            <Id Type="Int32" />
            <Name Type="String" />
            <Title Type="String" />
        </Properties>
    </SimpleType>
</Assembly>

Using XAG's express type creation, the XML compiles to the following C# code:

using System;

namespace ClassNamespace
{
    public class SimpleType
    {
        private Int32 id;
        private String name;
        private String title;
        public Int32 Id {
            get { return id; }
            set { id = value; }
        }

        public String Name {
            get { return name; }
            set { name = value; }
        }

        public String Title {
            get { return title; }
            set { title = value; }
        }

        public SimpleType(Int32 id, String name, String title) {
            this.Id = id;
            this.Name = name;
            this.Title = title;
        }

        public SimpleType( ) {
        }
    }
}

That's painfully verbose when compared with automatic properties.  The new feature in XAG allows you to choose between a classic property and a minimized property (an automatic property in C# 3.0).  Below is the same XAG DTO done with Minimized properties.  In this example, notice that AutoGenerateConstructorsByProperties is set to false (the default).  This is because C# 3.0 has feature called object initializers, which allow you to set properties when you instantiate an object without needing any special constructor.

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/">
  <SimpleType x:Key="ClassKey" Type="Class" Namespace="ClassNamespace" AccessModifier="Public">
    <Properties AccessModifier="Public" Minimized="True">
      <Id Type="Int32" />
      <Name Type="String" />
      <Title Type="String" />
    </Properties>
  </SimpleType>
</Assembly>

By simply setting Minimized to true (and optionally, AutoGenerateConstructorsByProperties to false), you get the following C# 3.0 code:

using System;

namespace ClassNamespace
{
    public class SimpleType
    {
        public Int32 Id { get; set; }
        public String Name { get; set; }
        public String Title { get; set; }

        public SimpleType( ) {
        }
    }
}

You can also use this new minimize option with the existing options Static (a Boolean) and Mode (Blank, "GetOnly", or "SetOnly"), but you obviously can't use it with the Backing option.   The Backing option has a default value of true which means that the property is backed by a private field.  There is no such thing as an automatic property with an explicit backing field; that's the entire point of an automatic property.  The following example demonstrates a few legal combinations for properties in XAG.  Notice that you can tell XAG that you want all but a few specified properties to be minimized.

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/">
    <SimpleType x:Key="ClassKey" Type="Class" Namespace="ClassNamespace"  AccessModifier="Public">
        <Properties AccessModifier="Public" Minimized="True">
            <Id Type="Int32" />
            <Name Type="String" Static="true" Mode="GetOnly" />
            <Title Type="String" Minimized="False" Backing="False" Mode="GetOnly" />
        </Properties>
    </SimpleType>
</Assembly>

This XML code compiles to the following C# 3.0 class:

using System;

namespace ClassNamespace
{
    public class SimpleType
    {
        public Int32 Id { get; set; }

        public static String Name { get; private set; }

        public String Title {
            get { throw new Exception("The method or operation is not implemented."); }
        }

        public SimpleType( ) {
        }
    }
}

In C# 3.0, you could use that code with an object initializer like this:

SimpleType st = new SimpleType( )
{
    Id = 8
};

Int32 id = st.Id; // id == 8

You can find more information about my XML Assembly Compiler at http://www.jampadtechnology.com/xag/.

Related Links

More Flexible XAG Properties

Recently, I found myself constantly writing classes that have many properties with no backing fields (i.e. use ViewState) or are get-only. So, I added this feature to XAG. Now, you can set the "Mode" to "GetOnly" or "SetOnly" and "Backing" to either "true" or "false". Keep in mind that set-only (write-only) properties aren't exactly the best thing to use. If you find yourself wanting to do that, you should really reexamine what you're doing.

Furthermore, I wanted the ability to have values cascade to others. So, now you can set things like the Mode, Backing, Static, and AccessModifier on the entire Properties or Methods group instead of the individual properties or methods.

Here's an example of all this:

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2007/02/" DefaultNamespace="MyCompany.MyProject.Confguration">
  <ProjectConfiguration Type="Class" AccessModifier="Internal" Static="True">
    <Properties Mode="GetOnly" Backing="False" AccessModifier="Internal">
      <ProjectTitle Type="String" />
      <DatabaseConnectionString Type="String" />
      <ErrorEmailToAddress Type="String" />
      <ErrorEmailFromAddress Type="String" />
      <AutoNotifyOnError Type="Boolean" />
    </Properties>
  </ProjectConfiguration>
  <Configuration>
    <appSettings>
      <add key="ProjectTitle" value="My Title" />
      <add key="DatabaseConnectionString " value="..." />
      <add key="ErrorEmailToAddress " value="dfb@davidbetz.net" />
      <add key="ErrorEmailFromAddress " value="no-reply@tempuri.org" />
      <add key="AutoNotifyOnError " value="False" />
    </appSettings>
  </Configuration>
</Assembly>

In addition, I changed the XAG interface a bit to make it much more user friendly. Personally, I use my WPF version, which I'll probably be releasing soon (as well as documentation for the Web Service).

New XAG Feature - Simplified DTO Creation

After finishing up the first CTP of Minima I have to say that creating my own objects for data transfer (called DTOs - Data Transfer Objects) is painfully lame and using XAG to create an entire projet every thing is a bit overkill. So, I added a middle ground feature into XAG to allow all of us to very efficiently generate DTOs.

So, now, you can go to XAG, select the DTO Class Template (or write your own), select "Single Type Only" and it will show you the class ON SCREEN in a text area for easy copy/paste into your own project. This should make data transfer in the pre-C# 3.0 world MUCH easier.

Here's an example of what you can do.... you simply put the following in (you could have XAG put the DataContract and DataMember attributes on there too-- see the XAG WCF template), select Single Type Only mode, hit Create, and you get the below code instantaneously on the screen. I've been an advocate of AJAX for 8 years now and this should serve as an example of why you should use it too. Link to XAG is below.

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/">
    <Person x:Key="Person" Type="Class" AutoGenerateConstructorsByProperties="True" AccessModifier="Public" Namespace="AcmeCorp.Sales">
      <Properties>
        <FirstName Type="String" />
        <LastName Type="String" />
        <Address1 Type="String" />
        <Address2 Type="String" />
        <City Type="String" />
        <State Type="String" />
        <PostalCode Type="String" />
      </Properties>
    </Person>
</Assembly>
using System;
using System.Runtime.Serialization;

namespace AcmeCorp.Sales
{
    public class Person
    {
        private String firstname;
        private String lastname;
        private String address1;
        private String address2;
        private String city;
        private String state;
        private String postalcode;

        public String FirstName {
            get { return firstname; }
            set { firstname = value; }
        }

        public String LastName {
            get { return lastname; }
            set { lastname = value; }
        }

        public String Address1 {
            get { return address1; }
            set { address1 = value; }
        }

        public String Address2 {
            get { return address2; }
            set { address2 = value; }
        }

        public String City {
            get { return city; }
            set { city = value; }
        }

        public String State {
            get { return state; }
            set { state = value; }
        }

        public String PostalCode {
            get { return postalcode; }
            set { postalcode = value; }
        }

        public Person(String firstName, String lastName, String address1, String address2, String city, String state, String postalCode) {
            this.FirstName=firstName;
            this.LastName=lastName;
            this.Address1=address1;
            this.Address2=address2;
            this.City=city;
            this.State=state;
            this.PostalCode=postalCode;
        }

        public Person( ) {
        }
    }
}

Links

New XAG Feature - Better Generics

In the original release of XAG, properties could be generic only by using aliases. That is, if you wanted to have a property with a type of "Collection<Item>" you would have to create an alias like this:

using LineItemsCollection = System.Collections.ObjectModel.Collection<XagNewGenericsExample.Item>;

...

private LineItemsCollection lineitems;

public LineItemsCollection LineItems {
    get { return lineitems; }
    set { lineitems = value; }
}

which in XAG's markup looked like this:

<Aliases>
  <Alias x:Key="LineItemsCollection" Name="Whatever" Type="System.Collections.ObjectModel.Collection[{Type Item}]" />
</Aliases>
<Properties>
  <LineItems Type="{Type LineItemsCollection}" />
</Properties>

That's not really a bad deal as it really helps to enforce proper type design. For example, many times I will see people doing this:

public class MyAlias : Collection<Item> {}

MyAlias is NOT an alias for Collection<Item>. Try to compare them in code, they won't match up. However, in the first example "LineItemsCollection" and "Collection<Item>" are the same.

That said, I wanted to add something a bit more flexible. So I wrote an extension markup subsystem for XAG that allows for more complex generics. Here's an example of a property using the new generics system (assuming you have the System.Collections.ObjectModel namespace in):

<LineItems Type="{GenericType Name=Collection, Types=({Type Item})}" />

As you can see it's completely inline. Now here's a more complex example:

<ComplexItems Type="{GenericType Name=Dictionary, Types=(Int32, {GenericType Name=Collection, Types=({Type Item})})}" />

This XAG property translates to the following C# property:

private Dictionary<Int32, Collection<Item>> complexitems;

public Dictionary<Int32, Collection<Item>> ComplexItems {
    get { return complexitems; }
    set { complexitems = value; }
}

Here's a complete example you can try on your own.

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/" DefaultNamespace="XagNewGenericsExample">
  <Item x:Key="Item" Type="Class" AccessModifier="Public" />
  <ItemSet x:Key="ItemSet" Type="Class" AccessModifier="Public">
    <Imports>
      <Import Name="System.Collections.Generic" />
      <Import Name="System.Collections.ObjectModel" />
    </Imports>
    <Properties>
      <Items Type="{GenericType Name=Collection, Types=({Type Item})}" />
      <ComplexItems Type="{GenericType Name=Dictionary, Types=(Int32, {GenericType Name=Collection, Types=({Type Item})})}" />
    </Properties>
  </ItemSet>
</Assembly>
So now you an have more complex generic types in your XAG structure.

Links

Using XAG to Create a WCF Service

Here's a good example of what you could use XAG for. Using XAG, the below XML document compiles to a WCF Service Project. It contains an interface, a class implementing the interface, a few data contracts, and all appropriate references.

As you can see, you can include a literal configuration in the XML structure. This will be included as an app.config in your project.

What is XAG? XAG is a new FREE .NET 2.0/3.0 architecture and development tool allowing the creation of entire VS2005 projects in a single XML structure. You can access XAG at http://www.jampadtechnology.com/xag/

<Assembly xmlns:x="http://www.jampadtechnology.com/xag/2006/11/">
  <References>
    <Reference Name="System.Runtime.Serialization " />
    <Reference Name="System.ServiceModel" />
  </References>
  <Folder Header="Data Contracts">
    <Person x:Key="Person" Type="Class" AutoGenerateConstructorsByProperties="True" AccessModifier="Public" Namespace="AcmeCorp.Sales ">
      <Attributes>
        <Attribute Type="DataContract" Namespace="System.Runtime.Serialization" />
      </Attributes>
      <Properties>
        <FirstName Type="String" />
        <LastName Type="String" />
        <Address1 Type="String" />
        <Address2 Type="String" />
        <City Type="String" />
        <State Type="String" />
        <PostalCode Type="String" />
      </Properties>
    </Person>
    <CreditCard x:Key="CreditCard" Type="Class" AccessModifier="Public" Namespace="AcmeCorp.Sales">
      <Attributes>
        <Attribute Type="DataContract" Namespace="System.Runtime.Serialization" />
      </Attributes>
      <Properties>
        <Number Type="String" />
        <Cvv2 Type="String" />
        <Name Type="String" />
        <ExpDate Type="String" />
      </Properties>
    </CreditCard>
    <Item x:Key="Item" Type="Class" AccessModifier="Public" Namespace="AcmeCorp.Sales">
      <Attributes>
        <Attribute Type="DataContract" Namespace="System.Runtime.Serialization" />
      </Attributes>
      <Properties>
        <ItemCode Type="String" />
        <Name Type="String" />
        <Price Type="Decimal" />
      </Properties>
    </Item>
    <Cart x:Key="Cart" Type="Class" AccessModifier="Public" Namespace="AcmeCorp.Sales ">
      <Attributes>
        <Attribute Type="DataContract" Namespace="System.Runtime.Serialization" />
      </Attributes>
      <Aliases>
        <Alias x:Key="LineItemsCollection" Name="LineItemsCollection" Type="System.Collections.ObjectModel.Collection [{Type Item}]" />
      </Aliases>
      <Properties>
        <LineItems Type="{Type LineItemsCollection}" />
      </Properties>
    </Cart>
    <Sale x:Key="Sale" Type="Class" AccessModifier="Public" Namespace="AcmeCorp.Sales">
      <Attributes>
        <Attribute Type="DataContract" Namespace="System.Runtime.Serialization " />
      </Attributes>
      <Properties>
        <Person AccessModifier="Public" Type="{Type Person}" InstantiateObject="True" />
        <CreditCard AccessModifier="Public" Type="{Type CreditCard}" />
        <Cart AccessModifier="Public" Type="{Type Cart}" />
      </Properties>
    </Sale>
  </Folder>
  <Folder Header="Services">
    <IProcessorService x:Key="IProcessorService" Type="Interface" AccessModifier="Public" Namespace="AcmeCorp.ServiceContracts">
      <Attributes>
        <Attribute Type="ServiceContract" Namespace="System.ServiceModel" Reference="System.ServiceModel" />
      </Attributes>
      <Methods>
        <ProcessSale ReturnType="Void">
          <Attributes>
            <Attribute Type="OperationContract" Namespace="System.ServiceModel" />
          </Attributes>
          <Parameters>
            <Parameter Name="sale" Type="{Type Sale}" />
          </Parameters>
        </ProcessSale>
      </Methods>
    </IProcessorService>
    <ProcessorService Type="Class" AccessModifier="Public" Namespace="AcmeCorp.Service">
      <Implements>
        <Interface Name="{Type IProcessorService}" Namespace="System" />
      </Implements>
    </ProcessorService>
  </Folder>
  <Configuration>
    <!--
// Sample Console Application

using System;
using System.ServiceModel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args) {
            using (ServiceHost service = new ServiceHost(typeof(AcmeCorp.Service.ProcessorService))) {
                service.Open( );
                Console.WriteLine("Listening...");
                Console.ReadLine( );
            }
        }
    }
}
-->
    <system.serviceModel>
      <services>
        <service name="AcmeCorp.Service.ProcessorService" behaviorConfiguration="Service1Behavior">
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:3827/"/>
              <add baseAddress="net.pipe://localhost/"/>
            </baseAddresses>
          </host>
          <endpoint address="" contract="AcmeCorp.ServiceContracts.IProcessorService" binding="netNamedPipeBinding"/>
          <endpoint address="mex" contract="IMetadataExchange" binding="mexHttpBinding"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="Service1Behavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
      </behaviors>
    </system.serviceModel>
  </Configuration>
</Assembly>
1 2

Powered by
Python / Django / Elasticsearch / Azure / Nginx / CentOS 7

Mini-icons are part of the Silk Icons set of icons at famfamfam.com