Exemplo n.º 1
0
        public void Run(ProcessingContext context)
        {
            _csvUtility.CreateCsv(context.Rows);

            Console.Clear();
            Console.WriteLine("Csv Created");
        }
Exemplo n.º 2
0
        public void CsvUtilityCreateCsvTest()
        {
            var objects = new List <TestObject>();

            objects.Add(new TestObject()
            {
                StringField  = "ABC\"\n,'ABC",
                IntField     = -1,
                DateField    = null,
                BooleanField = false
            });

            for (var i = 0; i < 500; i++)
            {
                var o = new TestObject()
                {
                    StringField  = Replicate('A', i),
                    IntField     = i,
                    DateField    = DateTime.Now,
                    BooleanField = true
                };
                objects.Add(o);
            }

            CsvUtility.CreateCsv(TestingFolder, "CsvObjects" + DateTime.Now.ToFileTime() + "", objects);
        }
        public void DownloadCsv()
        {
            var newFileName = ApplicationController.GetSaveFileName(string.Format("{0}", RecordService.GetCollectionName(RecordType)), "csv");

            ApplicationController.DoOnAsyncThread(() =>
            {
                try
                {
                    LoadingViewModel.IsLoading = true;
                    if (!string.IsNullOrWhiteSpace(newFileName))
                    {
                        var folder   = Path.GetDirectoryName(newFileName);
                        var fileName = Path.GetFileName(newFileName);
                        var fields   = FieldMetadata.Select(rf => rf.FieldName);
                        CsvUtility.CreateCsv(folder, fileName, GetGridRecords(true).Records, fields, (f) => RecordService.GetFieldLabel(f, RecordType), (r, f) => { return(RecordService.GetFieldAsDisplayString((IRecord)r, f)); });
                        ApplicationController.StartProcess("explorer.exe", "/select, \"" + Path.Combine(folder, fileName) + "\"");
                    }
                }
                catch (Exception ex)
                {
                    ApplicationController.UserMessage("Error Downloading CSV: " + ex.DisplayString());
                }
                finally
                {
                    LoadingViewModel.IsLoading = false;
                }
            });
        }
 public void DownloadCsv(string folder)
 {
     ApplicationController.DoOnAsyncThread(() =>
     {
         CsvForExtraction      = false;
         CsvExtracting         = true;
         CsvExtractingProgress = new ProgressControlViewModel(ApplicationController);
         CsvExtractingProgress.UpdateProgress(0, 1, "Extracting To CSV");
         try
         {
             var fileName = string.Format("{0} CSV Download - {1}.csv", ApplicationController.ApplicationName,
                                          DateTime.Now.ToFileTime());
             CsvUtility.CreateCsv(folder, fileName
                                  , Items, new LogController(CsvExtractingProgress));
             CsvExtracting = false;
             CsvExtracted  = true;
             OpenCsvButton = new XrmButtonViewModel("Open CSV", () => OpenFile(folder, fileName),
                                                    ApplicationController);
             OpenCsvFolderButton = new XrmButtonViewModel("Open CSV Folder", () => OpenFolder(folder),
                                                          ApplicationController);
         }
         catch (Exception ex)
         {
             CsvExtracting    = false;
             CsvForExtraction = true;
             ApplicationController.UserMessage("Error Downloading CSV: " + ex.DisplayString());
         }
     });
 }
        public void DownloadCsv()
        {
            var newFileName = ApplicationController.GetSaveFileName(string.Format("{0}", RecordService.GetCollectionName(RecordType)), "csv");

            ApplicationController.DoOnAsyncThread(() =>
            {
                try
                {
                    LoadingViewModel.IsLoading = true;
                    if (!string.IsNullOrWhiteSpace(newFileName))
                    {
                        var folder   = Path.GetDirectoryName(newFileName);
                        var fileName = Path.GetFileName(newFileName);
                        var fields   = FieldMetadata.ToArray();
                        var started  = DateTime.UtcNow;

                        var labelFuncDictionary = new Dictionary <string, Func <string, string> >();
                        foreach (var fm in FieldMetadata)
                        {
                            labelFuncDictionary.Add(fm.AliasedFieldName ?? fm.FieldName, s => fm.OverrideLabel ?? RecordService.GetFieldLabel(fm.FieldName, fm.AltRecordType ?? RecordType));
                        }

                        var displayFuncDictionary = new Dictionary <string, Func <object, string, string> >();
                        foreach (var fm in FieldMetadata)
                        {
                            displayFuncDictionary.Add(fm.AliasedFieldName ?? fm.FieldName, (o, s) => RecordService.GetFieldAsDisplayString(fm.AltRecordType ?? RecordType, fm.FieldName, ((IRecord)o).GetField(s)));
                        }

                        CsvUtility.CreateCsv(folder, fileName, GetGridRecords(true).Records,
                                             fields.Select(f => f.AliasedFieldName ?? f.FieldName),
                                             (f) => labelFuncDictionary[f](f),
                                             (r, f) => displayFuncDictionary[f](r, f));


                        ApplicationController.LogEvent("Download CSV", new Dictionary <string, string>
                        {
                            { "Is Completed Event", true.ToString() },
                            { "Type", RecordType },
                            { "Seconds Taken", (DateTime.UtcNow - started).TotalSeconds.ToString() },
                        });
                        ApplicationController.StartProcess("explorer.exe", "/select, \"" + Path.Combine(folder, fileName) + "\"");
                    }
                }
                catch (Exception ex)
                {
                    ApplicationController.ThrowException(ex);
                }
                finally
                {
                    LoadingViewModel.IsLoading = false;
                }
            });
        }
Exemplo n.º 6
0
        public override void ExecuteExtention(CustomisationExporterRequest request,
                                              CustomisationExporterResponse response,
                                              ServiceRequestController controller)
        {
            response.Folder = request.SaveToFolder.FolderPath;
            controller.LogLiteral("Loading Metadata");

            ProcessForEntities(request, response, controller.Controller);

            if ((request.Fields || request.FieldOptionSets) && request.IncludeAllRecordTypes)
            {
                controller.UpdateProgress(0, 1, "Loading All Fields.....");
                Service.LoadFieldsForAllEntities();
            }
            if ((request.Fields || request.Relationships) && request.IncludeAllRecordTypes)
            {
                controller.UpdateProgress(0, 1, "Loading All Relationships.....");
                Service.LoadRelationshipsForAllEntities();
            }
            ProcessForFields(request, response, controller.Controller);

            ProcessForRelationships(request, response, controller.Controller);
            ProcessForOptionSets(request, response, controller.Controller);

            response.Folder = request.SaveToFolder.FolderPath;

            if (request.Format == CustomisationExporterRequest.FileFormat.Xlsx)
            {
                var excelFileName = "Customisation Export " + DateTime.Now.ToFileTime() + ".xlsx";
                ExcelUtility.CreateXlsx(request.SaveToFolder.FolderPath, excelFileName, response.GetListsToOutput());
                response.ExcelFileName = excelFileName;
            }
            else
            {
                foreach (var item in response.GetListsToOutput())
                {
                    var csvName = item.Key + " " + DateTime.Now.ToFileTime() + ".csv";
                    CsvUtility.CreateCsv(request.SaveToFolder.FolderPath, csvName, item.Value);
                }
            }

            response.Message = "The Export is Complete";
        }
 private void ProcessForEntities(CustomisationExporterRequest request, CustomisationExporterResponse response,
                                 LogController controller)
 {
     if (request.Entities)
     {
         var allEntities = new List <EntityExport>();
         var types       = GetRecordTypesToExport(request).OrderBy(t => Service.GetDisplayName(t)).ToArray();
         var count       = types.Count();
         for (var i = 0; i < count; i++)
         {
             var thisType      = types.ElementAt(i);
             var thisTypeLabel = Service.GetDisplayName(thisType);
             controller.UpdateProgress(i, count, "Exporting Record Type " + thisTypeLabel);
             try
             {
                 allEntities.Add(new EntityExport(thisTypeLabel, thisType,
                                                  Service.GetRecordTypeMetadata(thisType).IsCustomType,
                                                  Service.GetRecordTypeMetadata(thisType).RecordTypeCode, Service.GetCollectionName(thisType),
                                                  Service.GetRecordTypeMetadata(thisType).Description
                                                  , Service.GetRecordTypeMetadata(thisType).Audit,
                                                  Service.GetRecordTypeMetadata(thisType).IsActivityType,
                                                  Service.GetRecordTypeMetadata(thisType).Notes,
                                                  Service.GetRecordTypeMetadata(thisType).Activities
                                                  , Service.GetRecordTypeMetadata(thisType).Connections,
                                                  Service.GetRecordTypeMetadata(thisType).MailMerge,
                                                  Service.GetRecordTypeMetadata(thisType).Queues,
                                                  Service.GetRecordTypeMetadata(thisType).MetadataId));
             }
             catch (Exception ex)
             {
                 response.AddResponseItem(new CustomisationExporterResponseItem("Error Exporting Record Type",
                                                                                thisType, ex));
             }
         }
         var fileName = "TypesExport_" + DateTime.Now.ToFileTime() + ".csv";
         CsvUtility.CreateCsv(request.SaveToFolder.FolderPath, fileName, allEntities);
         response.TypesFileName = fileName;
     }
 }
Exemplo n.º 8
0
 public void DownloadCsv()
 {
     try
     {
         var fileName = ApplicationController.GetSaveFileName(RecordType, ".csv");
         if (!fileName.IsNullOrWhiteSpace())
         {
             RecordForm.LoadingViewModel.IsLoading = true;
             DoOnAsynchThread(() =>
             {
                 try
                 {
                     Thread.Sleep(5000);
                     var records = GetGridRecords(true);
                     CsvUtility.CreateCsv(Path.GetDirectoryName(fileName), Path.GetFileName(fileName),
                                          records.Records
                                          , GetRecordService().GetFields(RecordType),
                                          (f) => GetRecordService().GetFieldLabel(f, RecordType),
                                          (r, f) => GetRecordService().GetFieldAsDisplayString((IRecord)r, f));
                     Process.Start(fileName);
                 }
                 catch (Exception ex)
                 {
                     ApplicationController.ThrowException(ex);
                 }
                 finally
                 {
                     RecordForm.LoadingViewModel.IsLoading = false;
                 }
             });
         }
     }
     catch (Exception ex)
     {
         ApplicationController.ThrowException(ex);
     }
 }
Exemplo n.º 9
0
        public override void LoadToUi(ViewModelBase viewModel)
        {
            if (viewModel is ObjectDisplayViewModel)
            {
                var oeVm = (ObjectDisplayViewModel)viewModel;
                UserInterface.LogMessage(string.Format("Loading {0}", oeVm.RecordType));
                oeVm.LoadFormSections();
                UserInterface.LogMessage(string.Format("Validating {0}", oeVm.RecordType));
                var validate = oeVm.Validate();
                if (!validate)
                {
                    throw new Exception(string.Format("The {0} Object Could Not Be Validated For Processing: {1}", oeVm.GetObject().GetType().Name, oeVm.GetValidationSummary()));
                }
                UserInterface.LogMessage("Validation Complete");
                oeVm.OnSave();
            }

            if (viewModel is ObjectEntryViewModel)
            {
                var oeVm = (ObjectEntryViewModel)viewModel;
                UserInterface.LogMessage(string.Format("Loading {0}", oeVm.RecordType));
                oeVm.LoadFormSections();
                UserInterface.LogMessage(string.Format("Validating {0}", oeVm.RecordType));
                var validate = oeVm.Validate();
                if (!validate)
                {
                    throw new Exception(string.Format("The {0} Object Could Not Be Validated For Processing: {1}", oeVm.GetObject().GetType().Name, oeVm.GetValidationSummary()));
                }
                UserInterface.LogMessage("Validation Complete");
                oeVm.OnSave();
            }

            if (viewModel is CompletionScreenViewModel)
            {
                var completion       = (CompletionScreenViewModel)viewModel;
                var completionObject = completion.CompletionDetails?.GetObject() as IProcessCompletion;
                if (completionObject == null)
                {
                    throw new Exception($"The Process Failed To Complete: {completion.CompletionHeadingText}");
                }
                else
                {
                    UserInterface.LogMessage("Processing Completion");
                    if (!completionObject.Success)
                    {
                        throw completionObject.Exception;
                    }
                    else
                    {
                        var errors = completionObject.GetResponseItemsWithError();
                        if (errors.Any())
                        {
                            var folder   = ApplicationController.LogPath;
                            var fileName = string.Format("{0}Errors_{1}.csv", errors.First().GetType().Name, DateTime.Now.ToFileTime());
                            CsvUtility.CreateCsv(ApplicationController.LogPath, fileName, errors);
                            throw new Exception(string.Format("Errors occured during the process and have been output into {0}", Path.Combine(folder, fileName)));
                        }
                    }
                }
            }
            if (viewModel is ProgressControlViewModel)
            {
                var progressVm          = (ProgressControlViewModel)viewModel;
                var lastPercentProgress = 0;
                var lastMessage         = "";
                progressVm.PropertyChanged += (s, e) => {
                    if (e.PropertyName == nameof(ProgressControlViewModel.FractionCompleted))
                    {
                        lock (_lockObject)
                        {
                            var percentProgress = (progressVm.FractionCompleted / 1) * 100;
                            if (percentProgress == 0)
                            {
                                lastPercentProgress = 0;
                            }
                            while (lastPercentProgress < percentProgress)
                            {
                                lastPercentProgress++;
                                if (lastPercentProgress % 10 == 0)
                                {
                                    System.Console.WriteLine(lastPercentProgress + "%");
                                }
                            }
                        }
                    }
                    if (e.PropertyName == nameof(ProgressControlViewModel.Message))
                    {
                        lock (_lockObject)
                        {
                            if (progressVm.Message != lastMessage)
                            {
                                lastMessage = progressVm.Message;
                                System.Console.WriteLine(lastMessage);
                            }
                        }
                    }
                };
            }
        }
 private void ProcessForRelationships(CustomisationExporterRequest request,
                                      CustomisationExporterResponse response,
                                      LogController controller)
 {
     if (request.Relationships)
     {
         var allRelationship = new List <RelationshipExport>();
         var types           = GetRecordTypesToExport(request).OrderBy(t => Service.GetDisplayName(t)).ToArray();
         var count           = types.Count();
         var manyToManyDone  = new List <string>();
         for (var i = 0; i < count; i++)
         {
             var thisType      = types.ElementAt(i);
             var thisTypeLabel = Service.GetDisplayName(thisType);
             controller.UpdateProgress(i, count, "Exporting Relationships For " + thisTypeLabel);
             try
             {
                 var relationships = Service.GetManyToManyRelationships(thisType);
                 for (var j = 0; j < relationships.Count(); j++)
                 {
                     var relationship = relationships.ElementAt(j);
                     try
                     {
                         if (relationship.RecordType1 == thisType
                             ||
                             (!request.DuplicateManyToManyRelationshipSides &&
                              !manyToManyDone.Contains(relationship.SchemaName))
                             )
                         {
                             allRelationship.Add(new RelationshipExport(relationship.SchemaName,
                                                                        relationship.RecordType1, relationship.RecordType2,
                                                                        relationship.IsCustomRelationship, relationship.RecordType1DisplayRelated,
                                                                        relationship.RecordType2DisplayRelated
                                                                        , relationship.Entity1IntersectAttribute, relationship.Entity2IntersectAttribute,
                                                                        RelationshipExport.RelationshipType.ManyToMany,
                                                                        relationship.RecordType1UseCustomLabel, relationship.RecordType2UseCustomLabel,
                                                                        relationship.RecordType1CustomLabel, relationship.RecordType2CustomLabel
                                                                        , relationship.RecordType1DisplayOrder, relationship.RecordType2DisplayOrder, relationship.MetadataId
                                                                        , null));
                             manyToManyDone.Add(relationship.SchemaName);
                         }
                         if (relationship.RecordType2 == thisType &&
                             (request.DuplicateManyToManyRelationshipSides ||
                              (!manyToManyDone.Contains(relationship.SchemaName))))
                         {
                             allRelationship.Add(new RelationshipExport(relationship.SchemaName,
                                                                        relationship.RecordType2, relationship.RecordType1,
                                                                        relationship.IsCustomRelationship, relationship.RecordType2DisplayRelated,
                                                                        relationship.RecordType1DisplayRelated
                                                                        , relationship.Entity2IntersectAttribute, relationship.Entity1IntersectAttribute,
                                                                        RelationshipExport.RelationshipType.ManyToMany,
                                                                        relationship.RecordType2UseCustomLabel, relationship.RecordType1UseCustomLabel,
                                                                        relationship.RecordType2CustomLabel, relationship.RecordType1CustomLabel
                                                                        , relationship.RecordType2DisplayOrder, relationship.RecordType1DisplayOrder
                                                                        , relationship.MetadataId, null));
                             manyToManyDone.Add(relationship.SchemaName);
                         }
                     }
                     catch (Exception ex)
                     {
                         response.AddResponseItem(
                             new CustomisationExporterResponseItem("Error Exporting Relationship",
                                                                   relationship.SchemaName, ex));
                     }
                 }
                 if (request.IncludeOneToManyRelationships)
                 {
                     var oneTorelationships = Service.GetOneToManyRelationships(thisType);
                     for (var j = 0; j < oneTorelationships.Count(); j++)
                     {
                         var relationship = oneTorelationships.ElementAt(j);
                         try
                         {
                             var isCustomRelationship = Service.FieldExists(relationship.ReferencingAttribute, relationship.ReferencingEntity) &&
                                                        Service.GetFieldMetadata(relationship.ReferencingAttribute, relationship.ReferencingEntity).IsCustomField;
                             allRelationship.Add(new RelationshipExport(relationship.SchemaName,
                                                                        relationship.ReferencedEntity, relationship.ReferencingEntity,
                                                                        isCustomRelationship, false,
                                                                        relationship.DisplayRelated
                                                                        , null, relationship.ReferencingAttribute,
                                                                        RelationshipExport.RelationshipType.OneToMany, false, relationship.IsCustomLabel,
                                                                        null, relationship.GetRelationshipLabel
                                                                        , 0, relationship.DisplayOrder, relationship.MetadataId, relationship.DeleteCascadeConfiguration));
                         }
                         catch (Exception ex)
                         {
                             response.AddResponseItem(
                                 new CustomisationExporterResponseItem("Error Exporting Relationship",
                                                                       relationship.SchemaName, ex));
                         }
                     }
                 }
             }
             catch (Exception ex)
             {
                 response.AddResponseItem(new CustomisationExporterResponseItem("Error Exporting Relationships",
                                                                                thisType, ex));
             }
         }
         var fileName = "RelationshipExport_" + DateTime.Now.ToFileTime() + ".csv";
         CsvUtility.CreateCsv(request.SaveToFolder.FolderPath, fileName, allRelationship);
         response.RelationshipsFileName = fileName;
         response.Folder = request.SaveToFolder.FolderPath;
     }
 }
        private void ProcessForFields(CustomisationExporterRequest request, CustomisationExporterResponse response,
                                      LogController controller)
        {
            if (request.Fields)
            {
                var allFields = new List <FieldExport>();
                var types     = GetRecordTypesToExport(request).OrderBy(t => Service.GetDisplayName(t)).ToArray();
                var count     = types.Count();
                for (var i = 0; i < count; i++)
                {
                    var thisType      = types.ElementAt(i);
                    var thisTypeLabel = Service.GetDisplayName(thisType);
                    var primaryField  = Service.GetPrimaryField(thisType);
                    controller.UpdateProgress(i, count, "Exporting Fields For " + thisTypeLabel);
                    try
                    {
                        var fields =
                            Service.GetFields(thisType)
                            .Where(f => !Service.GetFieldLabel(f, thisType).IsNullOrWhiteSpace())
                            .ToArray();
                        var numberOfFields = fields.Count();
                        for (var j = 0; j < numberOfFields; j++)
                        {
                            var field      = fields.ElementAt(j);
                            var fieldLabel = Service.GetFieldLabel(field, thisType);
                            try
                            {
                                var thisFieldType  = Service.GetFieldType(field, thisType);
                                var displayRelated = Service.IsLookup(field, thisType) &&
                                                     Service.GetFieldMetadata(field, thisType).IsDisplayRelated;
                                var picklist = thisFieldType == RecordFieldType.Picklist
                                    ? CreatePicklistName(field, thisType)
                                    : "N/A";
                                string referencedType = "N/A";
                                if (Service.IsLookup(field, thisType))
                                {
                                    referencedType = Service.GetLookupTargetType(field, thisType);
                                }
                                var isString   = Service.IsString(field, thisType);
                                int maxLength  = isString ? Service.GetMaxLength(field, thisType) : -1;
                                var textFormat = thisFieldType == RecordFieldType.String
                                    ? Service.GetFieldMetadata(field, thisType).TextFormat.ToString()
                                    : null;
                                var integerFormat = thisFieldType == RecordFieldType.Integer
                                    ? Service.GetFieldMetadata(field, thisType).IntegerFormat.ToString()
                                    : null;
                                var includeTime = thisFieldType == RecordFieldType.Date &&
                                                  Service.GetFieldMetadata(field, thisType).IncludeTime;
                                var minValue  = "-1";
                                var maxValue  = "-1";
                                var precision = "-1";
                                if (thisFieldType == RecordFieldType.Decimal)
                                {
                                    minValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MinValue.ToString(CultureInfo.InvariantCulture);
                                    maxValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MaxValue.ToString(CultureInfo.InvariantCulture);
                                    precision =
                                        Service.GetFieldMetadata(field, thisType)
                                        .DecimalPrecision.ToString(CultureInfo.InvariantCulture);
                                }
                                if (thisFieldType == RecordFieldType.Double)
                                {
                                    minValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MinValue.ToString(CultureInfo.InvariantCulture);
                                    maxValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MaxValue.ToString(CultureInfo.InvariantCulture);
                                    precision =
                                        Service.GetFieldMetadata(field, thisType)
                                        .DecimalPrecision.ToString(CultureInfo.InvariantCulture);
                                }
                                if (thisFieldType == RecordFieldType.Integer)
                                {
                                    minValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MinValue.ToString(CultureInfo.InvariantCulture);
                                    maxValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MaxValue.ToString(CultureInfo.InvariantCulture);
                                }
                                if (thisFieldType == RecordFieldType.Money)
                                {
                                    minValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MinValue.ToString(CultureInfo.InvariantCulture);
                                    maxValue =
                                        Service.GetFieldMetadata(field, thisType)
                                        .MaxValue.ToString(CultureInfo.InvariantCulture);
                                }

                                var fieldExport = new FieldExport(thisTypeLabel, thisType,
                                                                  fieldLabel, field, Service.GetFieldType(field, thisType),
                                                                  Service.GetFieldMetadata(field, thisType).IsCustomField,
                                                                  Service.GetFieldMetadata(field, thisType).IsMandatory,
                                                                  Service.GetFieldMetadata(field, thisType).Description, primaryField == field,
                                                                  Service.GetFieldMetadata(field, thisType).Audit,
                                                                  Service.GetFieldMetadata(field, thisType).Searchable
                                                                  , displayRelated, referencedType, maxLength, textFormat, integerFormat, includeTime, minValue,
                                                                  maxValue, precision, picklist, Service.GetFieldMetadata(field, thisType).MetadataId);
                                if (Service.IsString(field, thisType))
                                {
                                    fieldExport.MaxLength = Service.GetMaxLength(field, thisType);
                                }
                                allFields.Add(fieldExport);
                            }
                            catch (Exception ex)
                            {
                                response.AddResponseItem(new CustomisationExporterResponseItem("Error Exporting Field",
                                                                                               field, ex));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.AddResponseItem(
                            new CustomisationExporterResponseItem("Error Exporting Record Type Fields",
                                                                  thisType, ex));
                    }
                }
                var fileName = "FieldExport_" + DateTime.Now.ToFileTime() + ".csv";
                CsvUtility.CreateCsv(request.SaveToFolder.FolderPath, fileName, allFields);
                response.FieldsFileName = fileName;
                response.Folder         = request.SaveToFolder.FolderPath;
            }
        }
        private void ProcessForOptionSets(CustomisationExporterRequest request, CustomisationExporterResponse response,
                                          LogController controller)
        {
            if (!request.FieldOptionSets && !request.SharedOptionSets)
            {
                return;
            }

            var allOptions = new List <OptionExport>();

            if (request.FieldOptionSets)
            {
                var types = GetRecordTypesToExport(request).OrderBy(t => Service.GetDisplayName(t)).ToArray();
                var count = types.Count();
                for (var i = 0; i < count; i++)
                {
                    var thisType      = types.ElementAt(i);
                    var thisTypeLabel = Service.GetDisplayName(thisType);
                    controller.UpdateProgress(i, count, "Exporting Options For " + thisTypeLabel);
                    try
                    {
                        var fields =
                            Service.GetFields(thisType)
                            .Where(f => !Service.GetFieldLabel(f, thisType).IsNullOrWhiteSpace())
                            .Where(f => OptionSetTypes.Contains(Service.GetFieldType(f, thisType)))
                            .ToArray();
                        var numberOfFields = fields.Count();
                        for (var j = 0; j < numberOfFields; j++)
                        {
                            var field      = fields.ElementAt(j);
                            var fieldLabel = Service.GetFieldLabel(field, thisType);
                            try
                            {
                                var keyValues = Service.GetPicklistKeyValues(field, thisType);
                                foreach (var keyValue in keyValues)
                                {
                                    allOptions.Add(new OptionExport(thisTypeLabel, thisType,
                                                                    fieldLabel, field, keyValue.Key, keyValue.Value, false, null,
                                                                    JoinTypeAndFieldName(field, thisType)));
                                }
                            }
                            catch (Exception ex)
                            {
                                response.AddResponseItem(
                                    new CustomisationExporterResponseItem("Error Exporting Options For Field",
                                                                          field, ex));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        response.AddResponseItem(
                            new CustomisationExporterResponseItem("Error Exporting Record Type Options",
                                                                  thisType, ex));
                    }
                }
            }
            if (request.SharedOptionSets)
            {
                var sets      = Service.GetSharedPicklists();
                var countSets = sets.Count();
                for (var i = 0; i < countSets; i++)
                {
                    var thisSet = sets.ElementAt(i);
                    controller.UpdateProgress(i, countSets, "Exporting Share Option Sets");
                    try
                    {
                        var options = thisSet.PicklistOptions;
                        var label   = thisSet.DisplayName;
                        foreach (var option in options)
                        {
                            allOptions.Add(new OptionExport(null, null,
                                                            null, null, option.Key, option.Value, true, thisSet.SchemaName, label));
                        }
                    }
                    catch (Exception ex)
                    {
                        response.AddResponseItem(
                            new CustomisationExporterResponseItem("Error Exporting Shared Option Set",
                                                                  thisSet.SchemaName, ex));
                    }
                }
            }
            var fileName = "OptionsExport_" + DateTime.Now.ToFileTime() + ".csv";

            CsvUtility.CreateCsv(request.SaveToFolder.FolderPath, fileName, allOptions);
            response.OptionSetsFileName = fileName;
            response.Folder             = request.SaveToFolder.FolderPath;
        }
Exemplo n.º 13
0
        private void DownloadSpreadsheet(bool csv = false)
        {
            var extension   = csv ? "csv" : "xlsx";
            var newFileName = ApplicationController.GetSaveFileName(string.Format("{0}", RecordService.GetCollectionName(RecordType)), extension);

            ApplicationController.DoOnAsyncThread(() =>
            {
                try
                {
                    LoadingViewModel.IsLoading = true;
                    if (!string.IsNullOrWhiteSpace(newFileName))
                    {
                        var folder   = Path.GetDirectoryName(newFileName);
                        var fileName = Path.GetFileName(newFileName);
                        var fields   = FieldMetadata.ToArray();
                        var started  = DateTime.UtcNow;

                        var labelFuncDictionary = new Dictionary <string, Func <string, string> >();
                        foreach (var fm in FieldMetadata)
                        {
                            labelFuncDictionary.Add(fm.AliasedFieldName ?? fm.FieldName, s => fm.OverrideLabel ?? RecordService.GetFieldLabel(fm.FieldName, fm.AltRecordType ?? RecordType));
                        }

                        var displayFuncDictionary = new Dictionary <string, Func <object, string, string> >();
                        foreach (var fm in FieldMetadata)
                        {
                            displayFuncDictionary.Add(fm.AliasedFieldName ?? fm.FieldName, (o, s) => RecordService.GetFieldAsDisplayString(fm.AltRecordType ?? RecordType, fm.FieldName, ((IRecord)o).GetField(s)));
                        }

                        if (csv)
                        {
                            CsvUtility.CreateCsv(folder, fileName, GetGridRecords(true).Records,
                                                 fields.Select(f => f.AliasedFieldName ?? f.FieldName),
                                                 (f) => labelFuncDictionary[f](f),
                                                 (r, f) => displayFuncDictionary[f](r, f));
                        }
                        else
                        {
                            var sheetName      = "Records";
                            var excelCellTypes = new Dictionary <string, CellDataType>();
                            foreach (var field in fields)
                            {
                                var fieldType = field.AltRecordType != null
                                    ? RecordService.GetFieldType(field.FieldName, field.AltRecordType)
                                    : RecordService.GetFieldType(field.FieldName, RecordType);
                                if (fieldType == RecordFieldType.BigInt || fieldType == RecordFieldType.Decimal || fieldType == RecordFieldType.Double || fieldType == RecordFieldType.Integer || fieldType == RecordFieldType.Money)
                                {
                                    excelCellTypes.Add(field.AliasedFieldName ?? field.FieldName, CellDataType.Number);
                                }
                                else if (fieldType == RecordFieldType.Date)
                                {
                                    excelCellTypes.Add(field.AliasedFieldName ?? field.FieldName, CellDataType.Date);
                                }
                                else
                                {
                                    excelCellTypes.Add(field.AliasedFieldName ?? field.FieldName, CellDataType.String);
                                }
                            }

                            ExcelUtility.CreateXlsx(folder, fileName,
                                                    new Dictionary <string, IEnumerable>()
                            {
                                { sheetName, GetGridRecords(true).Records }
                            },
                                                    new Dictionary <string, IEnumerable <string> >()
                            {
                                { sheetName, fields.Select(f => f.AliasedFieldName ?? f.FieldName) }
                            },
                                                    new Dictionary <string, Func <object, string, object> >()
                            {
                                { sheetName, (r, f) => displayFuncDictionary[f](r, f) }
                            },
                                                    new Dictionary <string, Func <string, string> >()
                            {
                                { sheetName, (f) => labelFuncDictionary[f](f) }
                            },
                                                    new Dictionary <string, Func <string, CellDataType> >()
                            {
                                { sheetName, (f) => excelCellTypes[f] }
                            });
                        }
                        ApplicationController.LogEvent("Download " + extension.ToUpper(), new Dictionary <string, string>
                        {
                            { "Is Completed Event", true.ToString() },
                            { "Type", RecordType },
                            { "Seconds Taken", (DateTime.UtcNow - started).TotalSeconds.ToString() },
                        });
                        ApplicationController.StartProcess("explorer.exe", "/select, \"" + Path.Combine(folder, fileName) + "\"");
                    }
                }
                catch (Exception ex)
                {
                    ApplicationController.ThrowException(ex);
                }
                finally
                {
                    LoadingViewModel.IsLoading = false;
                }
            });
        }