a DotNetStyling - .Net World by Armen Ayvazyan
Welcome to DotNetStyling Sign in | Join | Help
Add to Technorati Favorites Add to Google Reader or Homepage Add to My AOL Subscribe in FeedLounge Subscribe in Bloglines Add to Excite MIX Add to flurry Add to Pageflakes Subscribe in NewsGator Online


C# 3.0 Features. Part IV: Anonymous Types

 

Previous materials of C# 3.0 Feature series:

"Dynamic" Classes

Anonymous Type is basically the C# way how we can dynamically create, populate and use a class without type declaration. If for some reason we need temporary classes as data carrier without any business logic implementation then Anonymous Types could be the perfect solution. Instead of having statically declared bunch of standard classes we can eliminate our efforts and use Anonymous types. Actually this feature mainly was created to support Expression Tree and LINQ which would be hard to implement without it.

Anonymous type declaration syntax is very simple.

   1: var someObject = new {Name = "Bob", Age = 23};

As you can see we used three technics introduced by C# 3.0 features: Auto Property, new Object initialization syntax and var keyword. Without any of them it won’t be possible to have Anonymous Types in game.

  

How does it work?

Actually Anonymous Type is not such “anonymous” like it sounds. What actually happens is that during the compilation compiler creates “static” type for us.

If we compile the application and look at the compiled IL code then we will find some strange f_AnonymousType0’2 class.

image

This is our Anonymous Type introduced by compiler which actually under the hood creates type with public properties.

image

  

Usage

After declaration of object based on Anonymous Type we are free to use it in a standard way as we do with standard classes including intellisense support.

image

   1: var someObject = new {Name = "Bob", Age = 23};
   2: Console.WriteLine("Name is {0}, age is {1}", someObject.Name, someObject.Age);

image

 

C# 3.0 Features. Part III: The var keyword

Previous materials of C# 3.0 Feature series:

 

“var” keyword

During the local variable declaration we have to explicitly specify the type even if the variable doesn’t have any value yet. The “var” expression brings as ability do not specify the type during local variable declaration. The compiler will get it from the initializer.

Let’s declare two local variables of the same type (User) but one will be declared in standard (old) way and another one with using “var” keyword.

   1: User userTodd = new User() { UserName = "Todd" };
   2:  
   3: var userBob = new User() {UserName = "Bob"};

Disassembler shows that both variables (userTodd and userBob) have the same type CSharp30Features.User even we did not explicitly specify the type in case of userBob variable.

image

Also keep in mind that ones the variable has been initialized by one type it won’t be possible to reassign it to another type. We will get compile time error:

   1: var someVar = 1;
   2: someVar = "This assignment will bring compile time error";

 

Why to use “var” keyword?

The obvious question is what is the advantage of using “var” keyword. 

Redundancy in expression

We do not need to specify type twice in local variable declaration expression.

   1: SomeType varName = new SomeType();

The right side of the expression already shows which type variable will be. It is enough to specify it just ones:

   1: var varName = new SomeType();

Anonymous Types support.

“var” expression became necessarily after introducing the Anonymous Types. In case of Anonymous Type declaration we cannot use standard expression as the type which variable has to be assign to is unknown.

   1: ??? someVar = new {Property1="value", Property2="Another value"};

This is a valid expression for Anonymous Types:

   1: var someVar = new {Property1="value", Property2="Another value"};

I am planning to speak explicitly about Anonymous Types in my next upcoming blog post “C# 3.0 Features. Part IV: Anonymous Types”

Technorati tags: , ,
Posted: 7. srpna 2008 13:58 by armencz | 1 Comments
Filed under: , ,
C# 3.0 Features. Part II: Object and Collection Initialization

Previous materials of C# 3.0 Feature series:

Object Initialization

New object initialization technique gives us ability to define and fill the public property of the object on the fly. This expression was created to support LINQ but it can be used anywhere. This expression helps to fill values during the initialization and keep constructor empty.

   1: public enum Sex { Male, Female }
   2:  
   3: public class User
   4: {
   5:     public int UserId { get; private set; }
   6:     public string UserName { get; set; }
   7:     public string UserAddress { get; set; }
   8:     public DateTime DateOfBirth { get; set; }
   9:     public Sex UserSex { get; set; }
  10: }

User object initialization by using OLD style expression:

   1: User user = new User();
   2: user.UserAddress = "FR, Paris";
   3: user.DateOfBirth = new DateTime(1984, 1, 1);
   4: user.UserName = "Michelle";
   5: user.UserSex = Sex.Female;

Similar object initialization by using new feature:

   1: User user = new User
   2:                 {
   3:                     UserAddress = "US,Redmond",
   4:                     DateOfBirth = new DateTime(1974, 1, 1),
   5:                     UserName = "Mike",
   6:                     UserSex = Sex.Male
   7:                 };

Collection Initialization

There is a similar feature for collection initialization. We can define a collection and add object on the fly.

The standard way of collection initialization:

   1: List<User> users = new List<User>();
   2: users.Add(user1);
   3: users.Add(user2);

Initialization of collection by using new C# 3.0 feature:

   1: List<User> users = new List<User>{user1, user2};

Both in one

Finally we can combine those two expressions and have the whole collection initialization in one line. This could be helpful when preparing collection with dummy data for testing.

   1: List<User> users = new List<User>
   2:                                 {
   3:                                     new User
   4:                                         {
   5:                                             UserAddress = "US,Redmond",
   6:                                             DateOfBirth = new DateTime(1974, 1, 1),
   7:                                             UserName = "Mike",
   8:                                             UserSex = Sex.Male
   9:                                         },
  10:                                     new User
  11:                                         {
  12:                                             UserAddress = "US, New-York",
  13:                                             DateOfBirth = new DateTime(1978, 1, 1),
  14:                                             UserName = "David",
  15:                                             UserSex = Sex.Male
  16:                                         }
  17:                                 };

 

 

Share this post :

C# 3.0 Features. Part I: Auto Property

 

I would like to continue my blogging experience with a series of blog posts related to C# 3.0 features. Although there are already a lot of materials regarding this subject in .Net community my impression is so strong that it forces me write about it.

I decided to post simple blog per feature. The first one in the list is “Auto Property”

 

Redundancy in Property Declaration

Usually, we use properties as data carrier which do not contain any business logic inside. This especially visible on DTO class implementation. For every property in the class we have to introduce private field which connects to property in getter and/or setter without being used in other parts of the class.

   1: public class User
   2: {
   3:     private int _userId;
   4:     public int UserId
   5:     {
   6:         get { return _userId; }
   7:         set { _userId = value; }
   8:     }
   9:  
  10:     private string _userName;
  11:     public string UserName
  12:     {
  13:         get { return _userName; }
  14:         set { _userName = value; }
  15:     }
  16:  
  17: }

As you can see we face to redundancy in property declaration.

 

Simplify Property Declaration

By using Auto Property feature of C# 3.0 we can declare a property without private field declaration, with empty setter and getter (using the same style as we do in interfaces). The compiler will create an appropriate code for us. It will create a private field and use it in set_ get_ methods accordingly.

On the example below the UserId property has been converted to Auto Property declaration style where UserName remained the same.

   1: public class User
   2: {
   3:     public int UserId { get; set; }
   4:  
   5:     private string _userName;
   6:     public string UserName
   7:     {
   8:         get { return _userName; }
   9:         set { _userName = value; }
  10:     }
  11: }

 

We will compile the code and explore the result. IL Disassembler shows that compiler created both "get_XXX" and "set_XXX" methods for UserId property the same way as it did for UserName.

image

 

 

Advantage

The advantage of this feature is obvious:

  • Saves time during class declaration
  • Removes redundancy in the code
  • Code becomes much more clear and readable
   1: public class User
   2: {
   3:     public int UserId { get; set; }
   4:     public string UserName { get; set; }
   5: }

 

BTW, we still can play with access modifiers of getter and setter if needed:

   1: public class User
   2: {
   3:     public int UserId { get; private set; }
   4:     public string UserName { get; internal set; }
   5: }

 

Attention

Auto property applies only on public properties which private member is not used in other part of the class (including constructor).

 

Technorati tags: ,

Share this post :

How to Create Plugin for Windows Live Writer? Simple Content Source.

Windows Live Writer gives capability to extend functionality by creating new plug-ins.

What I will demonstrate here is how to create content source plug-in which inserts custom formatted content.

There are two types of content sources available in writer:

  • Simple Content Source
  • Smart Content Source

 

Simple Content Source:
Enables to insert custom HTML code to the post.

Smart Content Source:
Enables to insert custom HTML content with "smart" editing capabilities, such as include atomic selection, two-way editing using the Sidebar, resizability.

In this blog post I'll demonstrate how to create Simple content source plug-in.

 

Content Source Plugin

 

Create Project in Visual Studio

First of all we have to create Class Library project in Visual Studio.

This demo has been done by Visual Studio 2005 and .Net Framework 2.0

image

image

 

Next, we have to add reference to C:\Program Files\Windows Live\Writer\WindowsLive.Writer.Api.dll library. Library contains classes which we will use for for plug-in implementation.

image

image

 

Set property "Copy Local" of added reference to false. It will stop copying to destination folder all libraries required for WindowsLive.Writer.Api.dll.

image

 

 

Create Class

Now it is time to implement class which will contain implementation of plug-in.

 

Attributes

Create a new class and cover it by WindowsLive.Writer.Api.WriterPluginAttribute.

WriterPluginAttribute's constructor accepts two input parameters: GUID and Name. Both require to unify plug-in in the list of all plugins in Live Writer.

Note: There is also "imagepath" parameter which defines path to the image file which can be used as an icon but currently it marks as "Obsolete" therefor I'll skip this part for now.

There are three features which can be overridden in both Simple and Smart content sources:

  • Insert content from Dialog box
  • Insert content from Clipboard
  • Insert content from URL

In this demo we will write plug-in which uses "Insert content from Dialog box" functionality. To achieve that we have to cover class by WindowsLive.Writer.Api.InsertableContentSourceAttribute attribute.

Note: To implement "Insert content from Clipboard" or "Insert content from URL" class should be covered by LiveClipboardContentSourceAttribute or UrlContentSourceAttribute respectively.

Attributes notify Live Writer that plug-in contains implantation of "Insert" functionality.

Constructor of InsertableContentSourceAttribute class require at least one input parameter which is title of plug-in shown on "Insert" list.

 

using WindowsLive.Writer.Api;
namespace HyperlinkBuilder
{  
     [WriterPlugin("ad23cf0b-5cf2-441d-a0d7-7ee3fdc4ff55""HyperlinkBuilder")] 
     [InsertableContentSource("Hyperlink to content.")] 
     public class LinkContainer 
    
     }
}

 

 

HyperlinkContainerEditor

For demo let's create plug-in which will insert hyperlink to the content.

First we'll create a editor with three textboxes which allows to add URL, Text and Title of hyperlink. Due to fact that dialog box (editor) based on windows form, we have to add reference to System.Windows.Forms.dll library.

image

 

Now let's implement editor. It basically contains three textboxes (URL, Text, Title) and two buttons (OK, Cancel).

 

using System.Windows.Forms;

 namespace DotNetStyling.LiveWriterPlugins.HyperlinkBuilder

     public partial class HyperlinkBuilderEditor : Form 
    
           public HyperlinkBuilderEditor() 
          
                InitializeComponent(); 
                this.txtURL.Focus(); 
           }


           public string HyperlinkTitle 
          
                get { return txtTitle.Text; } 
           }


           public string HyperlinkURL 
          
                get { return txtURL.Text; } 
           }


           public string HyperlinkText 
          
                get { return txtText.Text; } 
          
     }
}

image

 

 

ContentSource base class

To implement Simple Content we have to inherit class from WindowsLive.Writer.ContentSource and overrite one of its member:

To implement "Insert Content from Dialog Box" we have to override CreateContent method.

Note: For implementation "Create from Clipboard" or "Create Content From URL" functionality we have to override CreateContentFromLiveClipboard and CreateContentFromUrl methods respectively.

using System.Text;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

 namespace DotNetStyling.LiveWriterPlugins.LinkContainer

     [WriterPlugin("ad23cf0b-5cf2-441d-a0d7-7ee3fdc4ff55", "HyperlinkBuilder")] 
     [InsertableContentSource("Hyperlink to content.")] 
     public class HyperlinkBuilder: ContentSource 
    
           public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content) 
           {                  
                DialogResult dialogResult;

                HyperlinkContainerEditor editor = new HyperlinkContainerEditor();

                dialogResult = editor.ShowDialog();

                if(dialogResult==DialogResult.OK) 
               
                
    content = PrepareHyperlink(editor.HyperlinkText,
editor.HyperlinkURL,
editor.HyperlinkTitle);

                }

                 return dialogResult;
          }

           private string PrepareHyperlink(
string text,
string url,
string title) 
          
                StringBuilder formattedHyperlink = new StringBuilder(256);

                 formattedHyperlink.AppendFormat( 
                    "<a href='{0}' title='{1}'>{2}</a>"
                     url, 
                     title, 
                     text);

                 return formattedHyperlink.ToString(); 
         
     }
}

 

Basically that's it. To simplify demonstration I will skip Validating input parameter or other UX features.

 

Deploy

  • Build a project.
  • Copy compiled file to the C:\Program Files\Windows Live\Writer\Plugins\ folder 
  • Run Windows Live Writer

In the list of insert features there is