Tuesday, February 26, 2013

C# Numbers to Words example


        public static string NumberToWords(this Decimal d)
        {
            if (d == 0)
            {
                return ("Zero Dollars and No Cents");
            }
            d = Math.Abs(d);
            string[] ones = { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
            string[] teens = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
            string[] tens = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
            string[] magnitude = { "Hundred", "Thousand", "Million", "Billion", "Trillion", "Quadrillion", "WholeBunch" };
            byte Digit1, Digit2, Digit3, Digit2And3;
            int ndx;
            ArrayList wordSegments = new ArrayList();
            string wordAmount = string.Empty;
            string wordSegment = string.Empty;
            Int64 dollarAmount = Convert.ToInt64(Math.Floor(d));
            byte centsAmount = Convert.ToByte((System.Convert.ToDouble(d) - System.Convert.ToDouble(dollarAmount)) * 100);
            string segmentedNumber = d.ToString("###,###.00");
            string[] NumericSegments = segmentedNumber.Split(new string[] { ",", "." }, StringSplitOptions.RemoveEmptyEntries);
            for (ndx = 0; ndx < NumericSegments.Length; ndx++)
            {
                NumericSegments[ndx] = NumericSegments[ndx].PadLeft(3, Convert.ToChar("0"));
            }
            foreach (string NumericSegment in NumericSegments)
            {
                Digit1 = Convert.ToByte(Convert.ToString(NumericSegment[0]));
                Digit2 = Convert.ToByte(Convert.ToString(NumericSegment[1]));
                Digit3 = Convert.ToByte(Convert.ToString(NumericSegment[2]));
                Digit2And3 = Convert.ToByte(NumericSegment.Substring(1, 2));

                if (Digit1 > 0)  //in the hundreds
                {
                    wordSegment = ones[Digit1 - 1] + " Hundred";
                }
                if (Digit2And3 > 19) //over the teens
                {
                    wordSegment += (wordSegment.Length > 0 ? " and " : " ") + tens[Digit2 - 2];

                    if (Digit3 > 0) //has a lower decimal
                    {
                        wordSegment += "-" + ones[Digit3 - 1];
                    }
                }
                else
                {
                    if (Digit2And3 > 9) //teens
                    {
                        wordSegment += (wordSegment.Length > 0 ? " and " : " ") + teens[Digit3];
                    }
                    else
                    {
                        if (Digit3 > 0) //under teens
                        {
                            wordSegment += " " + ones[Digit3 - 1];
                        }
                    }
                }

                wordSegments.Add(wordSegment);
                wordSegment = string.Empty;
            }

            wordSegments.Reverse();

            for (ndx = 0; ndx < wordSegments.Count; ndx++)
            {
                string currentSegment = (string)wordSegments[ndx];
                switch (ndx)
                {
                    case 0:
                    wordAmount = (centsAmount == 0 ? " No Cents" : currentSegment + " Cent" + (centsAmount > 1 ? "s" : ""));
                    break;
                    case 1:
                    wordAmount = currentSegment + " Dollar" + (dollarAmount > 1 ? "s" : "") + " and" + wordAmount;
                    break;
                    default:
                    wordAmount = currentSegment + " " + magnitude[ndx - 1] + ", " + wordAmount;
                    break;
                }
            }
            wordAmount = wordAmount.Trim();
            string savedWordAmount = wordAmount;


            //wraps the string once
            try
            {
                const int maxLength = 70;
                if (wordAmount.Length > maxLength)
                {
                    string firstbit = wordAmount.Substring(0, maxLength);
                    int lastSpace = firstbit.LastIndexOf(" ");
                    wordAmount = wordAmount.Remove(lastSpace, 1);
                    wordAmount = wordAmount.Insert(lastSpace, Environment.NewLine);
                }

            }
            catch (Exception ex)
            {
                wordAmount = savedWordAmount;
            }

            return wordAmount;
        }


Friday, February 1, 2013

Generate Entities from SQL using CRM 2011

Introduction

This example shows how to create CRM entities based on an existing CRM database. The methodologies used here are as follows:


  1. Create a basic windows form app
  2. Create an Entity Data Model from the database
  3. Write a T4 template that iterates through the tables and their fields
  4. Creating C# code that creates entities on the fly.
  5. Plug the code into the T4 template
  6. Run the code for your solution
  7. Open CRM and notice the new entities
  8. Voila!

Create a basic windows form app

Call it EntityGenerator

Create an Entity Data Model from the database

  1. Right Click on the project, go to Visual C# items, Data and select ADO.Net Entity Data Model
  2. Call it MyEntityDataModel.edmx and click Add
  3. Select Generate from Database
  4. If necessary, specify Create New Connection to connect to the database you want to copy
  5. Make sure Save entity connection settings in App.Config is checked
  6. Click Next
  7. Include Tables only, Plurlize/Singularize the object names and accept the model Name Space.
  8. Click Finish
  9. You will be presented with a complete model of the database, with all the relations. Click save.

Write the T4 template

T4 is a built-in component of Visual Studio, but the editor (as of Visual Studio 2010) is non existent. So got to http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html and download a copy of their editor. Its free and worth every penny. Install it.
  1. Create a new folder in your project called Generated Code
  2. Right click on the folder and navigate to tangible T4 Editor, and select Blank T4 Template. Note that the name of the template file is the name of the .cs file you will create, so make it sensible. I'm calling mine CRMEntityClasses.tt
  3. After clicking OK, give it a few seconds. The pause happens as the TF editor is loaded into the IDE. It basically replaces the usual editor, with one that is more t4 friendly. You should have something like this:

  4. Very simply, the yellow section is where the directives for code generation live. This does not get written to the file. Anything that is in the white section actually written to file. Try it out - type Hello right at the bottom and expand the node in the project explorer to show the generated file - in this case CRMEntityClasses.cs. When you open the file, you will see "Hello". Directive blocks are denoted with a <# and a #>.
  5. Replace all the code with the following:

    <#@ template language="C#" debug="false" hostspecific="true"#>
    <#@ include file="EF.Utility.CS.ttinclude"#>
    <#@ output extension=".cs"#>
    using System;
    namespace EntityGenerator
    {
           public partial class GenerateEntities
           {
     <#


    #>
           }
    }


  6. The second line is important - you are telling the T4 generator to include the ability to use the Entity Framework. Click Save (this triggers generation) and look at the class. 
  7. Now in the yellow directives section, make the T4 generator aware of the Entity Data Model. Add the following code there:

    CodeGenerationTools code = new CodeGenerationTools(this);
    MetadataLoader loader = new MetadataLoader(this);
    CodeRegion region = new CodeRegion(this, 1);
    MetadataTools ef = new MetadataTools(this);

    string inputFile = @"../MyEntityDataModel.edmx";
    EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);

    EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
  8. Now add the logic of iterating through the entity data model, and output the code.  This is where the Tangible T4 editor is valuable - the coloring syntax makes it all a lot more readable. The entire filename should now look like this:

    <#@ template language="C#" debug="false" hostspecific="true"#>
    <#@ include file="EF.Utility.CS.ttinclude"#>
    <#@ output extension=".cs"#>
    using System;
    namespace EntityGenerator
    {
           public partial class GenerateEntities
           {
     <#
    CodeGenerationTools code = new CodeGenerationTools(this);
    MetadataLoader loader = new MetadataLoader(this);
    CodeRegion region = new CodeRegion(this, 1);
    MetadataTools ef = new MetadataTools(this);

    string inputFile = @"../MyEntityDataModel.edmx";
    EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);

    EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);

    foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
            {
                         string firstLetter = code.Escape(entity).Substring(0,1).ToLower();
                         string entityName = code.Escape(entity);#>     
                  //The table = <#=entityName#>
                  <#foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
           {#>
                  //field is <#= edmProperty #> of type <#=code.Escape(edmProperty.TypeUsage)#>
                  <#}#> 
             <#}#>
           }
    }
  9. When you click Save, the output file will be generated. Your  generated file will be different from mine, because you are using your own database. But this is the top part of my output:
    using System;
    namespace EntityGenerator
    {
           public partial class GenerateEntities
           {
          
                  //The table = City
                               //field is CityId of type int
                               //field is CountryId of type string
                               //field is StateId of type string
                               //field is Name of type string
                        
                 
                  //The table = Country
                               //field is Iso of type string
                               //field is Name of type string
                               //field is Printable_name of type string
                               //field is Iso3 of type string
                               //field is numcode of type Nullable<short>
                        
                 
                  //The table = County
                               //field is FIPSCode of type string
                               //field is StateID of type string
                               //field is Name of type string
                        
                 
                  //The table = Financer
                               //field is FinancerId of type int
                               //field is Name of type string
                         
  10. So all that this has done is show you how to expose the  tables, fields and field types of a specific database. The next step is the actual generation of code that will create them in CRM.

C# code that creates CRM 2011 entities on the fly

Review the MSDN article at http://msdn.microsoft.com/en-us/library/gg509071.aspx
This is similar to that article, but refactored to optimize for code generation
  1. Make sure the project is using .Net Framework 4 (not .Net Framework 4 Client Profile)
  2. Add the following service references to the project:
    1. System.Data.Services
    2. microsoft.crm.sdk.proxy
    3. microsoft.xrm.sdk
    4. System.ServiceModel
    5. System.Data.Entity.Design

  3. Add the following fields onto the windows form you created.(I put these here so I don't have to monkey with a config file; it a tad harder for other developers looking over my shoulder to discover my password. Yes, its horrible but it works for now. Clearly a case for refactoring...)

  4. Add the following USING statements in the form's code:

    using System;
    using System.ServiceModel.Description;
    using System.Windows.Forms;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using System.Data.Entity.Design.PluralizationServices;
    using System.Globalization;

  5. Embed the following code inside the Do It button:


    private void button1_Click(object sender, EventArgs e)
    {
        //SET UP CREDENTIALS
        Uri OrganizationUri = new Uri(textBoxServerUrl.Text + "/" + textBoxOrg.Text + "/XRMServices/2011/Organization.svc");
        ClientCredentials Credentials = new ClientCredentials();
        Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(textBoxName.Text, textBoxPassword.Text, textBoxDomain.Text);

        //INITIALIZE PIPELINE SERVICE
        OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null);
        serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
        IOrganizationService service = (IOrganizationService)serviceProxy;

        string prefix = "new_";
        string entityName = "BankAccount";
        string entityNamePlural = "BankAccounts";

        EntityMetadata emd = new EntityMetadata();
        emd.SchemaName = prefix + entityName;
        emd.DisplayName = new Microsoft.Xrm.Sdk.Label(entityName, 1033);
        emd.DisplayCollectionName = new Microsoft.Xrm.Sdk.Label(entityNamePlural, 1033);
        emd.OwnershipType = OwnershipTypes.UserOwned;
        emd.IsActivity = false;

        StringAttributeMetadata sam = new StringAttributeMetadata();
        sam.SchemaName = prefix + "BankAccountName";
        sam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended);
        sam.MaxLength = 100;
        sam.Format = Microsoft.Xrm.Sdk.Metadata.StringFormat.Text;
        sam.DisplayName = new Microsoft.Xrm.Sdk.Label("BankAccountName", 1033);

        CreateEntity(service, emd, sam);

        AttributeMetadata amd = new DateTimeAttributeMetadata(DateTimeFormat.DateOnly);
        amd.SchemaName = "new_checkeddate";
        amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
        amd.DisplayName = new Microsoft.Xrm.Sdk.Label("Date", 1033);
        amd.Description = new Microsoft.Xrm.Sdk.Label("The date the account balance was last confirmed", 1033);

        CreateAttribute(service, prefix+ entityName, amd);
    }

    private void CreateEntity(IOrganizationService service, EntityMetadata emd, StringAttributeMetadata sam)
    {
        CreateEntityRequest cr = new CreateEntityRequest();
        cr.Entity = emd;
        cr.PrimaryAttribute = sam;
        service.Execute(cr);
    }

    private void CreateAttribute(IOrganizationService service, string parentEntity, AttributeMetadata  amd)
    {
        CreateAttributeRequest car = new CreateAttributeRequest();
        car.EntityName = parentEntity.ToLower();
        car.Attribute = amd;
        service.Execute(car);
    }
  6. Run it. If it adds the entity, with the 2 fields to your CRM then you are ready to start using the Code Generator.

Using T4 Templates

Its ugly if you dont use the Tangible Editor. 
  1. Create a new Tt file called CRMEntityClasses.tt
  2. Paste the following block of code into the file, replacing everything:

    <#@ template language="C#" debug="false" hostspecific="true"#>
    <#@ include file="EF.Utility.CS.ttinclude"#>
    <#@ output extension=".cs"#>
    using System;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;
    using System.ServiceModel.Description;
    using Microsoft.Xrm.Sdk.Client;
    using System.Data.Entity.Design.PluralizationServices;
    using System.Globalization;

    namespace EntityGenerator
    {
           public partial class GenerateEntities
           {
            #region Private members
            private IOrganizationService _service;
                  private string _prefix;
                  private PluralizationService _pluralizer = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en-us"));
            #endregion


            #region Constructor
            public GenerateEntities(string org, string prefix, string userName, string userPassword, string domainName, string serverUrl )
            {
                 
                //SET UP CREDENTIALS
                Uri OrganizationUri = new Uri(serverUrl + "/" + org + "/XRMServices/2011/Organization.svc");
                ClientCredentials credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new System.Net.NetworkCredential(userName, userPassword, domainName);

                //INITIALIZE PIPELINE SERVICE
                OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, credentials, null);
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;
                 
                _service = service;
                         _prefix = prefix;
            }
                  #endregion

          
                  #region General private methods
          
            private void CreateEntity(IOrganizationService service, EntityMetadata emd, StringAttributeMetadata sam)
            {
                CreateEntityRequest cr = new CreateEntityRequest();
                cr.Entity = emd;
                cr.PrimaryAttribute = sam;
                service.Execute(cr);
            }
            private void CreateAttribute(IOrganizationService service, string parentEntity, AttributeMetadata  amd)
            {
                CreateAttributeRequest car = new CreateAttributeRequest();
                car.EntityName = parentEntity.ToLower();
                car.Attribute = amd;
                service.Execute(car);
            }
            #endregion

     <#
    CodeGenerationTools code = new CodeGenerationTools(this);
    MetadataLoader loader = new MetadataLoader(this);
    CodeRegion region = new CodeRegion(this, 1);
    MetadataTools ef = new MetadataTools(this);
    string inputFile = @"../MyEntityDataModel.edmx";
    EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);

    EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
    #>
                  public void CreateAllEntities()
                  {
                  string entityName;
                  string entityNamePlural;
                  EntityMetadata emd;
                  StringAttributeMetadata sam;
                  AttributeMetadata amd;
                  MemoAttributeMetadata mam;
    <#
    foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
            {
                         string firstLetter = code.Escape(entity).Substring(0,1).ToLower();
                         string entityName = code.Escape(entity);#>     
                         entityName ="<#=entityName#>";
                         entityNamePlural=_pluralizer.Pluralize(entityName);
                  //=====================================================================================================
                  //Create the <#=entityName#> entity
                 
                         emd = new EntityMetadata();
                emd.SchemaName = _prefix + entityName;
                emd.DisplayName = new Microsoft.Xrm.Sdk.Label(entityName, 1033);
                         emd.DisplayCollectionName = new Microsoft.Xrm.Sdk.Label(entityNamePlural, 1033);
                emd.OwnershipType = OwnershipTypes.UserOwned;
                emd.IsActivity = false;

                sam = new StringAttributeMetadata();
                sam.SchemaName = _prefix + entityName + "Name";
                sam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.Recommended);
                sam.MaxLength = 100;
                sam.Format = Microsoft.Xrm.Sdk.Metadata.StringFormat.Text;
                sam.DisplayName = new Microsoft.Xrm.Sdk.Label("<#=entityName#>Name", 1033);

                         //Make the WCF call to generate the entity
                CreateEntity(_service, emd, sam);         
                 
                  //Create the attributes for <#=entityName#>
                  <#foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
           {
                         string dataType=code.Escape(edmProperty.TypeUsage);
                         string fieldName=edmProperty.ToString();

                         if(fieldName.ToLower().Trim()==entityName.ToLower()+"id" )

                         {

                               fieldName=entityName.ToLower()+"_id" ;
                         }

                         string cleanDataType;
                         bool isNullable = dataType.IndexOf("Nullable")==-1?false:true;
                         bool isSupported=false;
                        
                         cleanDataType= dataType.Replace("Nullable","");
                         cleanDataType= cleanDataType.Replace("System.","");
                         cleanDataType= cleanDataType.Replace("Offset","");
                         cleanDataType= cleanDataType.Replace("<","");
                         cleanDataType= cleanDataType.Replace(">","");
                         cleanDataType= cleanDataType.Replace("[","");
                         cleanDataType= cleanDataType.Replace("]","");
                        
                         #>
    <#if(fieldName.ToLower().Trim()!=entityName.ToLower()+"id" && fieldName.ToLower().Trim()!=entityName.ToLower()+"name"){#>
    //attribute name is <#= fieldName #> of type <#=dataType#>, isNullable = <#= isNullable #> and clean type = <#= cleanDataType #>
                         <#
                switch (cleanDataType)
                {
                    case "int":
                                      #>amd = new IntegerAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                              
                    case "DateTime":
                                      #>amd = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime);
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                    case "decimal":
                                      #>amd = new DecimalAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                         case "byte":
                                      #>amd = new IntegerAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                                      break;
                         case "bool":
                                      #>amd = new DecimalAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                         case "long":
                                      #>amd = new IntegerAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                         case "double":
                                      #>amd = new DoubleAttributeMetadata();
                amd.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    amd.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    amd.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         amd.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                         CreateAttribute(_service, _prefix + entityName, amd);
                                      <#
                    break;
                         case "string":
                                       int maxLength = 0;
                                       Int32.TryParse(edmProperty.TypeUsage.Facets["MaxLength"].Value.ToString(), out maxLength);      #>
                                      <# if(maxLength==0){ #>          
                         mam = new MemoAttributeMetadata();
                         mam.MaxLength = 1048576;
                         mam.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    mam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    mam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
    mam.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         mam.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                        
                         CreateAttribute(_service, _prefix + entityName, mam);
                                     
                                      <# } else{ #>
    sam = new StringAttributeMetadata();
                         sam.MaxLength = <#= maxLength #>;
                         sam.SchemaName = _prefix + "<#= fieldName #>";
                         <# if(isNullable){ #>
    sam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None);
                         <# } else { #>
    sam.RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.ApplicationRequired);
                         <# } #>
                                     
                         sam.DisplayName = new Microsoft.Xrm.Sdk.Label("<#= fieldName #>", 1033);
                         sam.Description = new Microsoft.Xrm.Sdk.Label("Generated with a tool", 1033);
                        
                         CreateAttribute(_service, _prefix + entityName, sam);
                                     
                                      <# }  #>
               
                                      <#
                    break;
                         case "TimeSpan":
                                      #>
                  //TimeSpan attribute not supported for field <#= fieldName #>
                                      <#
                    break;
                                     
                    default:
                                      #><#
                    break;
                }
                         #>

           <#}#>
                  <#}#> 
             <#}#>
                  }
           }
    }
  3. Modify the line string inputFile = @"../MyEntityDataModel.edmx"; so that it points to your Entity Framework Model.
  4. You may need to modify your Namespace (namespace EntityGenerator)
  5. When you click save, T4 will read the EDMX and write the class file, which is basically a whole bunch of calls to the WCF service.

Implement the generated code:

Embed this in a button on your form:
        private void button2_Click(object sender, EventArgs e)
        {
            GenerateEntities ge = new GenerateEntities(
                textBoxOrg.Text,
                "fcbt_",
                textBoxName.Text,
                textBoxPassword.Text,
                textBoxDomain.Text,
                textBoxServerUrl.Text);
            ge.CreateAllEntities();
        }

 Run the code, it will take a while. Open CRM and see what it did. Have fun!