Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// viewId;entityLogicalName;viewName;ViewType;Type;LCID1;LCID2;...;LCODX
        /// </example>
        /// <param name="entities"></param>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        public void Export(List <EntityMetadata> entities, List <int> languages, ExcelWorksheet sheet, IOrganizationService service, ExportSettings settings)
        {
            var line = 0;
            var cell = 0;

            AddHeader(sheet, languages);

            var crmViews = new List <CrmView>();

            foreach (var entity in entities.OrderBy(e => e.LogicalName))
            {
                if (!entity.MetadataId.HasValue)
                {
                    continue;
                }

                var views = RetrieveViews(entity.LogicalName, entity.ObjectTypeCode.Value, service);

                foreach (var view in views)
                {
                    var crmView = crmViews.FirstOrDefault(cv => cv.Id == view.Id);
                    if (crmView == null)
                    {
                        crmView = new CrmView
                        {
                            Id           = view.Id,
                            Entity       = view.GetAttributeValue <string>("returnedtypecode"),
                            Type         = view.GetAttributeValue <int>("querytype"),
                            Names        = new Dictionary <int, string>(),
                            Descriptions = new Dictionary <int, string>()
                        };
                        crmViews.Add(crmView);
                    }

                    RetrieveLocLabelsRequest  request;
                    RetrieveLocLabelsResponse response;

                    if (settings.ExportNames)
                    {
                        // Names
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "name",
                            EntityMoniker = new EntityReference("savedquery", view.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmView.Names.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }

                    if (settings.ExportDescriptions)
                    {
                        // Descriptions
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "description",
                            EntityMoniker = new EntityReference("savedquery", view.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmView.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }
                }
            }

            foreach (var crmView in crmViews.OrderBy(cv => cv.Entity).ThenBy(cv => cv.Type))
            {
                if (settings.ExportNames)
                {
                    line++;
                    cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = _viewTypes.ContainsKey(crmView.Type) ?_viewTypes[crmView.Type] : crmView.Type.ToString();
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Name";

                    foreach (var lcid in languages)
                    {
                        var name = crmView.Names.FirstOrDefault(n => n.Key == lcid);
                        if (name.Value != null)
                        {
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = name.Value;
                        }
                        else
                        {
                            cell++;
                        }
                    }
                }

                if (settings.ExportDescriptions)
                {
                    line++;
                    cell = 0;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = _viewTypes.ContainsKey(crmView.Type) ? _viewTypes[crmView.Type] : crmView.Type.ToString();
                    ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                    foreach (var lcid in languages)
                    {
                        var desc = crmView.Descriptions.FirstOrDefault(n => n.Key == lcid);
                        if (desc.Value != null)
                        {
                            ZeroBasedSheet.Cell(sheet, line, cell++).Value = desc.Value;
                        }
                        else
                        {
                            cell++;
                        }
                    }
                }
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i <= line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
Пример #2
0
        public void Export(List <int> languages, ExcelWorkbook file, IOrganizationService service)
        {
            // Retrieve current user language information
            var setting = GetCurrentUserSettings(service);

            var userSettingLcid = setting.GetAttributeValue <int>("uilanguageid");
            var currentSetting  = userSettingLcid;

            var crmForms        = new List <CrmForm>();
            var crmFormTabs     = new List <CrmFormTab>();
            var crmFormSections = new List <CrmFormSection>();
            var crmFormLabels   = new List <CrmFormLabel>();

            foreach (var lcid in languages)
            {
                if (userSettingLcid != lcid)
                {
                    setting["localeid"]       = lcid;
                    setting["uilanguageid"]   = lcid;
                    setting["helplanguageid"] = lcid;
                    service.Update(setting);
                    currentSetting = lcid;
                }

                var forms = RetrieveDashboardList(service);

                foreach (var form in forms)
                {
                    #region Tabs

                    // Load Xml definition of form
                    var sFormXml = form.GetAttributeValue <string>("formxml");
                    var formXml  = new XmlDocument();
                    formXml.LoadXml(sFormXml);

                    foreach (XmlNode tabNode in formXml.SelectNodes("//tab"))
                    {
                        var tabName = ExtractTabName(tabNode, lcid, crmFormTabs, form);

                        #region Sections

                        foreach (
                            XmlNode sectionNode in tabNode.SelectNodes("columns/column/sections/section"))
                        {
                            var sectionName = ExtractSection(sectionNode, lcid, crmFormSections, form, tabName);

                            #region Labels

                            foreach (XmlNode labelNode in sectionNode.SelectNodes("rows/row/cell"))
                            {
                                ExtractField(labelNode, crmFormLabels, form, tabName, sectionName,
                                             lcid);
                            }

                            #endregion Labels
                        }

                        #endregion Sections
                    }

                    #endregion Tabs
                }
            }

            if (userSettingLcid != currentSetting)
            {
                setting["localeid"]       = userSettingLcid;
                setting["uilanguageid"]   = userSettingLcid;
                setting["helplanguageid"] = userSettingLcid;
                service.Update(setting);
            }

            var forms2 = RetrieveDashboardList(service);

            foreach (var form in forms2)
            {
                var crmForm =
                    crmForms.FirstOrDefault(f => f.FormUniqueId == form.GetAttributeValue <Guid>("formidunique"));
                if (crmForm == null)
                {
                    crmForm = new CrmForm
                    {
                        FormUniqueId = form.GetAttributeValue <Guid>("formidunique"),
                        Id           = form.GetAttributeValue <Guid>("formid"),
                        Names        = new Dictionary <int, string>(),
                        Descriptions = new Dictionary <int, string>()
                    };
                    crmForms.Add(crmForm);
                }

                // Names
                var request = new RetrieveLocLabelsRequest
                {
                    AttributeName = "name",
                    EntityMoniker = new EntityReference("systemform", form.Id)
                };

                var response = (RetrieveLocLabelsResponse)service.Execute(request);
                foreach (var locLabel in response.Label.LocalizedLabels)
                {
                    crmForm.Names.Add(locLabel.LanguageCode, locLabel.Label);
                }

                // Descriptions
                request = new RetrieveLocLabelsRequest
                {
                    AttributeName = "description",
                    EntityMoniker = new EntityReference("systemform", form.Id)
                };

                response = (RetrieveLocLabelsResponse)service.Execute(request);
                foreach (var locLabel in response.Label.LocalizedLabels)
                {
                    crmForm.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                }
            }

            var line      = 1;
            var formSheet = file.Worksheets.Add("Dashboards");
            AddFormHeader(formSheet, languages);

            foreach (var crmForm in crmForms)
            {
                line = ExportForm(languages, formSheet, line, crmForm);
            }

            // Applying style to cells
            for (int i = 0; i < (3 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(formSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(formSheet, i, j).Style);
                }
            }

            var tabSheet = file.Worksheets.Add("Dashboards Tabs");
            line = 1;
            AddFormTabHeader(tabSheet, languages);
            foreach (var crmFormTab in crmFormTabs)
            {
                line = ExportTab(languages, tabSheet, line, crmFormTab);
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(tabSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(tabSheet, i, j).Style);
                }
            }

            var sectionSheet = file.Worksheets.Add("Dashboards Sections");
            line = 1;
            AddFormSectionHeader(sectionSheet, languages);
            foreach (var crmFormSection in crmFormSections)
            {
                line = ExportSection(languages, sectionSheet, line, crmFormSection);
            }

            // Applying style to cells
            for (int i = 0; i < (5 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sectionSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sectionSheet, i, j).Style);
                }
            }

            var labelSheet = file.Worksheets.Add("Dashboards Fields");
            AddFormLabelsHeader(labelSheet, languages);
            line = 1;
            foreach (var crmFormLabel in crmFormLabels)
            {
                line = ExportField(languages, labelSheet, line, crmFormLabel);
            }

            // Applying style to cells
            for (int i = 0; i < (7 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(labelSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 7; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(labelSheet, i, j).Style);
                }
            }
        }
        public void Export(List <EntityMetadata> entities, List <int> languages, ExcelWorkbook file, IOrganizationService service, FormExportOption options, ExportSettings esettings)
        {
            settings = esettings;

            // Retrieve current user language information
            var setting = GetCurrentUserSettings(service);

            var userSettingLcid = setting.GetAttributeValue <int>("uilanguageid");
            var currentSetting  = userSettingLcid;

            var crmForms        = new List <CrmForm>();
            var crmFormTabs     = new List <CrmFormTab>();
            var crmFormSections = new List <CrmFormSection>();
            var crmFormLabels   = new List <CrmFormLabel>();

            foreach (var lcid in languages)
            {
                if (userSettingLcid != lcid)
                {
                    setting["localeid"]       = lcid;
                    setting["uilanguageid"]   = lcid;
                    setting["helplanguageid"] = lcid;
                    service.Update(setting);
                    currentSetting = lcid;

                    Thread.Sleep(2000);
                }

                foreach (var entity in entities.OrderBy(e => e.LogicalName))
                {
                    if (!entity.MetadataId.HasValue)
                    {
                        continue;
                    }

                    var forms = RetrieveEntityFormList(entity.LogicalName, service);

                    foreach (var form in forms)
                    {
                        #region Tabs

                        if (options.ExportFormTabs || options.ExportFormSections || options.ExportFormFields)
                        {
                            // Load Xml definition of form
                            var sFormXml = form.GetAttributeValue <string>("formxml");
                            var formXml  = new XmlDocument();
                            formXml.LoadXml(sFormXml);

                            // Specific for header
                            if (options.ExportFormFields)
                            {
                                var cellNodes = formXml.DocumentElement.SelectNodes("header/rows/row/cell");
                                foreach (XmlNode cellNode in cellNodes)
                                {
                                    ExtractField(cellNode, crmFormLabels, form, null, null, entity, lcid);
                                }
                            }

                            foreach (XmlNode tabNode in formXml.SelectNodes("//tab"))
                            {
                                var tabName = ExtractTabName(tabNode, lcid, crmFormTabs, form, entity);

                                #region Sections

                                if (options.ExportFormSections || options.ExportFormFields)
                                {
                                    foreach (
                                        XmlNode sectionNode in tabNode.SelectNodes("columns/column/sections/section"))
                                    {
                                        var sectionName = ExtractSection(sectionNode, lcid, crmFormSections, form,
                                                                         tabName, entity);

                                        #region Labels

                                        if (options.ExportFormFields)
                                        {
                                            foreach (XmlNode labelNode in sectionNode.SelectNodes("rows/row/cell"))
                                            {
                                                ExtractField(labelNode, crmFormLabels, form, tabName, sectionName,
                                                             entity, lcid);
                                            }
                                        }

                                        #endregion Labels
                                    }
                                }

                                #endregion Sections
                            }

                            // Specific for footer
                            if (options.ExportFormFields)
                            {
                                var cellNodes = formXml.DocumentElement.SelectNodes("footer/rows/row/cell");
                                foreach (XmlNode cellNode in cellNodes)
                                {
                                    ExtractField(cellNode, crmFormLabels, form, null, null, entity, lcid);
                                }
                            }
                        }

                        #endregion Tabs
                    }
                }
            }

            if (userSettingLcid != currentSetting)
            {
                setting["localeid"]       = userSettingLcid;
                setting["uilanguageid"]   = userSettingLcid;
                setting["helplanguageid"] = userSettingLcid;
                service.Update(setting);
            }

            foreach (var entity in entities.OrderBy(e => e.LogicalName))
            {
                if (!entity.MetadataId.HasValue)
                {
                    continue;
                }

                var forms = RetrieveEntityFormList(entity.LogicalName, service);

                foreach (var form in forms)
                {
                    var crmForm =
                        crmForms.FirstOrDefault(f => f.FormUniqueId == form.GetAttributeValue <Guid>("formidunique"));
                    if (crmForm == null)
                    {
                        crmForm = new CrmForm
                        {
                            FormUniqueId = form.GetAttributeValue <Guid>("formidunique"),
                            Id           = form.GetAttributeValue <Guid>("formid"),
                            Entity       = entity.LogicalName,
                            Names        = new Dictionary <int, string>(),
                            Descriptions = new Dictionary <int, string>()
                        };
                        crmForms.Add(crmForm);
                    }

                    RetrieveLocLabelsRequest  request;
                    RetrieveLocLabelsResponse response;

                    if (settings.ExportNames)
                    {
                        // Names
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "name",
                            EntityMoniker = new EntityReference("systemform", form.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmForm.Names.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }

                    if (settings.ExportDescriptions)
                    {
                        // Descriptions
                        request = new RetrieveLocLabelsRequest
                        {
                            AttributeName = "description",
                            EntityMoniker = new EntityReference("systemform", form.Id)
                        };

                        response = (RetrieveLocLabelsResponse)service.Execute(request);
                        foreach (var locLabel in response.Label.LocalizedLabels)
                        {
                            crmForm.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                        }
                    }
                }
            }

            var line = 0;
            if (options.ExportForms)
            {
                var formSheet = file.Worksheets.Add("Forms");
                AddFormHeader(formSheet, languages);

                foreach (var crmForm in crmForms)
                {
                    line = ExportForm(languages, formSheet, line, crmForm);
                }

                // Applying style to cells
                for (int i = 0; i < (4 + languages.Count); i++)
                {
                    StyleMutator.TitleCell(ZeroBasedSheet.Cell(formSheet, 0, i).Style);
                }

                for (int i = 1; i <= line; i++)
                {
                    for (int j = 0; j < 4; j++)
                    {
                        StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(formSheet, i, j).Style);
                    }
                }
            }

            if (options.ExportFormTabs)
            {
                var tabSheet = file.Worksheets.Add("Forms Tabs");
                line = 1;
                AddFormTabHeader(tabSheet, languages);
                foreach (var crmFormTab in crmFormTabs)
                {
                    line = ExportTab(languages, tabSheet, line, crmFormTab);
                }

                // Applying style to cells
                for (int i = 0; i < (5 + languages.Count); i++)
                {
                    StyleMutator.TitleCell(ZeroBasedSheet.Cell(tabSheet, 0, i).Style);
                }

                for (int i = 1; i < line; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(tabSheet, i, j).Style);
                    }
                }
            }

            if (options.ExportFormSections)
            {
                var sectionSheet = file.Worksheets.Add("Forms Sections");
                line = 1;
                AddFormSectionHeader(sectionSheet, languages);
                foreach (var crmFormSection in crmFormSections)
                {
                    line = ExportSection(languages, sectionSheet, line, crmFormSection);
                }

                // Applying style to cells
                for (int i = 0; i < (6 + languages.Count); i++)
                {
                    StyleMutator.TitleCell(ZeroBasedSheet.Cell(sectionSheet, 0, i).Style);
                }

                for (int i = 1; i < line; i++)
                {
                    for (int j = 0; j < 6; j++)
                    {
                        StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sectionSheet, i, j).Style);
                    }
                }
            }

            if (options.ExportFormFields)
            {
                var labelSheet = file.Worksheets.Add("Forms Fields");
                AddFormLabelsHeader(labelSheet, languages);
                line = 1;
                foreach (var crmFormLabel in crmFormLabels)
                {
                    line = ExportField(languages, labelSheet, line, crmFormLabel);
                }

                // Applying style to cells
                for (int i = 0; i < (8 + languages.Count); i++)
                {
                    StyleMutator.TitleCell(ZeroBasedSheet.Cell(labelSheet, 0, i).Style);
                }

                for (int i = 1; i < line; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(labelSheet, i, j).Style);
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// viewId;entityLogicalName;viewName;ViewType;Type;LCID1;LCID2;...;LCODX
        /// </example>
        /// <param name="entities"></param>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        public void Export(List<EntityMetadata> entities, List<int> languages, ExcelWorksheet sheet, IOrganizationService service)
        {
            var line = 1;

            AddHeader(sheet, languages);

            var crmViews = new List<CrmView>();

            foreach (var entity in entities.OrderBy(e => e.LogicalName))
            {
                if (!entity.MetadataId.HasValue)
                    continue;

                var views = RetrieveViews(entity.LogicalName, entity.ObjectTypeCode.Value, service);

                foreach (var view in views)
                {
                    var crmView = crmViews.FirstOrDefault(cv => cv.Id == view.Id);
                    if (crmView == null)
                    {
                        crmView = new CrmView
                        {
                            Id = view.Id,
                            Entity = view.GetAttributeValue<string>("returnedtypecode"),
                            Type = view.GetAttributeValue<int>("querytype"),
                            Names = new Dictionary<int, string>(),
                            Descriptions = new Dictionary<int, string>()
                        };
                        crmViews.Add(crmView);
                    }

                    // Names
                    var request = new RetrieveLocLabelsRequest
                    {
                        AttributeName = "name",
                        EntityMoniker = new EntityReference("savedquery", view.Id)
                    };

                    var response = (RetrieveLocLabelsResponse)service.Execute(request);
                    foreach (var locLabel in response.Label.LocalizedLabels)
                    {
                        crmView.Names.Add(locLabel.LanguageCode, locLabel.Label);
                    }

                    // Descriptions
                    request = new RetrieveLocLabelsRequest
                    {
                        AttributeName = "description",
                        EntityMoniker = new EntityReference("savedquery", view.Id)
                    };

                    response = (RetrieveLocLabelsResponse)service.Execute(request);
                    foreach (var locLabel in response.Label.LocalizedLabels)
                    {
                        crmView.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                    }
                }
            }

            foreach (var crmView in crmViews.OrderBy(cv => cv.Entity).ThenBy(cv => cv.Type))
            {
                var cell = 0;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Type;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Name";

                foreach (var lcid in languages)
                {
                    var name = crmView.Names.FirstOrDefault(n => n.Key == lcid);
                    if (name.Value != null)
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = name.Value;
                    else
                    {
                        cell++;
                    }
                }

                line++;
                cell = 0;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Id.ToString("B");
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Entity;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmView.Type;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                foreach (var lcid in languages)
                {
                    var desc = crmView.Descriptions.FirstOrDefault(n => n.Key == lcid);
                    if (desc.Value != null)
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = desc.Value;
                    else
                    {
                        cell++;
                    }
                }
                line++;
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }
Пример #5
0
        private static void Initialize()
        {
            const string        fetchXml      = "__fetchXml__";
            const string        schemaName    = "__schemaName__";
            const string        entityName    = "__entityName__";
            const string        logicalName   = "__logicalName__";
            const string        attributeName = "__attributeName__";
            const EntityFilters filters       = EntityFilters.All;
            var id = new Guid("ffffffff-ffff-ffff-ffff-ffffffffffff");

            var retrieveRequest = new RetrieveRequest {
                ColumnSet = new ColumnSet(true), Target = new EntityReference(logicalName, id)
            };

            _serializedRetrieveRequestFormat = SerializeForFormat(retrieveRequest)
                                               .Replace(logicalName, @"{0}")
                                               .Replace(id.ToString(), @"{1}");

            var relationship = new Relationship(schemaName)
            {
                PrimaryEntityRole = EntityRole.Referencing
            };
            var query = new RelationshipQueryCollection {
                { relationship, new QueryExpression(entityName)
                  {
                      ColumnSet = new ColumnSet(true)
                  } }
            };
            var retrieveRequestWithRelatedQuery = new RetrieveRequest {
                ColumnSet = new ColumnSet(), Target = new EntityReference(logicalName, id), RelatedEntitiesQuery = query
            };

            _serializedRetrieveRequestWithRelatedQueryFormat = SerializeForFormat(retrieveRequestWithRelatedQuery)
                                                               .Replace(logicalName, @"{0}")
                                                               .Replace(id.ToString(), @"{1}")
                                                               .Replace(schemaName, @"{2}")
                                                               .Replace(@"""PrimaryEntityRole"":0", @"""PrimaryEntityRole"":{3}")
                                                               .Replace(entityName, @"{4}");

            var retrieveAllEntitiesRequest = new RetrieveAllEntitiesRequest {
                EntityFilters = filters, RetrieveAsIfPublished = true
            };

            _serializedRetrieveAllEntitiesRequestFormat = SerializeForFormat(retrieveAllEntitiesRequest)
                                                          .Replace(((int)filters).ToString(), @"{0}")
                                                          .Replace("true", @"{1}");

            var retrieveEntityRequest = new RetrieveEntityRequest {
                EntityFilters = filters, LogicalName = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveEntityRequestFormat = SerializeForFormat(retrieveEntityRequest)
                                                     .Replace(((int)filters).ToString(), @"{0}")
                                                     .Replace(logicalName, @"{1}")
                                                     .Replace("true", @"{2}");

            var retrieveMultipleRequest = new RetrieveMultipleRequest {
                Query = new QueryExpression(logicalName)
                {
                    Distinct = true
                }
            };

            _serializedRetrieveMultipleRequestFormat = SerializeForFormat(retrieveMultipleRequest)
                                                       .Replace(logicalName, @"{0}")
                                                       .Replace("true", @"{1}");

            var retrieveMultipleFetchExpressionRequest = new RetrieveMultipleRequest {
                Query = new FetchExpression(fetchXml)
            };

            _serializedRetrieveMultipleFetchExpressionFormat = SerializeForFormat(retrieveMultipleFetchExpressionRequest)
                                                               .Replace(fetchXml, @"{0}");

            var retrieveRelationshipRequest = new RetrieveRelationshipRequest {
                Name = logicalName, RetrieveAsIfPublished = true
            };

            _serializedRetrieveRelationshipRequestFormat = SerializeForFormat(retrieveRelationshipRequest)
                                                           .Replace(logicalName, @"{0}")
                                                           .Replace("true", @"{1}");

            var retrieveLocLabelsRequest = new RetrieveLocLabelsRequest
            {
                EntityMoniker      = new EntityReference(logicalName, id),
                AttributeName      = attributeName,
                IncludeUnpublished = true
            };

            _serializedRetrieveLocLabelsRequestFormat =
                SerializeForFormat(retrieveLocLabelsRequest)
                .Replace(logicalName, @"{0}")
                .Replace(id.ToString(), @"{1}")
                .Replace(attributeName, @"{2}")
                .Replace("true", @"{3}");

            var retrieveProvLangsRequest = new RetrieveProvisionedLanguagesRequest();

            _serializedRetrieveProvisionedLanguagesRequestFormat = SerializeForFormat(retrieveProvLangsRequest);
        }
        public void Export(List<int> languages, ExcelWorkbook file, IOrganizationService service)
        {
            // Retrieve current user language information
            var setting = GetCurrentUserSettings(service);

            var userSettingLcid = setting.GetAttributeValue<int>("uilanguageid");
            var currentSetting = userSettingLcid;

            var crmForms = new List<CrmForm>();
            var crmFormTabs = new List<CrmFormTab>();
            var crmFormSections = new List<CrmFormSection>();
            var crmFormLabels = new List<CrmFormLabel>();

            foreach (var lcid in languages)
            {
                if (userSettingLcid != lcid)
                {
                    setting["localeid"] = lcid;
                    setting["uilanguageid"] = lcid;
                    setting["helplanguageid"] = lcid;
                    service.Update(setting);
                    currentSetting = lcid;
                }

                var forms = RetrieveDashboardList(service);

                foreach (var form in forms)
                {
                    #region Tabs

                    // Load Xml definition of form
                    var sFormXml = form.GetAttributeValue<string>("formxml");
                    var formXml = new XmlDocument();
                    formXml.LoadXml(sFormXml);

                    foreach (XmlNode tabNode in formXml.SelectNodes("//tab"))
                    {
                        var tabName = ExtractTabName(tabNode, lcid, crmFormTabs, form);

                        #region Sections

                        foreach (
                            XmlNode sectionNode in tabNode.SelectNodes("columns/column/sections/section"))
                        {
                            var sectionName = ExtractSection(sectionNode, lcid, crmFormSections, form, tabName);

                            #region Labels

                            foreach (XmlNode labelNode in sectionNode.SelectNodes("rows/row/cell"))
                            {
                                ExtractField(labelNode, crmFormLabels, form, tabName, sectionName,
                                    lcid);
                            }

                            #endregion Labels
                        }

                        #endregion Sections
                    }

                    #endregion Tabs
                }
            }

            if (userSettingLcid != currentSetting)
            {
                setting["localeid"] = userSettingLcid;
                setting["uilanguageid"] = userSettingLcid;
                setting["helplanguageid"] = userSettingLcid;
                service.Update(setting);
            }

            var forms2 = RetrieveDashboardList(service);

            foreach (var form in forms2)
            {
                var crmForm =
                    crmForms.FirstOrDefault(f => f.FormUniqueId == form.GetAttributeValue<Guid>("formidunique"));
                if (crmForm == null)
                {
                    crmForm = new CrmForm
                    {
                        FormUniqueId = form.GetAttributeValue<Guid>("formidunique"),
                        Id = form.GetAttributeValue<Guid>("formid"),
                        Names = new Dictionary<int, string>(),
                        Descriptions = new Dictionary<int, string>()
                    };
                    crmForms.Add(crmForm);
                }

                // Names
                var request = new RetrieveLocLabelsRequest
                {
                    AttributeName = "name",
                    EntityMoniker = new EntityReference("systemform", form.Id)
                };

                var response = (RetrieveLocLabelsResponse)service.Execute(request);
                foreach (var locLabel in response.Label.LocalizedLabels)
                {
                    crmForm.Names.Add(locLabel.LanguageCode, locLabel.Label);
                }

                // Descriptions
                request = new RetrieveLocLabelsRequest
                {
                    AttributeName = "description",
                    EntityMoniker = new EntityReference("systemform", form.Id)
                };

                response = (RetrieveLocLabelsResponse)service.Execute(request);
                foreach (var locLabel in response.Label.LocalizedLabels)
                {
                    crmForm.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                }
            }

            var line = 1;
            var formSheet = file.Worksheets.Add("Dashboards");
            AddFormHeader(formSheet, languages);

            foreach (var crmForm in crmForms)
            {
                line = ExportForm(languages, formSheet, line, crmForm);
            }

            // Applying style to cells
            for (int i = 0; i < (3 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(formSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(formSheet, i, j).Style);
                }
            }

            var tabSheet = file.Worksheets.Add("Dashboards Tabs");
            line = 1;
            AddFormTabHeader(tabSheet, languages);
            foreach (var crmFormTab in crmFormTabs)
            {
                line = ExportTab(languages, tabSheet, line, crmFormTab);
            }

            // Applying style to cells
            for (int i = 0; i < (4 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(tabSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(tabSheet, i, j).Style);
                }
            }

            var sectionSheet = file.Worksheets.Add("Dashboards Sections");
            line = 1;
            AddFormSectionHeader(sectionSheet, languages);
            foreach (var crmFormSection in crmFormSections)
            {
                line = ExportSection(languages, sectionSheet, line, crmFormSection);
            }

            // Applying style to cells
            for (int i = 0; i < (5 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sectionSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sectionSheet, i, j).Style);
                }
            }

            var labelSheet = file.Worksheets.Add("Dashboards Fields");
            AddFormLabelsHeader(labelSheet, languages);
            line = 1;
            foreach (var crmFormLabel in crmFormLabels)
            {
                line = ExportField(languages, labelSheet, line, crmFormLabel);
            }

            // Applying style to cells
            for (int i = 0; i < (7 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(labelSheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 7; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(labelSheet, i, j).Style);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <example>
        /// visualizationId;entityLogicalName;visualizationName;LCID1;LCID2;...;LCODX
        /// </example>
        /// <param name="entities"></param>
        /// <param name="languages"></param>
        /// <param name="sheet"></param>
        public void Export(List <EntityMetadata> entities, List <int> languages, ExcelWorksheet sheet, IOrganizationService service)
        {
            var line = 1;

            AddHeader(sheet, languages);

            var crmVisualizations = new List <CrmVisualization>();

            foreach (var entity in entities.OrderBy(e => e.LogicalName))
            {
                if (!entity.MetadataId.HasValue)
                {
                    continue;
                }

                var visualizations = RetrieveVisualizations(entity.ObjectTypeCode.Value, service);

                foreach (var visualization in visualizations)
                {
                    var crmVisualization = crmVisualizations.FirstOrDefault(cv => cv.Id == visualization.Id);
                    if (crmVisualization == null)
                    {
                        crmVisualization = new CrmVisualization
                        {
                            Id           = visualization.Id,
                            Entity       = visualization.GetAttributeValue <string>("primaryentitytypecode"),
                            Names        = new Dictionary <int, string>(),
                            Descriptions = new Dictionary <int, string>()
                        };
                        crmVisualizations.Add(crmVisualization);
                    }

                    // Names
                    var request = new RetrieveLocLabelsRequest
                    {
                        AttributeName = "name",
                        EntityMoniker = new EntityReference("savedqueryvisualization", visualization.Id)
                    };

                    var response = (RetrieveLocLabelsResponse)service.Execute(request);
                    foreach (var locLabel in response.Label.LocalizedLabels)
                    {
                        crmVisualization.Names.Add(locLabel.LanguageCode, locLabel.Label);
                    }

                    // Descriptions
                    request = new RetrieveLocLabelsRequest
                    {
                        AttributeName = "description",
                        EntityMoniker = new EntityReference("savedqueryvisualization", visualization.Id)
                    };

                    response = (RetrieveLocLabelsResponse)service.Execute(request);
                    foreach (var locLabel in response.Label.LocalizedLabels)
                    {
                        crmVisualization.Descriptions.Add(locLabel.LanguageCode, locLabel.Label);
                    }
                }
            }

            foreach (var crmVisualization in crmVisualizations.OrderBy(cv => cv.Entity))
            {
                var cell = 0;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmVisualization.Id.ToString("B");
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmVisualization.Entity;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Name";

                foreach (var lcid in languages)
                {
                    var name = crmVisualization.Names.FirstOrDefault(n => n.Key == lcid);
                    if (name.Value != null)
                    {
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = name.Value;
                    }
                    else
                    {
                        cell++;
                    }
                }

                line++;
                cell = 0;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmVisualization.Id.ToString("B");
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = crmVisualization.Entity;
                ZeroBasedSheet.Cell(sheet, line, cell++).Value = "Description";

                foreach (var lcid in languages)
                {
                    var desc = crmVisualization.Descriptions.FirstOrDefault(n => n.Key == lcid);
                    if (desc.Value != null)
                    {
                        ZeroBasedSheet.Cell(sheet, line, cell++).Value = desc.Value;
                    }
                    else
                    {
                        cell++;
                    }
                }
                line++;
            }

            // Applying style to cells
            for (int i = 0; i < (3 + languages.Count); i++)
            {
                StyleMutator.TitleCell(ZeroBasedSheet.Cell(sheet, 0, i).Style);
            }

            for (int i = 1; i < line; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    StyleMutator.HighlightedCell(ZeroBasedSheet.Cell(sheet, i, j).Style);
                }
            }
        }