public void ServiceRequestDetails() { // Arrange ServiceRequestController controller = new ServiceRequestController(); OpenJobModel openJobModel = new OpenJobModel { FirstName = "Albumius", LastName = "Artistus", Email = "*****@*****.**", PhoneNumber = "715-555-5555", Date = DateTime.Now, Message = "hackle frackle", TechNotes = "I am a technote", Estimate = 10.00, FinalCost = 10.00, WorkComplete = true, AssetModel = "1337", AssetType = "Laptop" }; var fullName = openJobModel.FirstName.ToString() + openJobModel.LastName.ToString(); var email = openJobModel.Email.ToString(); var phoneNumber = openJobModel.PhoneNumber.ToString(); var date = openJobModel.Date.ToString(); var message = openJobModel.Message.ToString(); var body = "Lead details: {0} // {1} // {2} // {3} // {4}"; SmtpClient client = new SmtpClient(); MailMessage mailMessage = new MailMessage(); mailMessage.To.Add("*****@*****.**"); mailMessage.Subject = "Service Request lead sent " + DateTime.Now.ToString(); mailMessage.Body = string.Format(body, fullName, email, phoneNumber, date, message); client.Send(mailMessage); // Act ViewResult result = controller.ServiceRequestDetails(openJobModel) as ViewResult; // Assert Assert.IsNotNull(result); }
public void ServiceRequestForm() { // Arrange ServiceRequestController controller = new ServiceRequestController(); // Act ViewResult result = controller.ServiceRequestForm() as ViewResult; // Assert Assert.IsNotNull(result); }
public void Delete_ServiceRequest_Return_NotFound() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); sr.id = new Guid("dadd45b9-d13d-4fd1-9f29-514aa8459e0d"); var contentStatus = (NotFoundResult)controller.DeleteServiceRequest(sr.id).Result.Result; Assert.NotNull(contentStatus); Assert.Equal(404, contentStatus.StatusCode); } }
public void Put_ServiceRequest_Return_BadRequest_For_CurrentStatus() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); sr.currentStatus = "Invalid code"; var controller = new ServiceRequestController(context); var contentStatus = (BadRequestObjectResult)controller.PutServiceRequest(sr.id, sr).Result; Assert.NotNull(contentStatus); Assert.Equal(400, contentStatus.StatusCode); } }
public void Put_ServiceRequest_Return_BadRequest_For_Id() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); sr.currentStatus = "InProgress"; var controller = new ServiceRequestController(context); var contentStatus = (BadRequestObjectResult)controller.PutServiceRequest(new Guid("dadd45b9-d13d-4fd1-9f29-514aa8459e0d"), sr).Result; Assert.NotNull(contentStatus); Assert.Equal(400, contentStatus.StatusCode); } }
public override void ExecuteExtention(ImportSolutionRequest request, ImportSolutionResponse response, ServiceRequestController controller) { //just use the method in DeployPackageService to do the import var xrmRecordService = new XrmRecordService(request.Connection, ConnectionFactory); var service = new DeployPackageService(null); var importItems = service.ImportSolutions(new[] { request.SolutionZip.FileName }, controller.Controller, xrmRecordService); response.AddResponseItems(importItems.Select(it => new ImportSolutionResponseItem(it))); response.Connection = request.Connection; response.Message = $"The Solution Has Been Deployed Into {request.Connection}"; }
public override void ExecuteExtention(ImportExcelRequest request, ImportExcelResponse response, ServiceRequestController controller) { controller.Controller.UpdateProgress(0, 1, "Loading Records For Import"); var dictionary = LoadMappingDictionary(request, controller.Controller); var importService = new SpreadsheetImportService(XrmRecordService); var responseItems = importService.DoImport(dictionary, request.MaskEmails, request.MatchRecordsByName, request.UpdateOnly, controller, executeMultipleSetSize: request.ExecuteMultipleSetSize, targetCacheLimit: request.TargetCacheLimit); response.Connection = XrmRecordService.XrmRecordConfiguration; response.LoadSpreadsheetImport(responseItems); response.Message = "The Import Process Has Completed"; }
public void ImportXml(string folder, ServiceRequestController controller, ImportXmlResponse response, bool maskEmails = false, bool includeOwner = false, bool matchByName = true) { controller.UpdateProgress(0, 1, "Loading XML Files"); var entities = LoadEntitiesFromXmlFiles(folder, controller.Controller); var matchOption = matchByName ? DataImportService.MatchOption.PrimaryKeyThenName : DataImportService.MatchOption.PrimaryKeyOnly; var importResponse = DataImportService.DoImport(entities, controller, maskEmails, matchOption: matchOption, includeOwner: includeOwner); response.Connection = XrmRecordService.XrmRecordConfiguration; response.LoadDataImport(importResponse); response.Message = "The Import Process Has Completed"; }
public override void ExecuteExtention(ImportRecordsRequest request, ImportRecordsResponse response, ServiceRequestController controller) { //just use the method in ImportXmlService to do the import var xrmRecordService = new XrmRecordService(request.Connection); var service = new ImportXmlService(xrmRecordService); var entities = service.LoadEntitiesFromXmlFiles(request.XmlFiles.Select(fr => fr.FileName).ToArray()); var importResponses = service.DataImportService.DoImport(entities, controller, false); response.LoadDataImport(importResponses); }
public void ImportXml(IImportXmlRequest request, ServiceRequestController controller, ImportXmlResponse response, bool maskEmails = false, bool includeOwner = false, bool matchByName = true, int?executeMultipleSetSize = null, int?targetCacheLimit = null) { controller.UpdateProgress(0, 1, "Loading XML Files"); var entities = request.GetOrLoadEntitiesForImport(controller.Controller).Values.ToArray(); var matchOption = matchByName ? MatchOption.PrimaryKeyThenName : MatchOption.PrimaryKeyOnly; var importResponse = DataImportService.DoImport(entities, controller, maskEmails, matchOption: matchOption, includeOwner: includeOwner, executeMultipleSetSize: executeMultipleSetSize, targetCacheLimit: targetCacheLimit); response.Connection = XrmRecordService.XrmRecordConfiguration; response.LoadDataImport(importResponse); response.Message = "The Import Process Has Completed"; }
public void GetAll_ServiceRequests_Return_NoContent() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); var contentStatus = (NoContentResult)controller.GetserviceRequests().Result.Result; Assert.NotNull(contentStatus); Assert.Equal(204, contentStatus.StatusCode); } }
public void Delete_ServiceRequest_Request_Is_Deleted() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); _ = controller.PostServiceRequest(sr); var result = controller.DeleteServiceRequest(sr.id); var deletedItem = controller.GetServiceRequest(sr.id); Assert.NotNull(result); Assert.Equal(sr, result.Result.Value); Assert.Null(deletedItem.Result.Value); } }
public void Put_ServiceRequest_Return_ServiceRequest() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); sr.currentStatus = "InProgress"; var controller = new ServiceRequestController(context); _ = controller.PutServiceRequest(sr.id, sr); var result = controller.GetServiceRequest(sr.id); Assert.NotNull(result); Assert.Equal(sr, result.Result.Value); } }
public void Post_ServiceRequest_Return_201() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); var result = (CreatedAtActionResult)controller.PostServiceRequest(sr).Result.Result; Assert.NotNull(result); Assert.NotNull(result.StatusCode); Assert.Equal(201, result.StatusCode); } }
public void Post_ServiceRequest_Return_BadRequest() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); sr.currentStatus = "invalid status"; var controller = new ServiceRequestController(context); var content = (BadRequestObjectResult)controller.PostServiceRequest(sr).Result.Result; Assert.NotNull(content); Assert.NotNull(content.StatusCode); Assert.Equal(400, content.StatusCode); } }
public void Get_ServiceRequest_Return_ServiceRequest() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); var result = controller.PostServiceRequest(sr); result = controller.GetServiceRequest(sr.id); Assert.NotNull(result); Assert.NotNull(result.Result); Assert.Equal(sr, result.Result.Value); } }
public ActionResult Index() { if (Session["Usuario"] == null) { return(RedirectToAction("Login", "User")); } else { MStatistics objStatistics = new MStatistics(); int intEmployee = PersonController.fnListPerson(null, 2, null, true).Count(); //2-empleado objStatistics.NroEmployee = intEmployee; int intClient = PersonController.fnListPerson(null, 1, null, true).Count(); //1-Client objStatistics.NroClient = intClient; objStatistics.ServicesProcess = 0; objStatistics.servicesCompleted = 0; MMEnterprisesEntities db = new MMEnterprisesEntities(); var Service = ServiceRequestController.fnListServiceRequest(null, null, null, null, null); //1-Client if (Service != null && Service.Count > 0) { var ListTableCatalog = db.VWListCatalog.Where(t => t.IdTable == "SERVICESTATUS").ToList(); if (ListTableCatalog.Count > 0) { var objProcesando = ListTableCatalog.Where(p => p.DetailDesc == "Procesando").First(); var objFinalizado = ListTableCatalog.Where(p => p.DetailDesc == "Finalizado").First(); if (objProcesando != null) { var ServicesProcess = Service.FindAll(p => p.IdServiceStatus == objProcesando.IdCatalogDetail).ToList(); objStatistics.ServicesProcess = ServicesProcess.Count(); } if (objFinalizado != null) { var servicesCompleted = Service.FindAll(p => p.IdServiceStatus == objFinalizado.IdCatalogDetail).ToList(); objStatistics.servicesCompleted = servicesCompleted.Count(); } } } return(View(objStatistics)); } }
public void CreateNewServiceRequest(ServiceContract serviceContract, Client client, string desc) { endCall(); ServiceRequestController serviceRequestController = new ServiceRequestController(); RequestController requestController = new RequestController(); ServiceRequest serviceRequest = new ServiceRequest( DateTime.Now, null, callLog, desc ); serviceRequestController.Create(serviceRequest); serviceRequestController.Set(serviceContract, serviceRequest); requestController.Set(client, serviceRequest); }
public override void ExecuteExtention(ImportSolutionRequest request, ImportSolutionResponse response, ServiceRequestController controller) { //just use the method in DeployPackageService to do the import var xrmRecordService = new XrmRecordService(request.Connection, ConnectionFactory); var service = new DeployPackageService(null); var importSolutionResponse = service.ImportSolutions(new[] { request.SolutionZip.FileName }, controller.Controller, xrmRecordService); response.LoadImportSolutionsResponse(importSolutionResponse); response.Connection = request.Connection; if (!importSolutionResponse.Success) { response.Message = $"There was an error importing the solution"; } else { response.Message = $"The Solution Has Been Deployed Into {request.Connection}"; } }
private async Task GetCustomerAppointmentInfo(IDialogContext context, IAwaitable <string> result) { string customerId = await result; var customerAppointment = new ServiceRequestController().GetAppointmentInformation(customerId); switch (customerAppointment.IsConfirmed) { case true: context.Done(GetAppointmentConfirmationInformation(customerAppointment)); break; case false: context.Call(new AppointmentConfirmationDialog(customerAppointment), BackFromConfirmationPrompt); break; default: break; } }
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"; }
public void GetAll_ServiceRequests_Return_ServiceRequest() { using (var context = new ServiceRequestContext()) { ServiceRequest sr = GetServiceRequest(); var controller = new ServiceRequestController(context); _ = controller.PostServiceRequest(sr); ServiceRequest sr2 = GetServiceRequest(); sr2.id = new Guid("dadd45b9-d13d-4fd1-9f29-514aa8459e0d"); List <ServiceRequest> srs = new List <ServiceRequest>(); srs.Add(sr); srs.Add(sr2); _ = controller.PostServiceRequest(sr2); var results = controller.GetserviceRequests(); Assert.NotNull(results); Assert.NotNull(results.Result); Assert.Equal(srs, results.Result.Value); } }
public override void ExecuteExtention(TextSearchRequest request, TextSearchResponse response, ServiceRequestController controller) { controller.UpdateProgress(0, 1, "Loading Text Search"); var document = DocumentWriter.NewDocument(); var firstSection = document.AddSection(); var nextSection = document.AddSection(); var container = new TextSearchContainer(request, response, controller.Controller, nextSection); ProcessRecordsReferencingTheWord(container); //insert title/summary firstSection.AddTitle("Text Search"); var table = firstSection.Add2ColumnTable(); table.AddFieldToTable("Execution Time", DateTime.Now.ToString(StringFormats.DateTimeFormat)); table.AddFieldToTable("Search Operator", request.Operator.ToString()); table.AddFieldToTable("Search Terms", string.Join(", ", request.SearchTerms.Select(s => "\"" + s.Text + "\""))); firstSection.AddTableOfContents(container.Bookmarks); //save document container.Controller.TurnOffLevel2(); container.Controller.UpdateProgress(1, 2, "Creating Document"); var folder = container.Request.SaveToFolder; var fileName = string.Format("Record Extract - {0} - {1}", "TextSearch", DateTime.Now.ToString("yyyyMMddHHmmss")); if (container.Request.GenerateDocument) { fileName = document.Save(folder, fileName, container.Request.DocumentFormat); container.Response.Folder = container.Request.SaveToFolder.FolderPath; container.Response.FileName = fileName; } container.Response.GenerateSummaryItems(Service); if (!container.Response.Summary.Any()) { container.Response.Message = "No Matches Were Found For The Search Criteria"; } }
private void DeployPackage(DeployPackageRequest request, ServiceRequestController controller, DeployPackageResponse response) { var xrmRecordService = new XrmRecordService(request.Connection, controller.Controller); var packageFolder = request.FolderContainingPackage.FolderPath; var solutionFiles = Directory.GetFiles(packageFolder, "*.zip") .OrderBy(s => s) .ToArray(); var importItems = ImportSolutions(solutionFiles, controller.Controller, xrmRecordService); response.AddResponseItems(importItems.Select(it => new DataImportResponseItem(it.Type, null, it.Name, null, $"{it.Result} - {it.ErrorCode} - {it.ErrorText}", null, it.GetUrl()))); foreach (var childFolder in Directory.GetDirectories(packageFolder)) { if (new DirectoryInfo(childFolder).Name == "Data") { var dataImportService = new ImportXmlService(xrmRecordService); var importResponse = new ImportXmlResponse(); dataImportService.ImportXml(childFolder, controller, importResponse); response.LoadImportxmlResponse(importResponse); } } }
public override void ExecuteExtention(RecordExtractRequest request, RecordExtractResponse response, ServiceRequestController controller) { var document = DocumentWriter.NewDocument(); var firstSection = document.AddSection(); var nextSection = document.AddSection(); var extractToDocumentRequest = new RecordExtractToDocumentRequest(request.RecordLookup, nextSection, controller.Controller, request.DetailOfRelatedRecords , request.RecordTypesOnlyDisplayName.Where(r => r.RecordType != null).Select(r => r.RecordType.Key).ToArray() , request.FieldsToExclude, request.RecordTypesToExclude.Where(r => r.RecordType != null).Select(r => r.RecordType.Key).ToArray() , request.IncludeCreatedByAndOn, request.IncludeModifiedByAndOn, request.IncludeCrmOwner, request.IncludeState, request.IncludeStatus, request.StripHtmlTags, request.CustomHtmlFields); var extractResponse = ExtractRecordToDocument(extractToDocumentRequest); response.AddResponseItems(extractResponse.ResponseItems); //insert title/summary firstSection.AddTitle("Record Extract"); var table = firstSection.Add2ColumnTable(); table.AddFieldToTable("Execution Time", DateTime.Now.ToString(StringFormats.DateTimeFormat)); table.AddFieldToTable("Record Type", Service.GetDisplayName(request.RecordLookup.RecordType)); table.AddFieldToTable("Record Name", extractResponse.Record.GetStringField(Service.GetPrimaryField(request.RecordLookup.RecordType))); firstSection.AddTableOfContents(extractResponse.Bookmarks); //save document controller.UpdateProgress(1, 2, "Creating Document"); var folder = request.SaveToFolder; var recordToExtractname = extractResponse.Record.GetStringField(Service.GetPrimaryField(request.RecordLookup.RecordType)); var fileName = string.Format("Record Extract - {0} - {1}", recordToExtractname, DateTime.Now.ToString("yyyyMMddHHmmss")); fileName = document.Save(folder, fileName, request.DocumentFormat); response.Folder = request.SaveToFolder.FolderPath; response.FileName = fileName; response.Message = "The Document Has Been Generated"; }
public override void ExecuteExtention(DeployPackageRequest request, DeployPackageResponse response, ServiceRequestController controller) { DeployPackage(request, controller, response); }
public SpreadsheetImportResponse DoImport(Dictionary <IMapSpreadsheetImport, IEnumerable <IRecord> > mappings, bool maskEmails, bool matchByName, bool updateOnly, ServiceRequestController controller, int?executeMultipleSetSize = null, bool useAmericanDates = false, int?targetCacheLimit = null) { var response = new SpreadsheetImportResponse(); var parseResponse = ParseIntoEntities(mappings, useAmericanDates: useAmericanDates); response.LoadParseResponse(parseResponse); var dataImportService = new DataImportService(XrmRecordService); var matchKeyDictionary = new Dictionary <string, IEnumerable <string> >(); foreach (var map in mappings.Keys) { if (map.AltMatchKeys != null && map.AltMatchKeys.Any()) { if (matchKeyDictionary.ContainsKey(map.TargetType)) { throw new NotSupportedException($"Error Type {map.TargetType} Is Defined With Multiple Match Keys"); } matchKeyDictionary.Add(map.TargetType, map.AltMatchKeys.Select(mk => mk.TargetField).ToArray()); } } response.LoadDataImport(dataImportService.DoImport(parseResponse.GetParsedEntities(), controller, maskEmails, matchOption: matchByName ? MatchOption.PrimaryKeyThenName : MatchOption.PrimaryKeyOnly, loadExistingErrorsIntoSummary: response.ResponseItems, altMatchKeyDictionary: matchKeyDictionary, updateOnly: updateOnly, includeOwner: true, containsExportedConfigFields: false, executeMultipleSetSize: executeMultipleSetSize, targetCacheLimit: targetCacheLimit)); return(response); }
public override void ExecuteExtention(ImportCsvsRequest request, ImportCsvsResponse response, ServiceRequestController controller) { controller.Controller.UpdateProgress(0, 1, "Loading Records For Import"); var dictionary = LoadMappingDictionary(request); var importService = new SpreadsheetImportService(XrmRecordService); var responseItem = importService.DoImport(dictionary, request.MaskEmails, request.MatchByName, request.UpdateOnly, controller, useAmericanDates: request.DateFormat == DateFormat.American); response.Connection = XrmRecordService.XrmRecordConfiguration; response.LoadSpreadsheetImport(responseItem); response.Message = "The Import Process Has Completed"; }
public override void ExecuteExtention(DeployIntoFieldRequest request, DeployIntoFieldResponse response, ServiceRequestController controller) { var records = new List <IRecord>(); var publishIds = new List <string>(); var numberToDo = request.Files.Count(); var numberDone = 0; foreach (var file in request.Files.Select(f => f?.Replace("∕", "∕"))) { var fileInfo = new FileInfo(file); controller.UpdateProgress(++numberDone, numberToDo, "Importing " + fileInfo.Name); var thisResponseItem = new DeployIntoFieldResponseItem() { Name = fileInfo.Name }; response.AddResponseItem(thisResponseItem); try { var containingFolderName = fileInfo.Directory.Name; var containingFolderParentName = fileInfo.Directory.Parent != null ? fileInfo.Directory.Parent.Name : null; //get target record type string recordType = null; if (Service.GetAllRecordTypes().Any(r => r == containingFolderName)) { recordType = Service.GetAllRecordTypes().First(r => r == containingFolderName); } else if (Service.GetAllRecordTypes().Any(r => Service.GetDisplayName(r)?.ToLower() == containingFolderName.ToLower())) { recordType = Service.GetAllRecordTypes().First(r => Service.GetDisplayName(r)?.ToLower() == containingFolderName.ToLower()); } else { throw new NullReferenceException($"Could not find matching type by logical or display name for folder name of {containingFolderName}"); } thisResponseItem.RecordType = recordType; if (recordType == Entities.adx_webfile) { //this one goes into an attachment var matchingRecord = GetRecordToDeployInto(recordType, fileInfo.Name, containingFolderParentName); if (matchingRecord == null) { throw new NullReferenceException($"There is no {Service.GetDisplayName(recordType)} record name {fileInfo.Name} to load the file attachment into"); } thisResponseItem.Link = new Url(Service.GetWebUrl(matchingRecord.Type, matchingRecord.Id), "Open"); //get matching attachment by name else create a new one var fileAttachments = Service.RetrieveAllAndClauses(Entities.annotation, new[] { new Condition(Fields.annotation_.filename, ConditionType.Equal, fileInfo.Name), new Condition(Fields.annotation_.objectid, ConditionType.Equal, matchingRecord.Id) }).OrderBy(n => n.GetDateTime(Fields.annotation_.createdon)).ToArray(); var contentBytes = File.ReadAllBytes(file); var contentBase64String = Convert.ToBase64String(contentBytes); if (fileAttachments.Any()) { //lets update the last modifed one var attachmentToUpdate = fileAttachments.First(); if (attachmentToUpdate.GetStringField(Fields.annotation_.documentbody) != contentBase64String) { attachmentToUpdate.SetField(Fields.annotation_.documentbody, contentBase64String, Service); Service.Update(attachmentToUpdate, new[] { Fields.annotation_.documentbody }); thisResponseItem.Updated = true; } } else { //lets create a new attachment var newAttachment = Service.NewRecord(Entities.annotation); newAttachment.SetLookup(Fields.annotation_.objectid, matchingRecord.Id, matchingRecord.Type); newAttachment.SetField(Fields.annotation_.subject, fileInfo.Name, Service); newAttachment.SetField(Fields.annotation_.filename, fileInfo.Name, Service); newAttachment.SetField(Fields.annotation_.documentbody, contentBase64String, Service); Service.Create(newAttachment); thisResponseItem.Created = true; } } else { //get the record with the same name as the file var nameToMatch = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".")); var matchingRecord = GetRecordToDeployInto(recordType, nameToMatch, containingFolderParentName); if (matchingRecord == null) { throw new NullReferenceException($"There is no {Service.GetDisplayName(recordType)} record name {fileInfo.Name} to load the file attachment into"); } thisResponseItem.Link = new Url(Service.GetWebUrl(matchingRecord.Type, matchingRecord.Id), "Open"); var targetField = GetTargetField(fileInfo, recordType); var contentText = File.ReadAllText(file); if (matchingRecord.GetStringField(targetField) != contentText) { matchingRecord.SetField(targetField, contentText, Service); Service.Update(matchingRecord, new[] { targetField }); thisResponseItem.Updated = true; } } } catch (Exception ex) { thisResponseItem.Exception = ex; } } }
public override void ExecuteExtention(RecordCountsRequest request, RecordCountsResponse response, ServiceRequestController controller) { controller.LogLiteral("Loading Types"); var excludeTheseTypes = new[] { Entities.msdyn_componentlayer, Entities.msdyn_solutioncomponentsummary, Entities.msdyn_nonrelationalds, Entities.datalakeworkspace, Entities.datalakeworkspacepermission }; var recordTypes = request.AllRecordTypes ? Service.GetAllRecordTypes() .Except(excludeTheseTypes) .Where(r => Service.GetRecordTypeMetadata(r).Searchable) .OrderBy(n => Service.GetDisplayName(n)) .ToArray() : request.RecordTypes.Select(p => p.RecordType.Key).ToArray(); if (request.OnlyIncludeSelectedOwner) { recordTypes = recordTypes.Where(r => Service.GetRecordTypeMetadata(r).HasOwner).ToArray(); } var numberOfTypes = recordTypes.Count(); var numberOfTypesCompleted = 0; var noOwnerIndex = "Organisation"; var recordCountsByUser = new Dictionary <string, Dictionary <string, long> >(); //due to limitations in crm web service cannot do a standard aggregate //as they are limitied to 50K records OOTB //need to query all records and manually aggregate foreach (var recordType in recordTypes) { var thisDictionary = new Dictionary <string, long>(); try { var metadata = Service.GetRecordTypeMetadata(recordType); var hasOwner = metadata.HasOwner; if (!hasOwner) { thisDictionary.Add(noOwnerIndex, 0); } long totalThisIteration = 0; var func = hasOwner ? ((records) => { totalThisIteration += records.Count(); controller.UpdateProgress(numberOfTypesCompleted, numberOfTypes, string.Format("Counting {0} ({1})", recordType, totalThisIteration)); foreach (var record in records) { var ownerType = record.GetLookupType("ownerid"); var ownerId = record.GetLookupId("ownerid"); var format = string.Format("{0}:{1}", ownerType, ownerId); if (!thisDictionary.ContainsKey(format)) { thisDictionary.Add(format, 0); } thisDictionary[format]++; } }) : (Action <IEnumerable <IRecord> >)((records) => { totalThisIteration += records.Count(); controller.UpdateProgress(numberOfTypesCompleted, numberOfTypes, string.Format("Counting {0} ({1})", recordType, totalThisIteration)); foreach (var record in records) { thisDictionary[noOwnerIndex]++; } }); var fields = hasOwner ? new[] { "ownerid" } : new string[0]; var conditions = request.OnlyIncludeSelectedOwner ? new[] { new Condition("ownerid", ConditionType.Equal, request.Owner.Id) } : new Condition[0]; var query = new QueryDefinition(recordType); var filter = new Filter(); filter.Conditions.AddRange(conditions); query.RootFilter.SubFilters.Add(filter); query.Fields = fields; Service.ProcessResults(query, func); recordCountsByUser.Add(recordType, thisDictionary); } catch (Exception ex) { response.AddResponseItem(new RecordCountsResponseItem(recordType, "Error Generating Counts", ex)); } finally { numberOfTypesCompleted++; } } controller.LogLiteral("Generating CSV files"); var groupByOwner = request.GroupCountsByOwner || request.OnlyIncludeSelectedOwner; if (!groupByOwner) { var totals = new List <RecordCount>(); foreach (var dictionary in recordCountsByUser) { totals.Add(new RecordCount(Service.GetDisplayName(dictionary.Key), dictionary.Value.Sum(kv => kv.Value))); } response.RecordCounts = totals; } if (groupByOwner) { var teamNameField = Service.GetRecordTypeMetadata(Entities.team).PrimaryFieldSchemaName; var userNameField = Service.GetRecordTypeMetadata(Entities.systemuser).PrimaryFieldSchemaName; var allDistinctOwners = recordCountsByUser .SelectMany(kv => kv.Value.Select(kv2 => kv2.Key)) .Distinct(); var allTeams = allDistinctOwners .Where(s => s.StartsWith(Entities.team)) .Distinct(); var allUsers = allDistinctOwners .Where(s => s.StartsWith(Entities.systemuser)) .Distinct(); var ownerKeyLabels = new Dictionary <string, string>(); var teams = Service.RetrieveAll(Entities.team, new[] { teamNameField }); foreach (var team in teams) { ownerKeyLabels.Add(string.Format("{0}:{1}", Entities.team, team.Id), team.GetStringField(teamNameField)); } var users = Service.RetrieveAll(Entities.systemuser, null); foreach (var user in users) { ownerKeyLabels.Add(string.Format("{0}:{1}", Entities.systemuser, user.Id), user.GetStringField(userNameField)); } var ownerTotals = new List <RecordCountByOwner>(); foreach (var dictionary in recordCountsByUser) { foreach (var owner in dictionary.Value) { if (owner.Key == noOwnerIndex) { ownerTotals.Add(new RecordCountByOwner(Service.GetDisplayName(dictionary.Key), owner.Value, noOwnerIndex, noOwnerIndex)); } else { if (ownerKeyLabels.ContainsKey(owner.Key)) { ownerTotals.Add(new RecordCountByOwner(Service.GetDisplayName(dictionary.Key), owner.Value, Service.GetDisplayName(owner.Key.Split(':')[0]), ownerKeyLabels[owner.Key])); } else { ownerTotals.Add(new RecordCountByOwner(Service.GetDisplayName(dictionary.Key), owner.Value, "Unknown", "Unknown")); } } } } response.RecordCounts = ownerTotals; } }