/// <summary>
        /// Obtains the organization service proxy.
        /// </summary>
        /// <param name="serverConfiguration"></param>
        /// <returns></returns>
        public static OrganizationServiceProxy GetOrganizationProxy(
            ServerConnection.Configuration serverConfiguration)
        {
            // Obtain the organization service proxy for the Federated, LiveId, and OnlineFederated environments.
            if (serverConfiguration.OrganizationServiceManagement != null
                && serverConfiguration.OrganizationTokenResponse != null)
            {
                return new OrganizationServiceProxy(
                    serverConfiguration.OrganizationServiceManagement,
                    serverConfiguration.OrganizationTokenResponse);
            }

            if (serverConfiguration.OrganizationServiceManagement == null)
                throw new ArgumentNullException("serverConfiguration.OrganizationServiceManagement");

            // Obtain the organization service proxy for the ActiveDirectory environment.
            return new OrganizationServiceProxy(
                serverConfiguration.OrganizationServiceManagement,
                serverConfiguration.Credentials);
        }
 public RibbonItemHelper(OrganizationServiceProxy serviceProxy, ServerConnection.Configuration serverConfig)
 {
     _serviceProxy = serviceProxy;
     _serverConfig = serverConfig;
 }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
               {
            //<snippetExportRibbonXml1>
            // Connect to the Organization service.
            // The using statement assures that the service proxy will be properly disposed.
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
             // This statement is required to enable early-bound type support.
             _serviceProxy.EnableProxyTypes();

             //Create export folder for ribbon xml files if not already exist.
             if (!Directory.Exists(exportFolder))
             Directory.CreateDirectory(exportFolder);

             //<snippetExportRibbonXml3>
             //Retrieve the Appliation Ribbon
             RetrieveApplicationRibbonRequest appribReq = new RetrieveApplicationRibbonRequest();
             RetrieveApplicationRibbonResponse appribResp = (RetrieveApplicationRibbonResponse)_serviceProxy.Execute(appribReq);

             System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml");
             File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml));
             //</snippetExportRibbonXml3>
             //Write the path where the file has been saved.
             Console.WriteLine(applicationRibbonPath);
             //<snippetExportRibbonXml4>
             //Retrieve system Entity Ribbons
             RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest() { RibbonLocationFilter = RibbonLocationFilters.All };

             #region retrieval code

            bool isDone = false;
            while (!isDone)
            {
            Console.WriteLine("\nRetrieve all ribbons or specific ribbons? (a)ll/(s)pecific: ");
            string input = Console.ReadLine();

            if (input == "a")
            {

                foreach (System.String entityName in entitiesWithRibbons)
                {
                    entRibReq.EntityName = entityName;
                    RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                    System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml");
                    File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                    //Write the path where the file has been saved.
                    Console.WriteLine(entityRibbonPath);
                }

                //</snippetExportRibbonXml4>

                //<snippetExportRibbonXml5>
                //Check for custom entities
                RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity };

                RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

                foreach (EntityMetadata em in resp.EntityMetadata)
                {
                    if (em.IsCustomEntity == true && em.IsIntersect == false)
                    {
                        entRibReq.EntityName = em.LogicalName;
                        RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                        System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml");
                        File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                        //Write the path where the file has been saved.
                        Console.WriteLine(entityRibbonPath);
                    }
                }

                isDone = true;
            }
            else if (input == "s")
            {
                // first do system entities
                int i = 0;
                foreach (System.String entityName in entitiesWithRibbons)
                {
                    Console.WriteLine("[{0}] {1}", i++, entityName);
                }
                Console.WriteLine("Enter the numbers of the entities to download, separated by commas: ");
                string entityNums = Console.ReadLine();
                string[] entityNumsArr = entityNums.Split(new char[] { ',' });

                foreach (string numStr in entityNumsArr)
                {
                    int num;
                    if (Int32.TryParse(numStr, out num))
                    {
                        if (num >= 0 && num < entitiesWithRibbons.Length)
                        {
                            string entityName = entitiesWithRibbons[num];
                            entRibReq.EntityName = entityName;
                            RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                            System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml");
                            File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                            //Write the path where the file has been saved.
                            Console.WriteLine(entityRibbonPath);
                        }
                        else
                        {
                            Console.WriteLine("No element index {0} in entitiesWithRibbons, skipping...", num);
                        }
                    }
                }

                // next check for custom entities
                RetrieveAllEntitiesRequest raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity };
                RetrieveAllEntitiesResponse resp = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(raer);

                i = 0;
                foreach (EntityMetadata em in resp.EntityMetadata)
                {
                    if (em.IsCustomEntity == true && em.IsIntersect == false)
                    {
                        Console.WriteLine("[{0}] {1}", i, em.LogicalName);
                    }
                    i++;
                }
                Console.WriteLine("Enter the numbers of the entities to download, separated by commas: ");
                entityNums = Console.ReadLine();
                entityNumsArr = entityNums.Split(new char[] { ',' });

                //foreach (EntityMetadata em in resp.EntityMetadata)
                foreach (string numStr in entityNumsArr)
                {
                    int index;
                    if (Int32.TryParse(numStr, out index))
                    {
                        if (index >= 0 && index < resp.EntityMetadata.Length)
                        {
                            EntityMetadata em = resp.EntityMetadata[index];
                            if (em.IsCustomEntity == true && em.IsIntersect == false)
                            {
                                entRibReq.EntityName = em.LogicalName;
                                RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)_serviceProxy.Execute(entRibReq);

                                System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml");
                                File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml));
                                //Write the path where the file has been saved.
                                Console.WriteLine(entityRibbonPath);
                            }
                        }
                    }
                }
                Console.WriteLine("");

                isDone = true;
            }

            }
             #endregion
            }
            //</snippetExportRibbonXml5>
            //</snippetExportRibbonXml1>
               }

               // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
               catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
               {
            // You can handle an exception here or pass it back to the calling method.
            throw;
               }
        }