Exemplo n.º 1
0
        public static void Start(SchemaBuilder sb)
        {
            if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                UserAssetsImporter.Register <UserChartEntity>("UserChart", UserChartOperation.Save);

                sb.Schema.Synchronizing += Schema_Synchronizing;

                sb.Include <UserChartEntity>()
                .WithSave(UserChartOperation.Save)
                .WithDelete(UserChartOperation.Delete)
                .WithQuery(() => uq => new
                {
                    Entity = uq,
                    uq.Id,
                    uq.Query,
                    uq.EntityType,
                    uq.DisplayName,
                    uq.ChartScript,
                    uq.Owner,
                });

                sb.Schema.EntityEvents <UserChartEntity>().Retrieved += ChartLogic_Retrieved;

                sb.Schema.Table <QueryEntity>().PreDeleteSqlSync += e =>
                                                                    Administrator.UnsafeDeletePreCommand(Database.Query <UserChartEntity>().Where(a => a.Query == e));


                UserCharts = sb.GlobalLazy(() => Database.Query <UserChartEntity>().ToDictionary(a => a.ToLite()),
                                           new InvalidateWith(typeof(UserChartEntity)));

                UserChartsByQuery = sb.GlobalLazy(() => UserCharts.Value.Values.Where(a => a.EntityType == null).SelectCatch(uc => KeyValuePair.Create(uc.Query.ToQueryName(), uc.ToLite())).GroupToDictionary(),
                                                  new InvalidateWith(typeof(UserChartEntity)));

                UserChartsByTypeForQuickLinks = sb.GlobalLazy(() => UserCharts.Value.Values.Where(a => a.EntityType != null && !a.HideQuickLink)
                                                              .SelectCatch(a => KeyValuePair.Create(TypeLogic.IdToType.GetOrThrow(a.EntityType !.Id), a.ToLite()))
                                                              .GroupToDictionary(),
                                                              new InvalidateWith(typeof(UserChartEntity)));
            }
        }
Exemplo n.º 2
0
 public QueryBuilder(IEnumerable <KeyValuePair <string, StringValues> > parameters)
     : this(parameters.SelectMany(kvp => kvp.Value, (kvp, v) => KeyValuePair.Create(kvp.Key, v)))
 {
 }
 public DataSourceOptions Set(string key, OptionValue value)
 {
     _options.Add(KeyValuePair.Create <string, object>(key, (long)value));
     return(this);
 }
Exemplo n.º 4
0
 public bool Remove(string key, string value) =>
 Create().Remove(KeyValuePair.Create(key, value));
Exemplo n.º 5
0
        public async Task <IActionResult> ExportIssues([FromForm(Name = "issues")] List <string> issuesList, [FromForm(Name = "includeqr")] bool includeQRCode
                                                       , [FromHeader(Name = "Referer")] string referer, [FromHeader(Name = "x-real-ip")] string realIp, [FromHeader(Name = "User-Agent")] string userAgent
                                                       , [FromHeader(Name = "x-forwarded-for")] string forwardedFor)
        {
            IActionResult result          = null;
            DateTime      requestDateTime = DateTime.Now;
            TaskMeasurer  taskMeasurer    = new TaskMeasurer();
            string        extension       = "pdf";

            Model.ClientRegistration registrationData = _client.RegistrationData;
            string fileId         = Guid.NewGuid().ToString();
            string reportFileName = $"{_configuration.GetValue<string>("Settings:StorageRoot", "clients_jiracloud")}/{registrationData.ClientKey}/{fileId}.{extension}";

            JArray  fields = null;
            JObject issues = null;
            Dictionary <string, JArray> epicStories = new Dictionary <string, JArray>();

            Report.Model.Document      document             = null;
            Model.ReportFile           reportFile           = null;
            ReportJiraCloudModel       reportJiraCloudModel = null;
            List <StatisticalDocument> statItems            = new List <StatisticalDocument>();

            try
            {
                _logger.LogInformation($"{requestDateTime} New job ClientKey {registrationData.ClientKey}, issues {String.Join(", ", issuesList)}");
                HttpClient httpCli = _clientFactory.CreateClient("jira_client");
                httpCli.BaseAddress = new Uri(registrationData.BaseUrl);
                RestApiClient cli = new RestApiClient(registrationData.Key, registrationData.SharedSecret, registrationData.ClientKey, httpCli);

                fields = (JArray)JsonConvert.DeserializeObject(await taskMeasurer.Run(() => cli.Get($"/rest/api/3/field"), "000_FetchFields"));
                var EpicNameField = getField(fields, "com.pyxis.greenhopper.jira:gh-epic-label");


                string[] responses = await taskMeasurer.Run(() => Task.WhenAll(issuesList.Select(i => cli.Get($"/rest/api/3/issue/{i}"))), "111_FetchIssuesData");

                PdfReport pdfReport = new PdfReport(filePath: reportFileName, storageName: _configuration.GetValue <string>("Settings:StorageName"), debug: _hostEnvironment.IsDevelopment());
                await pdfReport.Configure(_client.PdfApi, _client.BarcodeApi);

                issues = JToken.FromObject(new
                {
                    issues = responses.Select(JsonConvert.DeserializeObject).ToList()
                }) as JObject;

                // get stories for epics
                epicStories = new Dictionary <string, JArray>();
                if (!string.IsNullOrEmpty(EpicNameField))
                {
                    var issuesArr = await Task.WhenAll(issues["issues"]
                                                       .Where(i => !string.IsNullOrEmpty(i.SelectToken($"$.fields.{EpicNameField}")?.ToString()))
                                                       .Select(async i => KeyValuePair.Create(i.SelectToken($"$.key")?.ToString(), await getSubtasksForEpic(cli, i.SelectToken($"$.key")?.ToString()))
                                                               ));

                    epicStories = issuesArr.ToDictionary(t => t.Key, t => t.Value);
                }

                document = taskMeasurer.RunSync(() =>
                {
                    reportJiraCloudModel = new ReportJiraCloudModel(System.IO.File.ReadAllText(
                                                                        _configuration.GetValue("Templates:ReportIssuesModel",
                                                                                                "template/Report-Issues.Mustache")))
                    {
                        EpicLinkField  = getField(fields, "com.pyxis.greenhopper.jira:gh-epic-link"),
                        EpicNameField  = EpicNameField,
                        GenerateQRCode = includeQRCode
                    };
                    return(reportJiraCloudModel.CreateReportModel(reportJiraCloudModel.issuesModel(issues, epicStories)));
                }, "112_PrepareReportModel");

                if (null == document.Options)
                {
                    document.Options = new Report.Model.DocumentOptions();
                }
                await pdfReport.Report(document);


                DateTime current = DateTime.Now;
                reportFile = new Model.ReportFile
                {
                    UniqueId        = $"{Guid.NewGuid()}",
                    ReportType      = extension,
                    ContentType     = "application/pdf",
                    FileName        = issuesList.Count == 1 ? $"{issuesList.First()}.{extension}" : $"Issues.{extension}",
                    StorageFileName = reportFileName,
                    ClientId        = registrationData.Id,
                    Created         = current,
                    Expired         = current.AddHours(_configuration.GetValue("Settings:FileExpirationHours", 24)),
                };
                _dbContext.ReportFile.Add(reportFile);
                statItems = taskMeasurer.Stat.Concat(pdfReport.Stat).ToList();

                await _dbContext.SaveChangesAsync();

                _logger.LogInformation($"{current} Finished {registrationData.ClientKey} in {DateTime.Now - requestDateTime}");
                return(result = new OkObjectResult(new {
                    fileid = reportFile.UniqueId
                    , downloadlink = _basePathReplacement.ReplaceBaseUrl(Url.Link("GetDownload", new { id = reportFile.UniqueId }))
                    , expText = TimeSpan.FromHours(_configuration.GetValue("Settings:FileExpirationHours", 24)).ToReadableString()
                    , exp = reportFile.Expired
                }));
            }
            catch (Exception ex)
            {
                ZipFileArchive archive = new ZipFileArchive().AddFile("010_request_params.json", new
                {
                    RequestId = _client.RequestId,
                    FileId    = fileId,
                    FileName  = reportFileName,
                    includeQRCode, referer, realIp, userAgent, forwardedFor,
                    issues = issuesList
                });
                foreach (var f in new Dictionary <string, object> {
                    { "020_registration.json", registrationData },
                    { "030_fields.json", fields },
                    { "040_issues.json", issues },
                    { "050_epic_stories.json", epicStories },
                    { "051_RenderedDocument.yaml", reportJiraCloudModel?.RenderedYamlDocument },
                    { "052_RenderedJsonDocument.yaml", reportJiraCloudModel?.RenderedJsonDocument },
                    { "060_document.json", document },
                    { "070_report_file.json", reportFile },
                    { "080_result.json", result },
                }.ToArray())
                {
                    archive.AddFile(f.Key, f.Value);
                }
                throw new ControllerException($"Error generating {reportFileName}", innerException: ex, customData: await archive.Archive());
            }
            finally
            {
                _client.Stat = statItems;
            }
        }
        void SynchronizeAssets(NSIndexSet[] updatedAlbumIndexSets, IDictionary <string, PHFetchResult> fetchMapBeforeChanges, PHChange changeInstance)
        {
            var updatedIndexSets = updatedAlbumIndexSets;

            foreach (var i in FetchedAlbumsArray.Select((value, index) => KeyValuePair.Create(index, value)))
            {
                var section = i.Key;
                var albums  = i.Value;

                var updatedIndexSet = updatedIndexSets[section] as NSMutableIndexSet;

                foreach (var album in albums)
                {
                    Debug.WriteLine($"Looping album: {album.LocalizedTitle}");

                    var fetchResult         = fetchMapBeforeChanges[album.LocalIdentifier];
                    var assetsChangeDetails = changeInstance.GetFetchResultChangeDetails(fetchResult);
                    if (fetchResult == null || assetsChangeDetails == null)
                    {
                        continue;
                    }

                    // check thumbnail
                    if (IsThumbnailChanged(assetsChangeDetails) || IsCountChanged(assetsChangeDetails))
                    {
                        var updateRow = fetchedAlbumsArray[section].IndexOf(album);

                        if (updateRow > -1)
                        {
                            updatedIndexSet.Add((uint)updateRow);
                        }
                    }

                    // update fetch result for each album
                    fetchMap[album.LocalIdentifier] = assetsChangeDetails.FetchResultAfterChanges;

                    if (!assetsChangeDetails.HasIncrementalChanges)
                    {
                        NotifySubscribers((subscriber) =>
                        {
                            var indexPathForAlbum = this.IndexPathForAlbumInAlbumsArray(album, this.SortedAlbumsArray);
                            if (indexPathForAlbum != null)
                            {
                                subscriber.ReloadedAlbum(this, album, indexPathForAlbum);
                            }
                        });

                        continue;
                    }
                    var selectedAlbum = this.SelectedAlbum;
                    if (selectedAlbum == null || selectedAlbum.LocalIdentifier != album.LocalIdentifier)
                    {
                        continue;
                    }

                    // sync removed assets
                    var removedIndexesSet = assetsChangeDetails.RemovedIndexes;
                    if (removedIndexesSet != null)
                    {
                        var removedIndexes = removedIndexesSet.AsArray().OrderBy(x => x.Row);
                        var removeAssets   = new List <PHAsset>();
                        foreach (var removedIndex in removedIndexes.Reverse())
                        {
                            removeAssets.Insert(0, AssetArray.RemoveAndGet(removedIndex.Row));
                        }
                        // stop caching for removed assets
                        StopCache(removeAssets.ToArray(), PickerConfig.AssetCacheSize);
                        NotifySubscribers((_) => _.RemovedAssets(this, removeAssets.ToArray(), removedIndexes.ToArray()), removeAssets.Count > 0);
                    }

                    // sync inserted assets
                    var insertedIndexesSet = assetsChangeDetails.InsertedIndexes;
                    if (insertedIndexesSet != null)
                    {
                        var insertedIndexes = insertedIndexesSet.AsArray().OrderBy(x => x.Row);
                        var insertedAssets  = new List <PHAsset>();
                        foreach (var insertedIndex in insertedIndexes)
                        {
                            var insertedAsset = assetsChangeDetails.FetchResultAfterChanges[insertedIndex.Row] as PHAsset;
                            insertedAssets.Add(insertedAsset);
                            AssetArray.Insert(insertedIndex.Row, insertedAsset);
                        }
                        // stop caching for removed assets
                        Cache(insertedAssets.ToArray(), PickerConfig.AssetCacheSize);
                        NotifySubscribers((_) => _.InsertedAssets(this, insertedAssets.ToArray(), insertedIndexes.ToArray()), insertedAssets.Count > 0);
                    }

                    // sync updated assets
                    var updatedIndexes = assetsChangeDetails.ChangedIndexes;
                    if (updatedIndexes != null)
                    {
                        var updatedAssets = new List <PHAsset>();
                        foreach (var updatedIndex in updatedIndexes.AsArray())
                        {
                            var updatedAsset = assetsChangeDetails.FetchResultAfterChanges[updatedIndex.Row] as PHAsset;
                            updatedAssets.Add(updatedAsset);
                        }
                        // stop caching for removed assets
                        Cache(updatedAssets.ToArray(), PickerConfig.AssetCacheSize);
                        StopCache(updatedAssets.ToArray(), PickerConfig.AssetCacheSize);
                        NotifySubscribers((_) => _.UpdatedAssets(this, updatedAssets.ToArray(), updatedIndexes.AsArray()), updatedAssets.Count > 0);
                    }
                }

                // update final changes in albums
                var oldSortedAlbums = SortedAlbumsArray[section];
                var newSortedAlbums = SortedAlbumFromAlbums(fetchedAlbumsArray[section].ToArray());

                /* 1. find & notify removed albums. */
                var removedInfo = RemovedIndexPaths(newSortedAlbums, oldSortedAlbums.ToArray(), section);
                foreach (var item in removedInfo.Item1.Select((value, index) => new { Value = value, Index = index }))
                {
                    var fetchedIndexPath = IndexPathForAlbumInAlbumsArray(removedInfo.Item2[item.Index], fetchedAlbumsArray);
                    if (fetchedIndexPath != null)
                    {
                        updatedIndexSet.Remove((uint)fetchedIndexPath.Row);
                    }
                }
                SortedAlbumsArray[section] = oldSortedAlbums;
                NotifySubscribers((_) => _.InsertedAlbums(this, removedInfo.Item2, removedInfo.Item1), removedInfo.Item1.Length > 0);

                /* 2. find & notify inserted albums. */
            }
        }