Giter Club home page Giter Club logo

dlab.xrm.xrmtoolboxtools's Introduction

DLaB.Xrm.XrmToolBoxTools Build status

Join the chat at https://gitter.im/daryllabar/DLaB.Xrm.XrmToolBoxTools

This repository contains multiple plugins for the XrmToolBox.

XrmToolBox Plugins

  • Early Bound Generator - Extends and automates the creation of Early Bound Xrm classes
  • Attribute Manager BETA!!! - Allows the addition/editing of attributes, including renaming and changing Attribute Types. This will eventually replace the Local to Global Option Set Converter. This is not production ready! It is released with exactly zero warranty or support. If it deletes files or kills your family pet, you have been warned. It might work great, and it might not. It hasn't been tested against all CRM versions and entity scenarios, but it works on my machine/environment for the tasks that I have used it for.
  • Visual Studio Solution Accelerator - Setups a C# Solution (or adds to your existing solution) with the appropriate projects and shared proejcts to create Dataverse plugins, with optional unit testing build int.
  • Outlook Timesheet Calculator - An app to create timesheets by sucking hours out of Outlook (Has nothing to do with Dataverse)

dlab.xrm.xrmtoolboxtools's People

Contributors

adcodicem avatar bhawk90 avatar chadclair avatar daryllabar avatar dependabot[bot] avatar derekfinlinson avatar filcole avatar flaviocdc avatar iggsn avatar jodyfarnden avatar joshcampbell191 avatar kirillkanyukov avatar lnetrebskii avatar maeg02 avatar majakubowski avatar micheleietri avatar mscrmtools avatar ndoriot avatar power-maverick avatar rappen avatar ryanperrymba avatar skfd avatar thuemmeryf avatar vandenberghev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dlab.xrm.xrmtoolboxtools's Issues

Early Bound Generation - url / domain / user info not provided for onprem connection

I'm using an on premises connection and trying to run the early bound connection against it.

The utility doesn't seem to be providing the /url, /domain, /user, or /password to the crmsrvutil, which is causing it to fail.

If I run the generated command manually and provide the missing options, it will run and generate my classes. This is a decent workaround, though I can't use some of the functionality such as specifying which classes to map.

Is there anything I might be missing?

Could not load provider Error

Hello,

Having an issue where I can connect fine to the organization but when I try to generate code I get the following error, anyone can point me to a possible solution?

CRM Authentication Type Detected: OnlineFederation
Executing "C:\Users####\CRM SDK Samples\SDK\Bin\crmsvcutil.exe" /url:"#####" /namespace:"####" /out:"C:\Dev\CPP\MAIN - (LIVE)\SOURCE\CRMCommon\CRMEntities\XrmContext.cs" /servicecontextname:"XrmContext" /codecustomization:"DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /metadataproviderservice:"DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions" /username:"#####" /password:"***********"
CrmSvcUtil : CRM Service Utility [Version 8.1.0.7711]
¸ 2015 Microsoft Corporation. All rights reserved

CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.NotSupportedException: Could not load provider of type 'DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions'
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : CrmSvcUtil
Method : CreateInstance
Date : 4:25:41 PM
Time : 8/2/2016
Error : Could not load provider of type 'DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions'
Stack Trace : at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Output file was not updated or not found! C:\Dev\CPP\MAIN - (LIVE)\SOURCE\CRMCommon\CRMEntities\XrmContext.cs

Trying to use connection to an ifd crm throws exception

Hi,

unfortunatley I cannot use the tool to generate early bindings for an internet facing CRM organization.
I get the following exception, though I have connected to CRM sucessfully with XRM toolbox. Trying to exclude entities from the generated code also lets me select entites, so the connection must be working in some way.

CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentNullException: Organization cannot be null or empty.
Parameter name: Organization Name
at Microsoft.Xrm.Tooling.Connector.CrmServiceClient.ConnectToCrmWebService(String crmConnectionString)
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.CreateOrganizationServiceEndpoint()
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : InvokeMethod
Date : 15:15:56
Time : 24.03.2016
Error : Exception has been thrown by the target of an invocation.
Stack Trace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Inner Exception Level 1 :
Source : Microsoft.Xrm.Tooling.Connector
Method : ConnectToCrmWebService
Date : 15:15:56
Time : 24.03.2016
Error : Organization cannot be null or empty.
Parameter name: Organization Name
Stack Trace : at Microsoft.Xrm.Tooling.Connector.CrmServiceClient.ConnectToCrmWebService(String crmConnectionString)
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.CreateOrganizationServiceEndpoint()
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()

at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)

1.2016.4.27 - Doesn't change attribute casing

When I use the "Specify Attribute Names" the names are not updated with the casing that I have specified.

  • attribute name in CRM: "new_attribtecomplexname"
  • generated name: "New_attribtecomplexname"
  • expected name: "New_AttribteComplexName"

This appears to be a regression from the previous version.

Entity and OptionSet Could Have the Same Exact Name

If an Entity and a Global Option Set have the same exact name, when the classes generate, they will create compile warnings. Current workaround is to skip the OptionSet Generation and manually add it with a different name. Ideally the tool should be able to determine naming collisions and avoid them.

Difficulties with Early Bound Generator

I was trying to create the early bound CRM entitties, using XrmToolBox v1.2016.4.28.

First I set up my connection to our CRM instance and after I opened the Early Bound Generator.
I setup my preferred options and the list of entities which to exclude.
But once I try to create the entities, I get a list of options and the following error:

Output file was not updated or not found! + path to my Service context file.

My output file is located in the right directory.

Any help into the solution of this problem is greatly appreciated.

Select publisher prefix to skip

I think nice enhancement could be (additionaly to picking up optionSets/entities to skip while generating) will be add an option to pick publisher prefixes, eg. msdyn_ to ship. Adding manually all 3rd-party entities to excluded list is annoying.

Error connecting to CRM (0365?)

Hi Daryl,

I'm trying to use the Early Bound Generator plugin for the XrmToolBox and I'm getting a connection error.

I can select the Entites to Skip button and it loads all the correct entities and schema names, but whenever I click the Create Entities button I get an error similar to below (I've modified the Url, Username and Password to remove actual credentials

My CRM system is CRM Online (federated via Office365)

CRM Authentication Type Detected: OnlineFederation
Executing "C:\All Tools\CRM Tools\XrmToolBox2\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /url:"https://dev-org.api.crm6.dynamics.com/XRMServices/2011/Organization.svc" /namespace:"CrmEarlyBound" /out:"C:\All Tools\CRM Tools\XrmToolBox2\Plugins\CrmSvcUtil Ref\Entities.cs" /servicecontextname:"CrmServiceContext" /codecustomization:"DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /metadataproviderservice:"DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions" /username:"[email protected]" /password:"myPassword"
CrmSvcUtil : CRM Service Utility [Version 8.0.1.7297]
¸ 2015 Microsoft Corporation. All rights reserved

Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Connection to CRM is not established. Aborting process.
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : InvokeMethod
Date : 1:35:52 PM
Time : 23/05/2016
Error : Exception has been thrown by the target of an invocation.
Stack Trace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Inner Exception Level 1 :
Source : CrmSvcUtil
Method : Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata
Date : 1:35:52 PM
Time : 23/05/2016
Error : Connection to CRM is not established. Aborting process.
Stack Trace : at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()

at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)

Output file was not updated or not found! C:\All Tools\CRM Tools\XrmToolBox2\Plugins\CrmSvcUtil Ref\Entities.cs

Local to Global OptionSet Converter

Hi Darryl, I've been using your Local to Global OptionSet Converter for the last couple of days - firstly many thanks for making an immensely useful tool! I don't know what I'd have done if this wasn't available, probably ended up copying the option set to the other entity where I needed it and put up with the double entry...

Anyway, I have some feedback for you as the result of some pretty intensive testing! The first problem I encountered were data validation issues for old data coming from my plugins. Those caused the data migration to error out on the first run. That freaked me out somewhat since all the Views and Forms had been updated by that stage, and I'm working on the live system since we're on CRM Online with no Sandbox instance. So, I quickly implemented a 'Revert unsuccessful migration' option to undo a partially done migration (http://screencast.com/t/QaIxlI31).

Later I noticed that you had implemented in the data migration a "catch-up" option to speed up partially done migrations. Once I realised that you'd taken that into account, I quickly switched the order of the steps so that data migration is done before updating views and forms. That way, the data migration can take as long as it takes, and can be repeated endlessly, with no effect on the end user - the views and forms only get switched once a full migration has successfully completed.

I made the same change for the migrate to global section.

In your UpdateViews method, I found it necessary to trap for attempted changes to non-Public views, as Dynamics gave me an error when trying to change those programatically - they must be updated manually.

I made some additions to your AssertCanDelete method, to present to the user the name of the dependent component - much more helpful than just giving the Id.

Finally, AssertCanDelete was always returning errors because of SavedQueryVizualisation dependencies - ie. Charts! So I implemented an UpdateCharts method too.

I think that's it. I used your code from Codeplex, as I did download from Github but there were errors on trying to run XrmToolbox related to your components. The Codeplex version worked fine. I'm going to paste my updated code below as I'm sorry I didn't use your Github version, and nor am I particularly au fait with doing pull requests etc in Git, but you can easily do a file compare on your version and mine and see where the differences are.

Thanks again for your work, was immensely useful for me!!

Regards, Ben

Logic.cs

`using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Messages;
using DLaB.Xrm;
using Microsoft.Xrm.Sdk.Query;
using DLaB.Xrm.Entities;
using DLaB.Xrm.Common.Exceptions;
using DLaB.Xrm.Core.Entities;

namespace DLaB.LocalToGlobalOptionSet
{
public class Logic
{
public delegate void LogHandler(string text);
public event LogHandler OnLog;

    public bool MigrateData { get; set; }
    public bool ConvertValuesToGlobal { get; set; }
    public bool SupportsExecuteMultipleRequest { get; set; }
    public string TempPostfix { get; private set; }
    public IOrganizationService Service { get; private set; }
    public HashSet<int> ValidLanguageCodes { get; private set; }
    private const int CRM2013 = 6;
    private const int CRM2011 = 5;
    private const int Rollup12 = 3218;


    [Flags]
    public enum Steps
    {
        CreateTemp = 1,
        MigrateToTemp = 2,
        RemoveLocal = 4,
        CreateGlobal = 8,
        MigrateToGlobal = 16,
        RemoveTemp = 32,
        RevertUnsuccessful = 64,
    }

    public Logic(IOrganizationService service, McTools.Xrm.Connection.ConnectionDetail connectionDetail, string tempPostFix, bool migrateData, bool convertValuesToGlobal)
    {
        SupportsExecuteMultipleRequest = connectionDetail.OrganizationMajorVersion >= CRM2013 ||
                                         (connectionDetail.OrganizationMajorVersion >= CRM2011 && int.Parse(connectionDetail.OrganizationVersion.Split(new char[1] { '.' })[3]) >= Rollup12);
        Service = service;
        TempPostfix = tempPostFix;
        MigrateData = migrateData;
        ConvertValuesToGlobal = convertValuesToGlobal;
        ValidLanguageCodes = GetValidLanguageCodes();
    }

    private HashSet<int> GetValidLanguageCodes()
    {
        var resp = (RetrieveAvailableLanguagesResponse)Service.Execute(new RetrieveAvailableLanguagesRequest());
        return new HashSet<int>(resp.LocaleIds);
    }

    public void Run(string entityName, string attributeName, string globalOptionSetName, string globalOptionSetPrefix, Steps stepsToPerform)
    {
        // Create Temp
        AttributeMigrationState state = GetCrmOptionSetLocalToGlobalState(Service, entityName, attributeName, globalOptionSetName, stepsToPerform.HasFlag(Steps.RevertUnsuccessful));
        var oldAtt = state.Old;
        var tmpAtt = state.Temp;
        var newAtt = state.New;

        //see if we're undoing a previous unsuccessful run
        if (stepsToPerform.HasFlag(Steps.RevertUnsuccessful))
        {
            UpdateCharts(Service, tmpAtt, oldAtt);
            UpdateViews(Service, tmpAtt, oldAtt);
            UpdateForms(Service, tmpAtt, oldAtt);
            PublishEntity(Service, oldAtt.EntityLogicalName);
            AssertCanDelete(Service, tmpAtt);
            DeleteField(Service, tmpAtt);
            return;
        }

        AssertValidStepsForState(attributeName, stepsToPerform, state);
        AssertValidGlobalOptionSet(state, stepsToPerform, globalOptionSetName, globalOptionSetPrefix);

        if (stepsToPerform.HasFlag(Steps.CreateTemp))
        {
            tmpAtt = CreateTempAttribute(Service, oldAtt);
        }

        if (oldAtt != null)
        {
            if (stepsToPerform.HasFlag(Steps.MigrateToTemp))
            {
                if (MigrateData)
                {
                    CopyData(Service, oldAtt, tmpAtt, globalOptionSetPrefix);
                }

                // Replace Old Attribute with Tmp Attribute
                UpdateCharts(Service, oldAtt, tmpAtt);
                UpdateViews(Service, oldAtt, tmpAtt);
                UpdateForms(Service, oldAtt, tmpAtt);
                PublishEntity(Service, oldAtt.EntityLogicalName);
            }

            if (stepsToPerform.HasFlag(Steps.RemoveLocal))
            {
                AssertCanDelete(Service, oldAtt);
                DeleteField(Service, oldAtt);
            }
        }

        // Create new Attribute
        if (stepsToPerform.HasFlag(Steps.CreateGlobal))
        {
            newAtt = newAtt ?? CreateNewAttribute(Service, tmpAtt, state.GlobalOptionSet, globalOptionSetName, globalOptionSetPrefix);
        }

        if (stepsToPerform.HasFlag(Steps.MigrateToGlobal))
        {
            if (MigrateData)
            {
                CopyData(Service, tmpAtt, newAtt, globalOptionSetPrefix);
            }

            // Replace Tmp Attribute with New Attribute
            UpdateCharts(Service, tmpAtt, newAtt);
            UpdateViews(Service, tmpAtt, newAtt);
            UpdateForms(Service, tmpAtt, newAtt);
            PublishEntity(Service, newAtt.EntityLogicalName);
        }

        if (stepsToPerform.HasFlag(Steps.RemoveTemp))
        {
            AssertCanDelete(Service, tmpAtt);
            DeleteField(Service, tmpAtt);
        }
    }

    private void AssertValidGlobalOptionSet(AttributeMigrationState state, Steps stepsToPerform, string globalOptionSetName, string globalOptionSetPrefix)
    {
        if (MigrateData &&
            (stepsToPerform.HasFlag(Steps.MigrateToGlobal) || stepsToPerform.HasFlag(Steps.MigrateToTemp)))
        {
            var localOptionSet = (state.Old ?? state.Temp);

            if (localOptionSet == null)
            {
                throw new InvalidOperationException("Unable to Migrate Data!  No local Option Set was found!");
            }

            if (state.GlobalOptionSet != null)
            {
                if (!state.GlobalOptionSet.IsGlobal.GetValueOrDefault()) // Don't think this is possible
                {
                    throw new InvalidOperationException("Unable to Migrate Data!  " + globalOptionSetName +
                        " is invalid because it already exists and is not a global option set!");
                };

                var globalOptions = GetOptions(state.GlobalOptionSet);

                foreach (var option in localOptionSet.Options)
                {
                    var value = option.Value;
                    if (ConvertValuesToGlobal)
                    {
                        if (value > 9999)
                        {
                            throw new InvalidOperationException("Unable to Convert Option Set for Migrate!  " + option.Value +
                                " is an invalid local set value.  Local Option Set Values can not be greater than 9999");
                        }

                        value = ConvertLocalValueToGlobalValue(globalOptionSetPrefix, value);
                    }

                    if (!globalOptions.Any(osv => osv.Value == option.Value))
                    {
                        var displayText = option.Label == null ? String.Empty : option.Label.GetLocalOrDefaultText("N/A");

                        throw new InvalidOperationException(String.Format("Unable to Migrate Data!  Option Set Value \"{0}\" ({1}) does not have a corresponding value in the global option set {2} ({3})",
                            displayText, option.Value, globalOptionSetName, value));
                    }
                }
            }
            else if (ConvertValuesToGlobal)
            {
                foreach (var option in localOptionSet.Options.Where(o => o.Value.GetValueOrDefault() > 9999))
                {
                    throw new InvalidOperationException("Unable to Convert Option Set for Migrate!  " + option.Value +
                        " is an invalid local set value.  Local Option Set Values can not be greater than 9999");
                }
            }
        }
    }

    private static List<OptionMetadata> GetOptions(OptionSetMetadataBase optionSet)
    {
        List<OptionMetadata> options;
        var boolOS = optionSet as BooleanOptionSetMetadata;
        if (boolOS == null)
        {
            options = ((OptionSetMetadata)optionSet).Options.ToList();
        }
        else
        {
            options = new List<OptionMetadata>(){
                        boolOS.FalseOption, boolOS.TrueOption
                    };
        }
        return options;
    }

    private AttributeMigrationState GetCrmOptionSetLocalToGlobalState(IOrganizationService service, string entityName, string attributeName, string globalOptionSetName, bool revert)
    {
        AttributeMigrationState state;
        state = new AttributeMigrationState();
        try
        {
            Trace("Searching for Option Set " + entityName + "." + attributeName);

            state.Old = (AttributeMetadata)((RetrieveAttributeResponse)service.Execute(new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName })).AttributeMetadata;
            Trace("Option Set " + entityName + "." + attributeName + " found");
            if (state.Old.OptionSet.IsGlobal.GetValueOrDefault())
            {
                state.New = state.Old;
                state.Old = null;
                state.Temp = GetTempAttribute(service, entityName, attributeName);
                Trace("Option Set " + entityName + "." + attributeName + " is already a global option set");
            }
            else
            {
                try
                {
                    Trace("Searching for Option Set " + entityName + "." + attributeName + TempPostfix);
                    state.Temp = (AttributeMetadata)((RetrieveAttributeResponse)service.Execute(new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName + TempPostfix })).AttributeMetadata;
                    Trace("Option Set " + entityName + "." + attributeName + TempPostfix + " found");
                }
                catch { Trace("Option Set " + entityName + "." + attributeName + TempPostfix + " not found");  }
            }
        }
        catch (System.ServiceModel.FaultException<OrganizationServiceFault> ex)
        {
            if (ex.Message.Contains("Could not find attribute"))
            {
                if (state.New == null)
                {
                    Trace("Option Set " + entityName + "." + attributeName + " not found.  Seaching for Temp");
                    state.Temp = GetTempAttribute(Service, entityName, attributeName);
                }
                else
                {
                    throw new Exception(state.New.LogicalName + " is already a global option set, and no tmp optionset found to remove");
                }
            }
            else
            {
                throw;
            }
        }

        try
        {
            state.GlobalOptionSet = ((RetrieveOptionSetResponse)Service.Execute(new RetrieveOptionSetRequest() { Name = globalOptionSetName })).OptionSetMetadata;
        }
        catch {}

        return state;
    }

    private void AssertValidStepsForState(string attributeName, Steps stepsToPerform, AttributeMigrationState state)
    {
        if (stepsToPerform.HasFlag(Steps.CreateTemp) && state.Temp != null)
        {
            throw new InvalidOperationException("Unable to Create Temp!  Temp " + state.Temp.EntityLogicalName + "." + state.Temp.LogicalName + " already exists!");
        }

        if (stepsToPerform.HasFlag(Steps.MigrateToTemp))
        {
            // Can only Migrate if old already exists
            if (state.Old == null)
            {
                throw new InvalidOperationException("Unable to Migrate!  Local Option Set Value Attribute " + attributeName + " does not exist!");
            }

            // Can only Migrate if Tmp already exists, or temp will be created
            if (!(state.Temp != null || stepsToPerform.HasFlag(Steps.CreateTemp)))
            {
                throw new InvalidOperationException("Unable to Migrate!  Temporary Attribute " + attributeName + TempPostfix + " does not exist!");
            }
        }


        if (stepsToPerform.HasFlag(Steps.RemoveLocal))
        {
            if (state.Old == null)
            {
                AssertInvalidState("Unable to Remove Local!  Local Option Set Value Attribute " + attributeName + " does not exist!");
            }

            // Can only Remove local if Tmp already exists, or temp will be created
            if (!(state.Temp != null || stepsToPerform.HasFlag(Steps.CreateTemp)))
            {
                AssertInvalidState("Unable to Remove Local!  Temporary Attribute " + attributeName + TempPostfix + " does not exist!");
            }

            // Can only Remove local if Tmp will be migrated, or has been migrated
            if (!stepsToPerform.HasFlag(Steps.MigrateToTemp))
            {
                try
                {
                    AssertCanDelete(Service, state.Old);
                }
                catch
                {
                    AssertInvalidState("Unable to Remove Local!  Local Option Set Value Attribute " + attributeName + " has not been migrated to Temporary Attribute!");
                }
            }
        }

        if (stepsToPerform.HasFlag(Steps.CreateGlobal))
        {
            // Can only Create Global if Local does not exist or will be removed
            if (!(state.Old == null || stepsToPerform.HasFlag(Steps.RemoveLocal)))
            {
                AssertInvalidState("Unable to create Global!  Local Option Set Value Attribute " + attributeName + " still exists!");
            }

            // Can only Create Global if doesn't already exist
            if (!(state.New == null))
            {
                AssertInvalidState("Unable to create Global!  Global Option Set Value Attribute " + attributeName + " already exists!");
            }
        }

        if (stepsToPerform.HasFlag(Steps.MigrateToGlobal))
        {
            if (!(state.Temp != null || stepsToPerform.HasFlag(Steps.CreateTemp)))
            {
                AssertInvalidState("Unable to Migrate!  Temp Attribute " + attributeName + TempPostfix + " does not exist!");
            }

            // Can only Migrate if Global Already exists, or Global will be created
            if (!(state.New != null || stepsToPerform.HasFlag(Steps.CreateGlobal)))
            {
                AssertInvalidState("Unable to Migrate!  Global Option Set Value Attribute " + attributeName + " does not exist!");
            }
        }

        if (stepsToPerform.HasFlag(Steps.RemoveTemp))
        {
            // Can Only remove Temp if it exists, or will exist
            if (!(state.Temp != null || stepsToPerform.HasFlag(Steps.CreateTemp)))
            {
                AssertInvalidState("Unable to Remove Temp!  Temp Attribute " + attributeName + TempPostfix + " does not exist!");
            }

            // Can Only remove Temp if Global Already exists, or Global will be created
            if (!(state.New != null || stepsToPerform.HasFlag(Steps.CreateGlobal)))
            {
                AssertInvalidState("Unable to Migrate!  Global Option Set Value Attribute " + attributeName + " does not exist!");
            }

            // Can only Remove tmp if global will be migrated, or has been migrated
            if (!stepsToPerform.HasFlag(Steps.MigrateToGlobal))
            {
                try
                {
                    AssertCanDelete(Service, state.Temp);
                }
                catch
                {
                    AssertInvalidState("Unable to Remove Global!  Local Option Set Value Attribute " + attributeName + " has not been migrated to Temporary Attribute!");
                }
            }
        }
    }

    private void AssertInvalidState(string message)
    {
        throw new InvalidOperationException(message);
    }

    private AttributeMetadata GetTempAttribute(IOrganizationService service, string entityName, string attributeName)
    {
        return (AttributeMetadata)((RetrieveAttributeResponse)service.Execute(new RetrieveAttributeRequest() { EntityLogicalName = entityName, LogicalName = attributeName + TempPostfix })).AttributeMetadata;
    }

    private AttributeMetadata CreateNewAttribute(IOrganizationService service, AttributeMetadata tmpAtt, OptionSetMetadataBase globalOptionSet, string globalOptionSetName, string globalOSPrefix)
    {
        // Create Global OptionSet If needed
        if (globalOptionSet == null)
        {
            globalOptionSet = GetOptionSet(tmpAtt);
            globalOptionSet.IsGlobal = true;
            globalOptionSet.MetadataId = null;
            globalOptionSet.Name = globalOptionSetName;
            if (ConvertValuesToGlobal)
            {
                foreach (var option in GetOptions(globalOptionSet))
                {
                        option.Value = ConvertLocalValueToGlobalValue(globalOSPrefix, option.Value);
                }
            }

            Trace("Creating Global Option Set " + globalOptionSetName);
            try
            {
                var response = (CreateOptionSetResponse)service.Execute(new CreateOptionSetRequest()
                {
                    OptionSet = globalOptionSet
                });
                globalOptionSet.MetadataId = response.OptionSetId;
            }
            catch
            {
                Trace("Error Creating Option Set " + globalOptionSet.Name);
                throw;
            }
        }

        AttributeMetadata att = CloneAttribute(tmpAtt, globalOptionSet, s => s.Replace(TempPostfix, String.Empty));

        ClearOptions(globalOptionSet);
        Trace("Creating Attribute " + att.EntityLogicalName + "." + att.LogicalName);
        try
        {
            service.Execute(new CreateAttributeRequest()
            {
                Attribute = att,
                EntityName = att.EntityLogicalName,
            });
        }
        catch
        {

            Trace("Error Creating Attribute " + att.LogicalName);
            throw;
        }

        PublishEntity(service, att.EntityLogicalName);

        return att;
    }

    private void ClearOptions(OptionSetMetadataBase globalOptionSet)
    {
        var options = globalOptionSet as OptionSetMetadata;
        if (options == null)
        {
            var boolOptions = (BooleanOptionSetMetadata)globalOptionSet;
            boolOptions.TrueOption = null;
            boolOptions.FalseOption = null;
        }
        else
        {
            options.Options.Clear();
        }    
    }

    private void DeleteField(IOrganizationService service, AttributeMetadata att)
    {
        Trace("Deleting Field " + att.EntityLogicalName + "." + att.LogicalName);
        service.Execute(new DeleteAttributeRequest()
        {
            EntityLogicalName = att.EntityLogicalName,
            LogicalName = att.LogicalName
        });
    }

    private void AssertCanDelete(IOrganizationService service, AttributeMetadata oldAtt)
    {
        Trace("Checking for Delete Dependencies for " + oldAtt.EntityLogicalName + "." + oldAtt.LogicalName);
        var depends = (RetrieveDependenciesForDeleteResponse)service.Execute(new RetrieveDependenciesForDeleteRequest()
        {
            ComponentType = (int)componenttype.Attribute,
            ObjectId = oldAtt.MetadataId.Value
        });

        var errors = new List<String>();
        foreach (var d in depends.EntityCollection.ToEntityList<Dependency>())
        {
            var type = (componenttype) d.DependentComponentType.GetValueOrDefault();
            string err = type + " " + d.DependentComponentObjectId.Value;

            if (type == componenttype.EntityRelationship)
            {
                var response =
                    (RetrieveRelationshipResponse) service.Execute(new RetrieveRelationshipRequest {MetadataId = (Guid) d.DependentComponentObjectId});

                Trace("Entity Relationship {0} must be manually removed/added", response.RelationshipMetadata.SchemaName);
            }
            else if (type == componenttype.SavedQueryVisualization)
            {
                SavedQueryVisualization sq = service.GetEntity<SavedQueryVisualization>(d.DependentComponentObjectId.Value);
                if (sq != null)
                    err = String.Format("{0} ({1} - {2})", err, sq.Name, sq.CreatedBy.Name);
            }
            else if (type == componenttype.SavedQuery)
            {
                SavedQuery sq = service.GetEntity<SavedQuery>(d.DependentComponentObjectId.Value);
                if (sq != null)
                    err = String.Format("{0} ({1} - {2})", err, sq.Name, sq.CreatedBy.Name);
            }

            errors.Add(err);
        }

        if (errors.Count > 0)
        {
            throw new Exception("Dependencies found:\r\n\t" + String.Join("\r\n\t", errors));
        }
    }

    private void UpdateCharts(IOrganizationService service, AttributeMetadata from, AttributeMetadata to)
    {
        StringBuilder summary = new StringBuilder();
        Dictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("name=\"" + from.LogicalName + "\"", "name=\"#REPLACE#\"");

        foreach (KeyValuePair<string, string> kvp in conditions)
        {
            Trace("Retrieving System Charts with cond: " + kvp.Key);
            var charts = service.GetEntities<SavedQueryVisualization>(
                new ConditionExpression("datadescription", ConditionOperator.Like, "%<entity name=\"" + from.EntityLogicalName + "\">%" + kvp.Key + "%"));

            foreach (var chart in charts)
            {
                Trace("Updating Chart " + chart.Name);
                chart.DataDescription = chart.DataDescription.Replace(kvp.Key, kvp.Value.Replace("#REPLACE#", to.LogicalName));
                service.Update(chart);
            }
        }

        foreach (KeyValuePair<string, string> kvp in conditions)
        {
            Trace("Retrieving User Charts with cond: " + kvp.Key);
            var charts = service.GetEntities<UserQueryVisualization>(
                new ConditionExpression("datadescription", ConditionOperator.Like, "%<entity name=\"" + from.EntityLogicalName + "\">%" + kvp.Key + "%"));

            foreach (var chart in charts)
            {
                Trace("Updating Chart " + chart.Name);
                chart.DataDescription = chart.DataDescription.Replace(kvp.Key, kvp.Value.Replace("#REPLACE#", to.LogicalName));
                service.Update(chart);
            }
        }

        if (summary.Length > 0)
            Trace(summary.ToString());
    }

    private void UpdateForms(IOrganizationService service, AttributeMetadata from, AttributeMetadata to)
    {
        Trace("Retrieving Forms");
        var forms = service.GetEntities<SystemForm>(
            "objecttypecode", from.EntityLogicalName,
            new ConditionExpression("formxml", ConditionOperator.Like, "%<control id=\"" + from.LogicalName + "\"%"));

        foreach (var form in forms)
        {
            //if (form.IsManaged.Value || !form.IsCustomizable.CanBeChanged)
            //    Trace(String.Format("Cannot update form '{0}' Is not Customizable - you must update this manually!", form.Name));
            //else
            //{
                Trace("Updating Form " + form.Name);
                form.FormXml = form.FormXml.Replace("<control id=\"" + from.LogicalName + "\"", "<control id=\"" + to.LogicalName + "\"").
                    Replace("datafieldname=\"" + from.LogicalName + "\"", "datafieldname=\"" + to.LogicalName + "\"");
                service.Update(form);
            //}
        }
    }

    private void UpdateViews(IOrganizationService service, AttributeMetadata from, AttributeMetadata to)
    {
        StringBuilder summary = new StringBuilder();
        Dictionary<string, string> conditions = new Dictionary<string, string>();
        conditions.Add("name=\"" + from.LogicalName + "\"", "name=\"#REPLACE#\"");
        conditions.Add("attribute=\"" + from.LogicalName + "\"", "attribute=\"#REPLACE#\"");

        foreach (KeyValuePair<string, string> kvp in conditions) 
        {
            Trace("Retrieving Views with cond: " + kvp.Key);
            var queries = service.GetEntities<SavedQuery>(
                new ConditionExpression("fetchxml", ConditionOperator.Like, "%<entity name=\"" + from.EntityLogicalName + "\">%" + kvp.Key + "%"));

            foreach (var query in queries)
            {
                if (query.QueryType != 0)
                {
                    Trace(String.Format("Cannot update view '{0}' as this is not a Public view - you must update this manually!", query.Name));
                    summary.AppendFormat("Update view '{0}' manually!", query.Name);
                }
                else
                {
                    Trace("Updating View " + query.Name);
                    query.FetchXml = query.FetchXml.Replace(kvp.Key, kvp.Value.Replace("#REPLACE#", to.LogicalName));
                    if (query.LayoutXml != null)
                    {
                        query.LayoutXml = query.LayoutXml.Replace(kvp.Key, kvp.Value.Replace("#REPLACE#", to.LogicalName));
                    }
                    service.Update(query);
                }
            }
        }

        if (summary.Length > 0)
            Trace(summary.ToString());
    }

    private void CopyData(IOrganizationService service, OptionSetAttributeContainer from, OptionSetAttributeContainer to, string globalOSPrefix)
    {
        if (!MigrateData) { return; }

        var total = GetRecordCount(service, from);
        var count = 0;

        Trace("Copying data from {0} to {1}", from.LogicalName, to.LogicalName);
        var requests = new OrganizationRequestCollection();
        // Grab from and to, and only update if not equal.  This is to speed things up if it has failed part way through
        foreach (var entity in service.RetrieveAllList<Entity>(new QueryExpression(from.EntityLogicalName) { ColumnSet = new ColumnSet("name", from.LogicalName, to.LogicalName)}))
        {
            if (count++%10 == 0 || count == total)
            {
                if (requests.Any())
                {
                    PerformUpdates(service, requests);
                }

                Trace("Copying {0} / {1}", count, total);
                requests.Clear();
            }

            var value = entity.GetAttributeValue<OptionSetValue>(from.LogicalName);
            var toValue = entity.GetAttributeValue<OptionSetValue>(to.LogicalName);
            if (value != null)
            {
                if (ConvertValuesToGlobal && to.OptionSet.IsGlobal.GetValueOrDefault() && !from.OptionSet.IsGlobal.GetValueOrDefault())
                {
                    value = new OptionSetValue(ConvertLocalValueToGlobalValue(globalOSPrefix, value.Value).GetValueOrDefault());
                }

                if (!value.Equals(toValue))
                {
                    Trace(String.Format("Updating: {0} | {1} | {2}", entity.LogicalName, entity["name"], entity.Id));
                    entity.Attributes[to.LogicalName] = value;
                    requests.Add(new UpdateRequest() {Target = entity});
                }
            }
            else if (toValue != null)
            {
                Trace(String.Format("Updating: {0} | {1} | {2}", entity.LogicalName, entity["name"], entity.Id));
                entity.Attributes[to.LogicalName] = null;
                requests.Add(new UpdateRequest() { Target = entity });
            }
        }

        if (requests.Any())
        {
            PerformUpdates(service, requests);
        }

        Trace("Data Migration Complete", count, total);
    }

    private void PerformUpdates(IOrganizationService service, OrganizationRequestCollection requests)
    {
        if (SupportsExecuteMultipleRequest)
        {
            var response = (ExecuteMultipleResponse) service.Execute(
                new ExecuteMultipleRequest()
                {
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = false
                    },
                    Requests = requests,
                });

            if (response.IsFaulted)
            {
                var fault = response.Responses.First().Fault;
                while (fault.InnerFault != null)
                {
                    fault = fault.InnerFault;
                }

                var errorDetails = String.Empty;
                if (fault.ErrorDetails.ContainsKey("CallStack"))
                {
                    errorDetails = Environment.NewLine + fault.ErrorDetails["CallStack"];
                }

                errorDetails = String.Format("{0}{1}{1}TRACE TEXT:{1}{2}", errorDetails, Environment.NewLine, fault.TraceText);

                throw new Exception(fault.Message + errorDetails);
            }
        }
        else
        {
            foreach (var request in requests)
            {
                service.Save(((UpdateRequest) request).Target);
            }
        }
    }

    private static int? ConvertLocalValueToGlobalValue(string globalOSPrefix, int? value)
    {
        if (value.HasValue)
        {
            return int.Parse(globalOSPrefix + value.ToString().PadLeft(4, '0'));
        }
        else
        {
            return null;
        }
    }

    private int GetRecordCount(IOrganizationService service, AttributeMetadata from)
    {
        Trace("Retrieving {0} id attribute name", from.EntityLogicalName);
        var response = (RetrieveEntityResponse)service.Execute(new RetrieveEntityRequest() { LogicalName = from.EntityLogicalName, EntityFilters = EntityFilters.Entity });

        Trace("Determining record count (accurate only up to 50000)");
        var xml = String.Format(@"
        <fetch distinct='false' mapping='logical' aggregate='true'> 
            <entity name='{0}'> 
               <attribute name='{1}' alias='{1}_count' aggregate='count'/> 
            </entity> 
        </fetch>", from.EntityLogicalName, response.EntityMetadata.PrimaryIdAttribute);

        int total;
        try
        {
            var resultEntity = service.RetrieveMultiple(new FetchExpression(xml)).Entities.First();
            total = resultEntity.GetAliasedValue<int>(response.EntityMetadata.PrimaryIdAttribute + "_count");
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("AggregateQueryRecordLimit exceeded"))
            {
                total = 50000;
            }
            else
            {
                throw;
            }
        }

        return total;
    }

    private OptionSetAttributeContainer CreateTempAttribute(IOrganizationService service, AttributeMetadata oldAtt)
    {
        var optionSet = GetOptionSet(oldAtt);
        optionSet.MetadataId = null;
        optionSet.Name = optionSet.Name + TempPostfix;
        AttributeMetadata att = CloneAttribute(oldAtt, optionSet, n => n += TempPostfix);

        var createAttReq = new CreateAttributeRequest()
        {
            EntityName = att.EntityLogicalName,
            Attribute = att
        };

        try
        {
            var response = (CreateAttributeResponse)service.Execute(createAttReq);
            att.MetadataId = response.AttributeId;
        }
        catch
        {
            Trace("Error Creating Attribute " + att.LogicalName);
            throw;
        }

        // http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.publishxmlrequest.parameterxml.aspx

        PublishEntity(service, oldAtt.EntityLogicalName);
        return att;
    }

    private AttributeMetadata CloneAttribute(AttributeMetadata att, OptionSetMetadataBase optionSet, Func<string, string> convertName)
    {
        AttributeMetadata clone = CopyAttribute(att, optionSet);
        clone.CanModifyAdditionalSettings = att.CanModifyAdditionalSettings;
        clone.Description = att.Description;
        clone.DisplayName = att.DisplayName;
        clone.ExtensionData = att.ExtensionData;
        clone.IsAuditEnabled = att.IsAuditEnabled;
        clone.IsCustomizable = att.IsCustomizable;
        clone.IsRenameable = att.IsRenameable;
        clone.IsSecured = att.IsSecured;
        clone.IsValidForAdvancedFind = att.IsValidForAdvancedFind;
        clone.LinkedAttributeId = att.LinkedAttributeId;
        clone.RequiredLevel = att.RequiredLevel;

        // Fix for issue 1468 Inactive Language Causing Error
        RemoveInvalidLanguageLocalizedLabels(att.Description);
        RemoveInvalidLanguageLocalizedLabels(att.DisplayName);

        clone.LogicalName = convertName(att.LogicalName);
        clone.SchemaName = convertName(att.SchemaName);

        // Update EntityLogicalName for other methods to use
        SetEntityLogicalName(clone, att.EntityLogicalName);
        return clone;
    }

    private AttributeMetadata CopyAttribute(AttributeMetadata existingAtt, OptionSetMetadataBase optionSet)
    {
        AttributeMetadata att;
        switch (existingAtt.AttributeType.GetValueOrDefault())
        {
            case AttributeTypeCode.Boolean:
                var boolAtt = (BooleanAttributeMetadata)existingAtt;
                var tmpBool = new BooleanAttributeMetadata()
                {
                    DefaultValue = boolAtt.DefaultValue,
                    OptionSet = (BooleanOptionSetMetadata)optionSet,
                };

                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.Description);
                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.DisplayName);
                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.TrueOption.Description);
                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.TrueOption.Label);
                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.FalseOption.Description);
                RemoveInvalidLanguageLocalizedLabels(tmpBool.OptionSet.FalseOption.Label);
                att = tmpBool;
                break;

            case AttributeTypeCode.Picklist:
                att = new PicklistAttributeMetadata();
                break;

            case AttributeTypeCode.State:
                att = new StateAttributeMetadata();
                break;

            case AttributeTypeCode.Status:
                att = new StatusAttributeMetadata();
                break;

            default:
                throw new EnumCaseUndefinedException<AttributeTypeCode>(existingAtt.AttributeType.GetValueOrDefault());
        }

        EnumAttributeMetadata enumAtt = existingAtt as EnumAttributeMetadata;
        if (enumAtt != null)
        {
            var tmp = att as EnumAttributeMetadata;
            tmp.DefaultFormValue = enumAtt.DefaultFormValue;
            tmp.OptionSet = (OptionSetMetadata)optionSet;

            // Fix for issue 1468 Inactive Language Causing Error
            RemoveInvalidLanguageLocalizedLabels(tmp.OptionSet.Description);
            RemoveInvalidLanguageLocalizedLabels(tmp.OptionSet.DisplayName);
            foreach (var label in tmp.OptionSet.Options.Select(o => o.Label))
            {
                RemoveInvalidLanguageLocalizedLabels(label);
            }
            foreach (var description in tmp.OptionSet.Options.Select(o => o.Description))
            {
                RemoveInvalidLanguageLocalizedLabels(description);
            }
        }

        return att;
    }

    private void RemoveInvalidLanguageLocalizedLabels(Label label)
    {
        if (label == null)
        {
            return;
        }

        var labelsToRemove = new List<LocalizedLabel>();
        foreach (var local in label.LocalizedLabels)
        {
            if (!ValidLanguageCodes.Contains(local.LanguageCode))
            {
                labelsToRemove.Add(local);
            }
        }

        if (label.UserLocalizedLabel != null && !ValidLanguageCodes.Contains(label.UserLocalizedLabel.LanguageCode))
        {
            Trace("UserLocalizedLabel was invalid.  Removing Localization Label '{0}' for language code '{1}'", label.UserLocalizedLabel.Label, label.UserLocalizedLabel.LanguageCode);
            label.UserLocalizedLabel = null;
        }

        foreach (var local in labelsToRemove)
        {
            Trace("Removing Localization Label '{0}' for language code '{1}'", local.Label, local.LanguageCode);
            label.LocalizedLabels.Remove(local);
        }

        labelsToRemove.Clear();
    }

    private OptionSetMetadataBase GetOptionSet(AttributeMetadata att)
    {
        OptionSetMetadataBase optionSet = null;
        switch (att.AttributeType.GetValueOrDefault())
        {
            case AttributeTypeCode.Boolean:
                optionSet = ((BooleanAttributeMetadata)att).OptionSet;
                break;

            case AttributeTypeCode.Picklist:
            case AttributeTypeCode.EntityName:
            case AttributeTypeCode.State:
            case AttributeTypeCode.Status:
                optionSet = ((EnumAttributeMetadata)att).OptionSet;
                break;
        }
        return optionSet;
    }

    private void SetEntityLogicalName(AttributeMetadata att, string entityLogicalName)
    {
        var prop = att.GetType().GetProperty("EntityLogicalName");
        prop.SetValue(att, entityLogicalName);
    }

    private void PublishEntity(IOrganizationService service, string logicalName)
    {
        Trace("Publishing Entity " + logicalName);
        service.Execute(new PublishXmlRequest()
        {
            ParameterXml = "<importexportxml>"
          + "    <entities>"
          + "        <entity>" + logicalName + "</entity>"
          + "    </entities>"
          + "</importexportxml>"
        });
    }

    private void Trace(string message)
    {
        OnLog(message);
    }

    private void Trace(string messageFormat, params object[] args)
    {
        OnLog(String.Format(messageFormat, args));
    }

    private class OptionSetAttributeContainer
    {
        public AttributeMetadata Attribute { get; set; }
        public List<OptionMetadata> Options { get; set; }
        public OptionSetMetadataBase OptionSet { get; private set; }

        public string LogicalName { get { return Attribute.LogicalName; } }
        public string EntityLogicalName { get { return Attribute.EntityLogicalName; } }

        private OptionSetMetadataBase GetOptionSet(AttributeMetadata att)
        {
            OptionSetMetadataBase value = null;
            if (att != null)
            {
                switch (att.AttributeType.GetValueOrDefault())
                {
                    case AttributeTypeCode.Boolean:
                        var boolOptionSet = ((BooleanAttributeMetadata)att).OptionSet;
                        Options = new List<OptionMetadata>(){
                            boolOptionSet.FalseOption, boolOptionSet.TrueOption
                        };
                        value = boolOptionSet;
                        break;
                    case AttributeTypeCode.State:
                    //case AttributeTypeCode.EntityName:
                    case AttributeTypeCode.Picklist:
                    case AttributeTypeCode.Status:
                        var enumOptionSet = ((EnumAttributeMetadata)att).OptionSet;
                        Options = enumOptionSet.Options.ToList();
                        value = enumOptionSet;
                        break;
                    default:
                        throw new EnumCaseUndefinedException<AttributeTypeCode>(att.AttributeType.GetValueOrDefault());
                }
            }
            return value;
        }

        public static implicit operator OptionSetAttributeContainer(AttributeMetadata att)
        {
            var container = new OptionSetAttributeContainer() { Attribute = att };
            container.OptionSet = container.GetOptionSet(att);
            return container;
        }

        public static implicit operator AttributeMetadata(OptionSetAttributeContainer container)
        {
            return container.Attribute;
        }
    }

    private class AttributeMigrationState
    {
        public OptionSetAttributeContainer Old { get; set; }
        public OptionSetAttributeContainer Temp { get; set; }
        public OptionSetAttributeContainer New { get; set; }
        public OptionSetMetadataBase GlobalOptionSet { get; set; }
    }
}

}
`

DirectoryNotFoundException thrown when trying to generate OptionSets from command line

I am getting the following exception if I try to generate the code with the command line shown in thte output window. Part of the path seems to get duplicated (see DirectoryNotFoundException) The exception is:

`C:\Users*****\DLaB.Xrm.XrmToolBoxTools-Full\Plugins>"C:\Users**\DLaB.Xrm.XrmToolBoxTools-Full\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /namespace:"CrmEarlyBound" /out:"C:\Users**\DLaB.Xrm.XrmToolBoxTools-Full\CrmPackage\Plugins\PrdOptionSets.cs" /codecustomization:"DLaB.CrmSvcUtilExtensions.OptionSet.CreateOptionSetEnums,DLaB.CrmSvcUtilExtensions" /codegenerationservice
:"DLaB.CrmSvcUtilExtensions.OptionSet.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /
namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /connectionstring:"Url=http://**
***;Domain=**;UserName=sip;Password="
CrmSvcUtil : CRM Service Utility [Version 8.0.1.7297]
© 2015 Microsoft Corporation. All rights reserved

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users******\DLaB.Xrm.XrmToolBoxTools-Full\Plugins\Plugins\CrmSvcUtil Ref\alphabets'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileSystemEnumerableIterator1.CommonInit() at System.IO.FileSystemEnumerableIterator1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler1 resultHandler, Boolean checkHost) at System.IO.Directory.GetFiles(String path) at DLaB.CrmSvcUtilExtensions.OptionSet.Transliteration.TransliterationService.<>c.<.cctor>b__7_0() at System.Lazy1.CreateValue()
at System.Lazy1.LazyInitValue() at DLaB.CrmSvcUtilExtensions.NamingService.<>c.<Transliterate>b__28_0(LocalizedLabel x) at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate) at DLaB.CrmSvcUtilExtensions.NamingService.Transliterate(OptionMetadata optionMetadata, String defaultName) at DLaB.CrmSvcUtilExtensions.NamingService.GetDuplicateNameValues(OptionSetMetadataBase metadata, IServiceProvider services) at DLaB.CrmSvcUtilExtensions.NamingService.AppendValueForDuplicateOptionSetValueNames(OptionSetMetadataBase optionSetMetadata, String name, Nullable1 value, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.NamingService.GetNameForOption(OptionSetMetadataBase optionSetMetadata, OptionMetadata optionMetadata, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.NamingService.GetNameForOption(OptionSetMetadataBase optionSetMetadata, OptionMetadata optionMetadata, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService.GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildAttributeOptionSet(EntityMetadata entity, AttributeMetadata attribute, CodeTypeMember attributeMember, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildEntity(EntityMetadata entity, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildEntities(EntityMetadata[] entityMetadata, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.BuildCodeDom(IOrganizationMetadata organizationMetadata, String outputNamespace, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.Microsoft.Crm.Services.Utility.ICodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, S
tring outputNamespace, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.WriteInternal(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider s
ervices)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)`

Trying to convert local option set to global option set

and get the error ...

System.Exception: A validation error occurred. The value of 'new_crmsystem_t_' on record of type 'account' is outside the valid range.

The original field has some data and an option set.
I have created a new Global option set to migrate to

Tried twice with different names for the global option set - same error.

XrmToolBox connects to CRM Online, but early bound generation fails to connect

Downloaded the Full zip of of 2016.2.29.1, unblocked it and then unzipped it

Ran XrmToolBox, created a new connection to our CRM Online DEV instance using the unique name URL

Opened the early bound generator

Selected the list of entities to exclude ... the list was populated OK
Added all entities except for the one I was interested in
Then tried to create the code ...

And get an error ... Error : Connection to CRM is not established. Aborting process.

CRM Authentication Type Detected: OnlineFederation
Executing ... command line deleted ...
CrmSvcUtil : CRM Service Utility [Version 8.0.1.7297]
¸ 2015 Microsoft Corporation. All rights reserved

Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Connection to CRM is not established. Aborting process.
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : InvokeMethod
Date : 17:56:54
Time : 08/03/2016
Error : Exception has been thrown by the target of an invocation.
Stack Trace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Inner Exception Level 1 :
Source : CrmSvcUtil
Method : Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata
Date : 17:56:54
Time : 08/03/2016
Error : Connection to CRM is not established. Aborting process.
Stack Trace : at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()

at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)

Support for German Labels

I have added a file called 1031.json in the alphabet subfolder containing the following text:
{
"code": 1031,
"language": "German",
"alphabet": [
[ "Ä", "Ae" ],
[ "Ö", "Oe" ],
[ "Ü", "Ue" ],
[ "ä", "ae" ],
[ "ö", "oe" ],
[ "ü", "ue" ],
[ "ß", "ss" ]
]
}

This led to CRM systems with only German labels being supported.
It would be great to include this file in further versions.

Regards
Klemens

Command Line Output in OptionSets file is incorrect

When I generate a file with the option sets, the command line code generated and put into the file is not the command line that will generate the option sets file, but the command line that will generate the Entities file.

Generated Account.cs Entity cannot find AccountState (StateCodeEnum)

The following lines are giving me errors in my Account.cs

[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statecode")]
public virtual AccountState? StateCodeEnum
{
    [System.Diagnostics.DebuggerNonUserCode()]
    get
    {
        return ((AccountState?)(EntityOptionSetEnum.GetEnum(this, "statecode")));
    }
    [System.Diagnostics.DebuggerNonUserCode()]
    set
    {
        StateCode = (int?)value;
    }
}

The error is

The type or namespace name 'AccountState' could not be found (are you missing a using directive or an assembly reference?)

I generated all the OptionSets and there is no AccountState.cs file in the OptionsSets directory.

This same error appears for all state properties of any Entity I create using the plugin.

Do I need to manually create all these StateCode enums? I don't think I really need them for my application so I could remove them, but I would need to remove them each time I regenerate the files.

Relationships are created even if the entity has been skipped

When generating only selected entities, the relationships to these entities are still generated.
For example, in Account.cs there is the following relationship to Invoice even if I skipped the Invoice entity:

/// <summary>
/// 1:N invoice_customer_accounts
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("invoice_customer_accounts")]
public System.Collections.Generic.IEnumerable<Identicar.BtB.Common.Entities.Invoice> invoice_customer_accounts
{
    [System.Diagnostics.DebuggerNonUserCode()]
    get
    {
        return this.GetRelatedEntities<Identicar.BtB.Common.Entities.Invoice>("invoice_customer_accounts", null);
    }
    [System.Diagnostics.DebuggerNonUserCode()]
    set
    {
        this.OnPropertyChanging("invoice_customer_accounts");
        this.SetRelatedEntities<Identicar.BtB.Common.Entities.Invoice>("invoice_customer_accounts", null, value);
        this.OnPropertyChanged("invoice_customer_accounts");
    }
}

These relationships must not be generated otherwise it leads to compilation errors.

Also, it will be wonderful if you can add an option for disabling the generation of the relationships, indeed I never use them in my code.

Error on entity generation

I had your excellent plugin working, but after (I guess) configuration in CRM I only receives this error message every time I try to run the entity generator

Exception attempting to GetDictionaryList for config key: duplicaterule,BaseEntityTypeCode,MatchingEntityTypeCode|invoicedetail,InvoiceStateCode|leadaddress,AddressTypeCode,ShippingMethodCode|organization,CurrencyFormatCode,DateFormatCode,TimeFormatCode,WeekStartDayCode|quote,StatusCode|quotedetail,QuoteStateCode|salesorderdetail,SalesOrderStateCode|DuplicateRule,BaseEntityTypeCode,MatchingEntityTypeCode|InvoiceDetail,InvoiceStateCode|LeadAddress,AddressTypeCode,ShippingMethodCode|Organization,CurrencyFormatCode,DateFormatCode,TimeFormatCode,WeekStartDayCode|Quote,StatusCode|QuoteDetail,QuoteStateCode|SalesOrderDetail,SalesOrderStateCode
System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at DLaB.CrmSvcUtilExtensions.ConfigHelper.GetDictionaryList(String value, Boolean lowerCaseValues)
System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at DLaB.CrmSvcUtilExtensions.ConfigHelper.GetDictionaryList(String value, Boolean lowerCaseValues)
   at DLaB.CrmSvcUtilExtensions.Entity.EnumPropertyGenerator.InitializeMappings()
   at DLaB.CrmSvcUtilExtensions.Entity.EnumPropertyGenerator.CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
   at DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService.CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
   at Microsoft.Crm.Services.Utility.CodeGenerationService.WriteFile(String outputFile, String language, CodeNamespace codenamespace, ServiceProvider serviceProvider)
   at Microsoft.Crm.Services.Utility.CodeGenerationService.Microsoft.Crm.Services.Utility.ICodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String outputNamespace, IServiceProvider services)
   at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.WriteInternal(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)
   at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)

Unable to compile

Hi Darryl, I'm unable to compile this project, I'm not clear on why, I have the 4.5.2 targetting pack installed. Here is a screenshot of the failing lines: http://screencast.com/t/1X1k51I5u8

Clearly the compiler is not understanding the => in the variable declaration, but I don't know why. Can you help with this?

Error when trying to create OptionSets.cs

Hi Daryl

I installed your plugin in the XRM Toolbox. When I try to generate the OptionSet.cs I get an error message.

Output file was not updated or not found! C:\XrmToolBox\Plugins\CrmSvcUtil Ref\OptionSets.cs

See full output below:

When I tried to run your plugin the first time there was a warning regarding my .NET framework. I had to update it. I installed version 4.6. Is this supported at all?

Many thanks
Alen

CRM Authentication Type Detected: ActiveDirectory
Executing "C:\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /namespace:"SGAM2.AgreementRequest" /out:"C:\XrmToolBox\Plugins\CrmSvcUtil Ref\OptionSets.cs" /codecustomization:"DLaB.CrmSvcUtilExtensions.OptionSet.CreateOptionSetEnums,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.OptionSet.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions"
CrmSvcUtil : CRM Service Utility [Version 8.0.0.7134]
¸ 2015 Microsoft Corporation. All rights reserved

Options:
/nologo
Suppresses the banner.

/language:
The language to use for the generated proxy code. This can be either 'CS' or 'VB'. The default language is 'CS'. Short form is '/l:'.

/url:
A url or path to the SDK endpoint to contact for metadata.

/out:
The filename for the generated proxy code. Short form is '/o:'.

/namespace:
The namespace for the generated proxy code. The default namespace is the global namespace. Short form is '/n:'.

/interactivelogin:
Presents a login dialog to loginto the service with, if passed all other connect info is ignored. Short form is '/il:'.

/connectionstring:
Connection String to use when connecting to CRM. If provided, all other connect info is ignored. Short form is '/connstr:'.

/username:
Username to use when connecting to the server for authentication. Short form is '/u:'.

/password:
Password to use when connecting to the server for authentication. Short form is '/p:'.

/domain:
Domain to authenticate against when connecting to the server. Short form is '/d:'.

/serviceContextName:
The name for the generated service context. If a value is passed in, it will be used for the Service Context. If not, no Service Context will be generated

/help
Show this usage message. Short form is '/?'.

/generateActions
Generate wrapper classes for custom actions Short form is '/a'.

/deviceid:
Device ID to use when connecting to the online server for authentication. Short form is '/di:'.

/devicepassword:
Device Password to use when connecting to the online server for authentication. Short form is '/dp:'.

Example:
crmsvcutil.exe /url:http://localhost/Organization1/XRMServices/2011/Organization.svc /out:GeneratedCode.cs

Output file was not updated or not found! C:\XrmToolBox\Plugins\CrmSvcUtil Ref\OptionSets.cs

Handle StatusCodes that are duplicate names for inactive/active

Status Codes are dependent on the State code, and generally duplicate text values are created, which results in "Label_Number". this should be changed to "Label_Active" or "Label_Inactive"

Maybe think about changing the text for different languages?

Unable to generate classes as trying to connect to Office 365

Hello,
Apologies, this is based on #24
I was unable to respond before the thread was closed, so here goes.
When I run the Early bound generator, I get the below message
When I run the tool, I get the below

CRM Authentication Type Detected: Federation
Executing "C:\Users\philst\Downloads\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /url:"/XRMServices/2011/Organization.svc" /namespace:"Core.Crm" /out:"C:\Users\philst\Downloads\CrmContext.cs" /servicecontextname:"CrmContext" /codecustomization:"DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /metadataproviderservice:"DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /username:"" /password:"**********"
CrmSvcUtil : CRM Service Utility [Version 8.0.1.7297]
¸ 2015 Microsoft Corporation. All rights reserved

Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (North America) URI is = https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Europe, Middle East and Africa) URI is = https://disco.crm4.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Asia Pacific Area) URI is = https://disco.crm5.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (South America) URI is = https://disco.crm2.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Oceania) URI is = https://disco.crm6.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Japan) URI is = https://disco.crm7.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (North America 2) URI is = https://disco.crm9.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (Canada) URI is = https://disco.crm3.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Exception while trying to connect Discovery Server, (India) URI is = https://disco.crm8.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : No Orgs Found, Searched Online. Region Setting =
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Connection to CRM is not established. Aborting process.
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstanceTIService
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : InvokeMethod
Date : 10:49:49
Time : 22/03/2016
Error : Exception has been thrown by the target of an invocation.
Stack Trace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstanceTIService
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Inner Exception Level 1 :
Source : CrmSvcUtil
Method : Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata
Date : 10:49:49
Time : 22/03/2016
Error : Connection to CRM is not established. Aborting process.
Stack Trace : at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()

at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)

Output file was not updated or not found! C:\Users\philst\Downloads\CrmContext.cs

Apologies for the delay and thank you

Multilanguage support for optionsets

Not as much an issue as a question,
I have a multilingual environment and I was wondering if it is possible to generate Enums for the translated options as well?

Problems with CRM 2016

The tool seems to be having trouble with a 2016 onprem org. This used to work fine in 2015. It throws an error that the crm context .cs file is missing. It adds new entities it finds but does not update entities with new properties.

Let me know if you need more information.

Exception when adding Actions to skip (opening window "Specify Actions")

DLaB.Common.Exceptions.TypeArgumentException: 'Entity' is an invalid type for T. Please use the LateBoundQuerySettings.
at DLaB.Xrm.QuerySettings`1..ctor()
at DLaB.Xrm.QueryExpressionFactory.Create[T](ColumnSet columnSet, Object[] columnNameAndValuePairs)
at DLaB.XrmToolboxCommon.DialogBase.b__13_0(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

Difficulties with Connection to Online Sandbox + resolution

I connected to my organization's O365 Online CRM sandbox today for the first time in months, and couldn't connect, with the SvcUtil throwing "System.Exception: Connection to CRM is not established. Aborting process." This despite a successful connection for other plugins in the Toolbox.

After reading various posts on similar issues, I found the workaround is to switch the command line's /url parameter (or the <OrganizationServiceUrl> value in the mscrmtools2011.config file) for one using the org unique name instead of the friendly name:

  • original: /url:"https://friendlysandbox.api.crm4.dynamics.com/XRMServices/2011/Organization.svc"
  • new: /url:"https://org1234abcd.api.crm4.dynamics.com/XRMServices/2011/Organization.svc"

I'm not sure whether this is a problem with how the <OrganizationServiceUrl> is stored at the Toolbox level, or the plugin needs to deal with fudging the URL to allow the SvcUtil tool to work, but I hope the workaround is useful for someone in the meantime.

Running Early Bound Generator against org that has a non-standard port does not work

This is an on-prem org with AD auth. The connection string that the tool generates does not include the port specified by the connection, so connectivity to the org fails. I have two different connection setups in XrmToolbox: 1) normal wizard which uses my current AD creds and 2) connection string. Both have the same problem. I am using the latest toolbox (1.2016.6.29) and latest EBG (1.2016.6.1). If I take the command line that gets generated and modify it to include the port, both connection types successfully generate the code.

Using Current Credentials is missing UserName

Message from @JurgenPostelmans in Issue: Difficulties with Early Bound Generator #43

@daryllabar I just tried the new version and it could successfully generate the entities, option sets and actions in C#.

One strange thing however was that in my connection settings in XrmToolbox I have "Use your current credentials" checked and your plugin asked me for the password when I pressed the "Create All" button.
In the output below you can see that Username is empty in the connection string but password is there. Cloud be that this is the expected behavior?

CRM Authentication Type Detected: ActiveDirectory
Executing "C:\Users\Administrator\Downloads\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /generateActions /out:"C:\Users\Administrator\Downloads\XrmToolBox\Plugins\CrmSvcUtil Ref\Actions.cs" /namespace:"CrmEarlyBound" /codecustomization:"DLaB.CrmSvcUtilExtensions.Action.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.Action.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.Action.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /connectionstring:"Url=http://springfield:5555/U2U;UserName=;Password=_"
Executing "C:\Users\Administrator\Downloads\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /namespace:"CrmEarlyBound" /out:"C:\Users\Administrator\Downloads\XrmToolBox\Plugins\CrmSvcUtil Ref\OptionSets.cs" /codecustomization:"DLaB.CrmSvcUtilExtensions.OptionSet.CreateOptionSetEnums,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.OptionSet.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions" /connectionstring:"Url=http://springfield:5555/U2U;UserName=;Password=
_"

Option set on model class specifies wrong enum name for global option sets

I have an entity with a global option set on it. Here's the property that gets generated for it:

[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("xyz_addressescode")]
public virtual xyz_DynamicOptionSet? xyz_AddressesCodeEnum
{
    // ...snip...
}

Here's the enum for the global option set:

[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "8.0.1.7297")]
public enum xyz_DynamicOptionSetEnum
{
    // ...snip...
}

These don't link together correctly because the enum is called xyz_DynamicOptionSetEnum whereas the type of the property is xyz_DynamicOptionSet?. Either the return type of the property should be xyz_DynamicOptionSetEnum? or the global option set shouldn't have the Enum suffix.

This seems to only be an issue for global option sets. I'm using 1.2016.3.30, but this is not a new problem.

Great tool, cheers.

Generate File Diff Export File

Currently the Entities, OptionSets, and Actions run in parallel. This causes race conditions if attempts are made to update the project file, by adding new files. Instead of updating TFS generate diff XML that can then be loaded and ran not in parallel.

Connection error OnlineFederation

When creating a connection with the latest XRMToolBox to an online instance that uses federated AD or Azure AD (see "Known Issue" at https://github.com/MscrmTools/XrmToolBox/wiki/Connecting-to-a-Microsoft-Dynamics-CRM-deployment), the connection needs to use the unique org name instead of the named alias.

Everything connects fine this way, but the generated command line ends up using the named alias for the URL instead of the unique name, eg 'https://customernameDev.crm... instead of https://customername0.crm.... Copying the generated command line and updating the URL parameter to use the unique org name makes everything work.

Here is the stack trace that it kicks back:
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: Connection to CRM is not established. Aborting process.
at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source : mscorlib
Method : InvokeMethod
Date : 10:04:16 AM
Time : 2/24/2016
Error : Exception has been thrown by the target of an invocation.
Stack Trace : at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
at Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()

at Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)

Inner Exception Level 1 :
Source : CrmSvcUtil
Method : Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata
Date : 10:04:16 AM
Time : 2/24/2016
Error : Connection to CRM is not established. Aborting process.
Stack Trace : at Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()

at DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)

Unable to compile source code or use precompiled release

Hi Darryl, I'm really struggling to get this working!!

Firstly, I cloned the git repo and opened in Visual Studio 2015 (14.0.25123.00 Update 2), and did a build. I get many warning about unresolved references, here are the first 4, there are many more. Note that NuGet did download many packages, here's a screenshot of my packages folder: http://screencast.com/t/OENePRpF

Warning Could not resolve this reference. Could not locate the assembly "Microsoft.WindowsAzure.Configuration". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. DLaB.CrmSvcUtilExtensions
Warning Could not resolve this reference. Could not locate the assembly "Microsoft.TeamFoundation.Test.WebApi". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. DLaB.CrmSvcUtilExtensions
Warning The referenced component 'Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms' could not be found. DLaB.CrmSvcUtilExtensions
Warning Could not resolve this reference. Could not locate the assembly "Microsoft.TeamFoundation.Build2.WebApi". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. DLaB.CrmSvcUtilExtensions

Secondly, I went to your releases section and downloaded https://github.com/daryllabar/DLaB.Xrm.XrmToolBoxTools/releases/download/2016.6.1.1/DLaB.Xrm.XrmToolBoxTools.1.2016.6.1.nupkg - I wasn't sure how to deal with a nupkg file on it's own but 7zip seemed to extract it without problems. In the lib\net452\plugins folder there seem to be your compiled plugins, but this folder contains another sub-folder "CrmSvcUtil%20Ref" - the %20 looks odd in a folder name. So I left this alone.

Thirdly, I downloaded https://github.com/daryllabar/DLaB.Xrm.XrmToolBoxTools/releases/download/2016.3.30.1/DLaB.XrmToolBoxTools.Full.zip and extracted it. I ran the XrmToolBox.exe file I found there. I tried to create a new connection entering the organization url I see when connecting in the browser as it says on the dialog box (ie. https://{orgname}.crm4.dynamics.com), I entered a username and password and got this error: http://screencast.com/t/sfdwLrRglsf

So I went back and entered the org unique name instead of the org friendly name in the URL but got exactly the same error.

I clicked on the link to try and connect using a connection string, using the connection string https://{orgname}.crm4.dynamics.com;{org unique Id}, but got this error: http://screencast.com/t/w6H7zqhX

Fourthly I tried to copy your dll's into the plugin folder of the version of XrmToolbox which I have which does work (v1.2015.11.5) but get the error "System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'" when opening XrmToolBox.exe. Clearly there will be version conflicts here, I'm guessing this will never work.

Ideally I'd like to sort out the source code references and work with that. I don't see anybody else here having similar issues which seems strange, I don't understand why I would be having these issues when nobody else does! Any ideas?

Regards, Ben

Fix Serialization Issues

The EarlyBoundEntityGenerator Settings file is attempting to read the settings differently than what it should.

Integrate the CRM Mobile Development

Currently Windows RT does not support some of the features of the standard generated Entities. Microsoft has created a Code DOM Service for generating Entities that are supported for RT and their for Mobile development. (See here)

If this is something you will find useful, please comment on this issue. Currently I'm not planning on implementing it, unless there is interest in it.

Attribute Manager doesn't Handle Plugin Steps or Images

Recieved error when attempting to delete an attribute...

Checking for Delete Dependencies for lead.new_paymentprocessed
System.Exception: Dependencies found:
SDKMessageProcessingStepImage 97cd4051-b422-e611-80f3-3863bb36bd38
SDKMessageProcessingStep b1d45b42-b422-e611-80f3-3863bb36bd38
SDKMessageProcessingStep a0d14d8a-ad05-e611-80f3-3863bb36edb0
at DLaB.AttributeManager.Logic.AssertCanDelete(IOrganizationService service, AttributeMetadata attribute)
at DLaB.AttributeManager.Logic.MigrateAttribute(AttributeMetadata fromAtt, AttributeMetadata toAtt, Action actions)
at DLaB.AttributeManager.Logic.MigrateToTemp(Steps stepsToPerform, AttributeMetadata oldAtt, AttributeMetadata tmpAtt, Action actions)
at DLaB.AttributeManager.Logic.Run(AttributeMetadata att, String newAttributeSchemaName, Steps stepsToPerform, Action actions, AttributeMetadata newAttributeType)
at DLaB.AttributeManager.AttributeManagerPlugin.<>c.b__38_2(BackgroundWorker w, DoWorkEventArgs e)

Plugin Images and Plugin Steps should be updated when migrating an attribute.

Create DebuggerDisplay Class Attributes

I'm thinking it would be useful to add DebuggerDisplay attributes to entities that default to the name of the attribute.

It would also be nice to be able to define your own DebuggerDisplay strings per entity.

Feel free to comment, if this is something that would benefit you so I can prioritize it.

Where to find .dll for XrmToolBox?

Hi Daryl

Where can I find the lastet .exe / dll files for the the CRM Early Bound generator ? On Github or Codeplex? I understand the version on Codeplex is outdated.

Many thanks
Alen

Selecting Optionsets to skip

Isn't there a way to cherry pick the option sets I want to generate opposed to the list of the ones I want to skip? It seems extremely tedious to generate the negative list, since I have to go through a dialog for every singele option set I want to skip and the list is long.

Could not load file or assembly 'DLaB.Xrm, Version=1.0.0.0

Just downloaded latest "Full" from ... https://github.com/daryllabar/DLaB.Xrm.XrmToolBoxTools/releases/tag/v2016.2.6.1
Unblocked the zip and extracted to folder
Ran XrmToolBox, created a new connection to our dev instance of CRM Online
Opened the Early Bound Generator, and clicked the Entities to Skip ...

After a bit of time, get error dialog ...

************** Exception Text **************
System.IO.FileNotFoundException: Could not load file or assembly 'DLaB.Xrm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fbff471681eb6c24' or one of its dependencies. The system cannot find the file specified.
File name: 'DLaB.Xrm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=fbff471681eb6c24'
at DLaB.XrmToolboxCommon.Extensions.<>c.b__2_0(EntityMetadata e)
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.OrderedEnumerable1.d__1.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source) at DLaB.EarlyBoundGenerator.SpecifyEntitiesDialog.LoadEntities(IEnumerable1 entities)
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)

I added in a copy of the MsCrmTools.MetadataDocumentGenerator plugin and it successfully brought back a list of the CRM entities

Cheers,
SteveC.

Error while creating entities using Xrm Client

I downloaded the standalone in the latest PreRelease (2016.2.23.2)

When I try to create my entities I check "Use Xrm Client" but once I try to create entities with this option checked, I get an error. I'm connected to my 2015 online project and we're about to update to 2016. We have set up an on prem 2016 project to test this with as well, but without success. I get the same error as below.

System.TypeInitializationException: The type initializer for 'Microsoft.Xrm.Client.CodeGeneration.CodeCustomization' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Xrm.Client, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Het systeem kan het opgegeven bestand niet vinden.
at Microsoft.Xrm.Client.CodeGeneration.CodeCustomization..cctor()
--- End of inner exception stack trace ---
at Microsoft.Xrm.Client.CodeGeneration.CodeCustomization.CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService.CustomizeCodeDom(CodeCompileUnit codeUnit, IServiceProvider services)
at Microsoft.Crm.Services.Utility.CodeGenerationService.WriteFile(String outputFile, String language, CodeNamespace codenamespace, ServiceProvider serviceProvider)
at Microsoft.Crm.Services.Utility.CodeGenerationService.Microsoft.Crm.Services.Utility.ICodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String outputNamespace, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.WriteInternal(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)
at DLaB.CrmSvcUtilExtensions.BaseCustomCodeGenerationService.Write(IOrganizationMetadata organizationMetadata, String language, String outputFile, String targetNamespace, IServiceProvider services)
Output file was not updated or not found!
\Plugins\CrmSvcUtil Ref\Entities.cs

Command Line Output in OptionSets file is incorrect

The command line output to the generated file when generation options sets is not the command line needed to regenerate the option sets. Instead the command line to regenerate the entities is put into the file.

Error When Generating Code on a Virtual Machine with no audio device

Our dev machine has no audio devices (it is virtual anyway). Please remove speech synthesis reference: wile nice, this is rather irrelevant for generating code.

System.Speech.Internal.Synthesis.AudioException: Audio device error encountered. - Error Code: 0x2
at System.Speech.Internal.Synthesis.VoiceSynthesis.Speak(Prompt prompt)

Problem with CRM 2016 on premises with ADFS

Hello Daryl,

I use the early bound generator on the following environment : CRM 2016, on premises, with ADFS.
The following exception appeared after generating the Entities files :

Executing "C:\Users\cmarty\Documents\XrmToolBox\Plugins\CrmSvcUtil Ref\crmsvcutil.exe" /url:"https://internaldevcrm2k15.identicar.fr:444/BTBDev/XRMServices/2011/Organization.svc" /namespace:"Identicar.BtB.Entities" /out:"C:\Users\cmarty\Desktop\Entities\CrmServiceContext.cs" /servicecontextname:"CrmServiceContext" /codecustomization:"DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions" /codegenerationservice:"DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions" /codewriterfilter:"DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions" /namingservice:"DLaB.CrmSvcUtilExtensions.Entity.OverridePropertyNames,DLaB.CrmSvcUtilExtensions" /metadataproviderservice:"DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions" /username:"cmarty" /password:"********" /domain:"identicar" 
CrmSvcUtil : CRM Service Utility [Version 8.0.0.7134]
¸ 2015 Microsoft Corporation. All rights reserved

Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Organization not found. Org = BTBDev/
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Unable to Login to Dynamics CRM
CrmSvcUtil Error: 2 : Exiting program with exit code 2 due to exception : System.Reflection.TargetInvocationException: Une exception a ‚t‚ lev‚e par la cible d'un appel. ---> System.Exception: Connection to CRM is not established. Aborting process.
   … Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
   … DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
   --- Fin de la trace de la pile d'exception interne ---
   … System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   … System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   … Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
   … Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
CrmSvcUtil Error: 2 : ===== DETAIL ======
CrmSvcUtil Error: 2 : Source    : mscorlib
Method  : InvokeMethod
Date    : 15:41:58
Time    : 10/02/2016
Error   : Une exception a ‚t‚ lev‚e par la cible d'un appel.
Stack Trace : … System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   … System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   … Microsoft.Crm.Services.Utility.ServiceFactory.CreateInstance[TIService](TIService defaultServiceInstance, String parameterValue, CrmSvcUtilParameters parameters)
   … Microsoft.Crm.Services.Utility.ServiceProvider.InitializeServices(CrmSvcUtilParameters parameters)
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.get_ServiceProvider()
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.Run()
   … Microsoft.Crm.Services.Utility.CrmSvcUtil.Main(String[] args)
======================================================================================================================
Inner Exception Level 1 : 
Source  : CrmSvcUtil
Method  : Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata
Date    : 15:41:58
Time    : 10/02/2016
Error   : Connection to CRM is not established. Aborting process.
Stack Trace : … Microsoft.Crm.Services.Utility.SdkMetadataProviderService.Microsoft.Crm.Services.Utility.IMetadataProviderService.LoadMetadata()
   … DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService..ctor(IMetadataProviderService defaultService, IDictionary`2 paramters)
======================================================================================================================

Output file was not updated or not found!  C:\Users\cmarty\Desktop\Entities\CrmServiceContext.cs

This organization was updated from CRM 2015 and, at that time, it generated successfully the files. After the update to CRM 2016 it doesn't work anymore.

As the #12 issue's message was different I opened a new issue.

Let me know if you need more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.