public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
 {
     var controller = (IHttpController) container.Resolve(controllerType);
     var resource = new Release(() => container.Release(controller));
     request.RegisterForDispose(resource);
     return controller;
 }
Ejemplo n.º 2
0
        public void ShouldGetLastFiveReleases()
        {
            //given
            var releaseRepository = new ReleaseRepository();
            var expectedReleaseDetailsModels = new List<Release>
                                                   {
                                                       new ReleaseBuilder().WithReleaseNumber("REL05").WithReleaseDate(DateTime.Today.AddDays(-1)).Build(),
                                                       new ReleaseBuilder().WithReleaseNumber("REL04").WithReleaseDate(DateTime.Today.AddMonths(-1)).Build(),
                                                       new ReleaseBuilder().WithReleaseNumber("REL03").WithReleaseDate(DateTime.Today.AddMonths(-1)).Build(),
                                                       new ReleaseBuilder().WithReleaseNumber("REL02").WithReleaseDate(DateTime.Today.AddMonths(-2).AddDays(2)).Build(),
                                                       new ReleaseBuilder().WithReleaseNumber("REL01").WithReleaseDate(DateTime.Today.AddMonths(-2)).Build()
                                                   };

            var lastfiveReleases = new Release[expectedReleaseDetailsModels.Count];
            expectedReleaseDetailsModels.CopyTo(lastfiveReleases);

            expectedReleaseDetailsModels.Add(new ReleaseBuilder().WithReleaseNumber("REL06").WithReleaseDate(DateTime.Today.AddMonths(-3).AddDays(-1)).Build());

            //when
            foreach (Release expectedReleaseDetailsModel in expectedReleaseDetailsModels)
            {
                releaseRepository.SaveReleaseDetails(expectedReleaseDetailsModel);
            }

            // then
            IEnumerable<Release> releaseDetailsModels = releaseRepository.GetLastFiveReleases();
            IEnumerable<Release> expectedReleases = lastfiveReleases.ToList();
            Assert.That(releaseDetailsModels, Is.EqualTo(expectedReleases));
        }
 public void ViewReleaseDetails(Release release)
 {
     navigationService.UriFor<ReleaseDetailsViewModel>()
         .WithParam(v => v.ReleaseId, release.Id)
         .WithParam(v => v.ArtistId, release.Artist.Id)
         .Navigate();
 }
Ejemplo n.º 4
0
 /// <summary>
 ///   Get all releases of economic data. Corresponds to http://api.stlouisfed.org/fred/releases
 /// </summary>
 /// <param name="realtimeStart"> The start of the real-time period. </param>
 /// <param name="realtimeEnd"> The end of the real-time period. </param>
 /// <param name="limit"> The maximum number of results to return. An integer between 1 and 1000, defaults to 1000. </param>
 /// <param name="offset"> non-negative integer, optional, default: 0 </param>
 /// <param name="orderBy"> Order results by values of the specified attribute. </param>
 /// <param name="order"> Sort results is ascending or descending order for attribute values specified by order_by. </param>
 /// <returns> All releases in the FRED database. </returns>
 public IEnumerable<Release> GetReleases(DateTime realtimeStart, DateTime realtimeEnd,
     int limit = 1000,
     int offset = 0,
     Release.OrderBy orderBy = Release.OrderBy.ReleaseId,
     SortOrder order = SortOrder.Ascending)
 {
     return GetReleasesAsync(realtimeStart, realtimeEnd, limit, offset, orderBy, order).Result;
 }
Ejemplo n.º 5
0
        public static Lizenz_Versionsorientiert createAndGetVersionslizenz(Release licensedRelease, Int32 versionIncremention)
        {
            Lizenz_Versionsorientiert license = Lizenz_Versionsorientiert.CreateLizenz_Versionsorientiert(versionIncremention, licensedRelease.ReleaseID);

            HodorGlobals.getHodorContext().Lizenzs.AddObject(license);
            HodorGlobals.save();

            return license;
        }
Ejemplo n.º 6
0
 public void SaveReleaseDetails(Release release)
 {
     using (ISession session = ReleaseRepository.CreateSessionFactory().OpenSession())
       {
     using (ITransaction transaction = session.BeginTransaction())
     {
       session.SaveOrUpdate((object) release);
       transaction.Commit();
     }
       }
 }
Ejemplo n.º 7
0
 public override object Loading(object arguments)
 {
     IMusicService ms = this.Host.MusicService;
     String[] parameters = (String[])arguments;
     release = ms.LoadRelease(parameters[2]);
     release.LoadTracks();
     return new
     {
         Release = release
     };
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Get all releases of economic data. Corresponds to http://api.stlouisfed.org/fred/releases
        /// </summary>
        /// <param name="realtimeStart">The start of the real-time period.</param>
        /// <param name="realtimeEnd">The end of the real-time period. </param>
        /// <param name="limit">The maximum number of results to return. An integer between 1 and 1000, defaults to 1000. </param>
        /// <param name="offset">non-negative integer, optional, default: 0</param>
        /// <param name="orderBy">Order results by values of the specified attribute.</param>
        /// <param name="order">Sort results is ascending or descending order for attribute values specified by order_by.</param>
        /// <returns>All releases in the FRED database.</returns>
        public IEnumerable<Release> GetReleases(DateTime realtimeStart, DateTime realtimeEnd, int limit = 1000,
                                                int offset = 0,
                                                Release.OrderBy orderBy = Release.OrderBy.ReleaseId,
                                                SortOrder order = SortOrder.Ascending)
        {
            var url = String.Format(Urls.Releases, _key, realtimeStart.ToFredDateString(),
                                    realtimeEnd.ToFredDateString(), limit, offset, Extensions.ToString(orderBy),
                                    Extensions.ToString(order));

            return CreateReleases(url);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Get a release of economic data. Corresponds to http://api.stlouisfed.org/fred/release
        /// </summary>
        /// <param name="releaseId">The ID of the release to retrieve.</param>
        /// <param name="realtimeStart">The start of the real-time period.</param>
        /// <param name="realtimeEnd">The end of the real-time period. </param>
        /// <param name="limit">The maximum number of results to return. An integer between 1 and 1000, defaults to 1000. </param>
        /// <param name="offset">non-negative integer, optional, default: 0</param>
        /// <param name="orderBy">Order results by values of the specified attribute.</param>
        /// <param name="order">Sort results is ascending or descending order for attribute values specified by order_by.</param>
        /// <returns>The requested release.</returns>
        /// <remarks>Note that release dates are published by data sources and do not necessarily represent when data will be available on the FRED or ALFRED websites.</remarks>

        public async Task<Release> GetReleaseAsync(int releaseId, DateTime realtimeStart, DateTime realtimeEnd, int limit = 1000,
                                  int offset = 0,
                                  Release.OrderBy orderBy = Release.OrderBy.ReleaseId,
                                  SortOrder order = SortOrder.Ascending)
        {
            var url = String.Format(Urls.Release, _key, releaseId, realtimeStart.ToFredDateString(),
                                    realtimeEnd.ToFredDateString());

            var root = await GetRootAsync(url);
            var element = root.Elements("release").First();
            return CreateRelease(element);
        }
Ejemplo n.º 10
0
        /// <summary>
        ///   Get all releases of economic data. Corresponds to http://api.stlouisfed.org/fred/releases
        /// </summary>
        /// <param name="realtimeStart"> The start of the real-time period. </param>
        /// <param name="realtimeEnd"> The end of the real-time period. </param>
        /// <param name="limit"> The maximum number of results to return. An integer between 1 and 1000, defaults to 1000. </param>
        /// <param name="offset"> non-negative integer, optional, default: 0 </param>
        /// <param name="orderBy"> Order results by values of the specified attribute. </param>
        /// <param name="order"> Sort results is ascending or descending order for attribute values specified by order_by. </param>
        /// <returns> All releases in the FRED database. </returns>
        public async Task<IEnumerable<Release>> GetReleasesAsync(DateTime realtimeStart, DateTime realtimeEnd,
                                                                 int limit = 1000,
                                                                 int offset = 0,
                                                                 Release.OrderBy orderBy = Release.OrderBy.ReleaseId,
                                                                 SortOrder order = SortOrder.Ascending)
        {
            var url = String.Format(Urls.Releases, _key, realtimeStart.ToFredDateString(),
                                    realtimeEnd.ToFredDateString(), limit, offset, Extensions.ToString(orderBy),
                                    Extensions.ToString(order));

            var root = await GetRootAsync(url);
            return root.Elements("release").Select(CreateRelease).ToList();
        }
Ejemplo n.º 11
0
 public void SaveReleaseDetails(Release release)
 {
     // create our NHibernate session factory
     ISessionFactory sessionRepository = CreateSessionFactory();
     using (ISession session = sessionRepository.OpenSession())
     {
         // populate the database
         using (ITransaction transaction = session.BeginTransaction())
         {
             session.SaveOrUpdate(release);
             transaction.Commit();
         }
     }
 }
Ejemplo n.º 12
0
		public static async Task<string> DownloadRelease(Release release, string downloadDirectory)
		{
			try
			{
				var path = Path.Combine(downloadDirectory, release.Assets[0].Name);
				using(var wc = new WebClient())
					await wc.DownloadFileTaskAsync(release.Assets[0].Url, path);
				return path;
			}
			catch(Exception e)
			{
				Log.Error(e);
				return null;
			}
		}
            public void UploadsToCorrectUrl()
            {
                var client = Substitute.For<IApiConnection>();
                var releasesClient = new ReleasesClient(client);
                var release = new Release { UploadUrl = "https://uploads.test.dev/does/not/matter/releases/1/assets{?name}" };
                var rawData = Substitute.For<Stream>();
                var upload = new ReleaseAssetUpload { FileName = "example.zip", ContentType = "application/zip", RawData = rawData };

                releasesClient.UploadAsset(release, upload);

                client.Received().Post<ReleaseAsset>(
                    Arg.Is<Uri>(u => u.ToString() == "https://uploads.test.dev/does/not/matter/releases/1/assets?name=example.zip"),
                    rawData,
                    "application/vnd.github.v3",
                    Arg.Is<string>(contentType => contentType == "application/zip"));
            }
Ejemplo n.º 14
0
        public static void deleteRelease(Release release)
        {
            List<Subrelease> subreleases = release.Subreleases.ToList<Subrelease>();

            foreach (Subrelease subrelease in subreleases)
            {
                SubreleaseDAO.deleteSubrelease(subrelease);
            }

            List<Lizenz> licenses = release.Lizenz_Versionsorientiert.ToList<Lizenz>();

            foreach (Lizenz license in licenses)
            {
                LizenzDAO.deleteLicense(license);
            }

            HodorGlobals.getHodorContext().Releases.DeleteObject(release);

            HodorGlobals.save();
        }
Ejemplo n.º 15
0
        public async Task <int> changeCheckListStakeholder(int ReleaseID, List <int> changedStakeholderIds, Release newRelease)
        {
            int count = 0, employeeId;
            var histories = new List <History>();

            using (IEmployeeRepository db = new EmployeeRepository())
            {
                employeeId = db.GetEmployee(ConfigurationManager.AppSettings["SystemUserNtnet"]);
            }
            using (IReleaseChecklistAnswerRepository db = new ReleaseChecklistAnswerRepository())
            {
                var releaseChecklistAnswer = db.Where(cl => cl.ReleaseID == ReleaseID).Include(cl => cl.Question).Where(cl => changedStakeholderIds.Where(s => s == cl.Question.QuestionOwnerID).Count() > 0);



                foreach (ReleaseChecklistAnswer cl in releaseChecklistAnswer)
                {
                    var history = new History();
                    history.ReleaseID = cl.ReleaseID;
                    history.ItemID    = cl.ReleaseChecklistAnswerID;
                    history.TableID   = 26;
                    //  history.ActivityLogID = activityLog.ActivityLogID;
                    history.OldValue   = cl.QuestionOwnerID.ToString();
                    history.FieldName  = "QuestionOwner";
                    cl.QuestionOwnerID = newRelease.ReleaseStakeholders.Where(s => s.StakeholderID == cl.Question.QuestionOwnerID).FirstOrDefault().EmployeeID1;
                    history.NewValue   = cl.QuestionOwnerID.ToString();
                    histories.Add(history);
                }
                count += await db.SaveAsync(null, true, histories);
            }
            return(count);
        }
Ejemplo n.º 16
0
        public bool TryAddRelease(ReleaseModel model)
        {
            var release = new Release(model.Name, model.From, model.To, ProjectId)
            {
                Description = model.Description
            };

            if (Releases.AnyOverlapsWith(release))
            {
                Errors.Add(new Tuple<string, string>("from", "ReleaseOverlapedErrorKey"));
                Errors.Add(new Tuple<string, string>("to", "ReleaseOverlapedErrorKey"));

                return false;
            }

            Database.Releases.Add(release);

            return true;
        }
Ejemplo n.º 17
0
        public void CreateReleaseTest()
        {
            Release created = CreateRelease();

            Assert.IsNotNull(created);
        }
        public async Task PublishMethodologyFilesIfApplicableForRelease_FirstPublicReleaseHasMethodologyScheduledImmediately()
        {
            var release = new Release
            {
                Id            = Guid.NewGuid(),
                PublicationId = Guid.NewGuid()
            };

            var methodologyVersion = new MethodologyVersion
            {
                Id = Guid.NewGuid(),
                PublishingStrategy = Immediately,
                Status             = Approved
            };

            var methodologyService        = new Mock <IMethodologyService>(MockBehavior.Strict);
            var publicBlobStorageService  = new Mock <IBlobStorageService>(MockBehavior.Strict);
            var privateBlobStorageService = new Mock <IBlobStorageService>(MockBehavior.Strict);
            var publicationService        = new Mock <IPublicationService>(MockBehavior.Strict);
            var releaseService            = new Mock <IReleaseService>(MockBehavior.Strict);

            methodologyService.Setup(mock => mock.GetLatestByRelease(release.Id))
            .ReturnsAsync(ListOf(methodologyVersion));

            methodologyService.Setup(mock => mock.GetFiles(methodologyVersion.Id, Image))
            .ReturnsAsync(new List <File>());

            publicationService.Setup(mock => mock.IsPublicationPublished(release.PublicationId))
            .ReturnsAsync(false);

            // Invocations on the storage services expected because this will be the first published release.
            // The methodology and its files will be published for the first time with this release

            publicBlobStorageService.Setup(mock => mock.DeleteBlobs(
                                               PublicMethodologyFiles,
                                               $"{methodologyVersion.Id}/",
                                               null))
            .Returns(Task.CompletedTask);

            privateBlobStorageService.Setup(mock => mock.CopyDirectory(
                                                PrivateMethodologyFiles,
                                                $"{methodologyVersion.Id}/",
                                                PublicMethodologyFiles,
                                                $"{methodologyVersion.Id}/",
                                                It.Is <IBlobStorageService.CopyDirectoryOptions>(options =>
                                                                                                 options.DestinationConnectionString == PublicStorageConnectionString)))
            .ReturnsAsync(new List <BlobInfo>());

            releaseService.Setup(mock => mock.Get(release.Id))
            .ReturnsAsync(release);

            var service = BuildPublishingService(publicStorageConnectionString: PublicStorageConnectionString,
                                                 methodologyService: methodologyService.Object,
                                                 publicBlobStorageService: publicBlobStorageService.Object,
                                                 privateBlobStorageService: privateBlobStorageService.Object,
                                                 publicationService: publicationService.Object,
                                                 releaseService: releaseService.Object);

            await service.PublishMethodologyFilesIfApplicableForRelease(release.Id);

            MockUtils.VerifyAllMocks(methodologyService,
                                     publicBlobStorageService,
                                     privateBlobStorageService,
                                     publicationService,
                                     releaseService);
        }
Ejemplo n.º 19
0
        public async Task <int> SaveNewRelease(int ReleaseID, ReleaseTabs UpdateRelease)
        {
            Release ReleaseTemp = null;
            int     count       = 0;

            try
            {
                using (IReleaseRepository db = new ReleaseRepository())
                {
                    ReleaseTemp = new Release()
                    {
                        AccountID              = UpdateRelease.GeneralDetails.AccountID,
                        Name                   = UpdateRelease.GeneralDetails.Name,
                        Size                   = UpdateRelease.GeneralDetails.Size,
                        LOB                    = UpdateRelease.GeneralDetails.LOB,
                        AdditionalProducts     = UpdateRelease.ProductsInScope.Release.AdditionalProducts,
                        ReleaseStakeholders    = new List <ReleaseStakeholder>(),
                        ReleaseAreaOwners      = new List <ReleaseAreaOwner>(),
                        ReleaseFamilyProducts  = new List <ReleaseFamilyProduct>(),
                        ReleaseProducts        = new List <ReleaseProduct>(),
                        ReleaseMilestones      = new List <ReleaseMilestone>(),
                        ReleaseCharacteristics = new List <ReleaseCharacteristic>()
                    };

                    UpdateRelease.ReleaseMilestones.ToList().ForEach(
                        prop =>
                        ReleaseTemp.ReleaseMilestones.Add(new ReleaseMilestone()
                    {
                        MilestoneID = prop.MilestoneID, MilestoneDate = prop.MilestoneDate
                    })
                        );

                    UpdateRelease.ReleaseStakeholders.ToList().ForEach(
                        prop =>
                        ReleaseTemp.ReleaseStakeholders.Add(new ReleaseStakeholder()
                    {
                        StakeholderID = prop.StakeholderID, EmployeeID1 = prop.EmployeeID1, EmployeeID2 = prop.EmployeeID2
                    })
                        );

                    UpdateRelease.AreaOwners.ToList().ForEach(
                        prop =>
                        ReleaseTemp.ReleaseAreaOwners.Add(new ReleaseAreaOwner()
                    {
                        AreaID = prop.AreaID, AmdocsFocalPoint1ID = prop.AmdocsFocalPoint1ID, AmdocsFocalPoint2ID = prop.AmdocsFocalPoint2ID, IsChecked = prop.IsChecked, CustomerFocalpoint1 = prop.CustomerFocalPoint1, CustomerFocalPoint2 = prop.CustomerFocalPoint2, Resposibility = prop.Resposibility
                    })
                        );

                    UpdateRelease.ReleaseCharacteristic.ToList().ForEach(
                        prop =>
                        ReleaseTemp.ReleaseCharacteristics.Add(new ReleaseCharacteristic()
                    {
                        CharacteristicID = prop.CharacteristicID, IsChecked = prop.IsChecked
                    })
                        );


                    UpdateRelease.ProductsInScope.FamilyProducts.ToList().ForEach(prop =>
                    {
                        ReleaseTemp.ReleaseFamilyProducts.Add(new ReleaseFamilyProduct()
                        {
                            FamilyProductID = prop.ID, IsChecked = prop.IsChecked
                        });
                        prop.Products.ToList().ForEach(rp =>
                                                       ReleaseTemp.ReleaseProducts.Add(new ReleaseProduct()
                        {
                            ProductID = rp.ID, IsChecked = rp.IsChecked
                        })
                                                       );
                    });

                    //ReleaseTemp.ReleaseCharacteristics = new List<ReleaseCharacteristic>();
                    //using (IReleaseRepository db = new ReleaseRepository())
                    //{
                    //    using (var transactionScope = new TransactionScope())
                    //    {
                    //        db.Add(ReleaseTemp);
                    //        await db.SaveAsync((WindowsPrincipal)User);
                    //        transactionScope.Complete();
                    //    }
                    //}
                    db.Add(ReleaseTemp);

                    count += await db.SaveAsync((WindowsPrincipal)User);

                    await AddCPs(ReleaseTemp.ReleaseID);
                }
            }
            catch (Exception ex)
            {
                count = -1;
            }

            return(count > 0 ? ReleaseTemp.ReleaseID : count);
        }
Ejemplo n.º 20
0
 public AsyncLock()
 {
     _release     = new Release(this);
     _releaseTask = Task.FromResult(_release);
 }
        public void OnMouseDown(System.Windows.Forms.MouseEventArgs mouseEventArgs, int width, int height)
        {
            if (mSegmenter.DatasetLoaded)
            {
                var x = (int)Math.Floor(((float)mouseEventArgs.X / width) * mSegmenter.Interop.VolumeDescription.NumVoxelsX);
                var y = (int)Math.Floor(((float)mouseEventArgs.Y / height) * mSegmenter.Interop.VolumeDescription.NumVoxelsY);

                switch (mSegmenter.CurrentSegmenterToolMode)
                {
                case SegmenterToolMode.Adjust:
                    mSegmenter.BeginScribble(x, y);

                    if (Keyboard.IsKeyDown(Key.LeftAlt))
                    {
                        if (mouseEventArgs.Button == MouseButtons.Left)
                        {
                            mSegmenter.SelectNeuralProcessOrScribble(x, y, ConstraintType.Foreground, Constants.MAX_BRUSH_WIDTH);
                        }

                        if (mouseEventArgs.Button == MouseButtons.Right)
                        {
                            mSegmenter.SelectNeuralProcessOrScribble(x, y, ConstraintType.Background, Constants.MAX_BRUSH_WIDTH);
                        }
                    }
                    else
                    {
                        if (mouseEventArgs.Button == MouseButtons.Left)
                        {
                            mSegmenter.SelectNeuralProcessOrScribble(x, y, ConstraintType.Foreground, Constants.MIN_BRUSH_WIDTH);
                        }

                        if (mouseEventArgs.Button == MouseButtons.Right)
                        {
                            mSegmenter.SelectNeuralProcessOrScribble(x, y, ConstraintType.Background, Constants.MIN_BRUSH_WIDTH);
                        }
                    }
                    break;

                case SegmenterToolMode.Merge:
                    if (mouseEventArgs.Button == MouseButtons.Left)
                    {
                        mSegmenter.SelectMergeSourceNeuralProcess(x, y);
                    }

                    if (mouseEventArgs.Button == MouseButtons.Right)
                    {
                        if (mSegmenter.MergeSourceNeuralProcess != null)
                        {
                            mSegmenter.SelectMergeDestinationNeuralProcess(x, y);
                        }
                    }
                    break;

                case SegmenterToolMode.Split:
                    mSegmenter.BeginScribble(x, y);

                    if (Keyboard.IsKeyDown(Key.LeftAlt))
                    {
                        if (mouseEventArgs.Button == MouseButtons.Left)
                        {
                            mSegmenter.SelectSplitNeuralProcessOrScribble(x, y, ConstraintType.Foreground, Constants.MAX_BRUSH_WIDTH);
                        }

                        if (mouseEventArgs.Button == MouseButtons.Right)
                        {
                            mSegmenter.SelectSplitNeuralProcessOrScribble(x, y, ConstraintType.Background, Constants.MAX_BRUSH_WIDTH);
                        }
                    }
                    else
                    {
                        if (mouseEventArgs.Button == MouseButtons.Left)
                        {
                            mSegmenter.SelectSplitNeuralProcessOrScribble(x, y, ConstraintType.Foreground, Constants.MIN_BRUSH_WIDTH);
                        }

                        if (mouseEventArgs.Button == MouseButtons.Right)
                        {
                            mSegmenter.SelectSplitNeuralProcessOrScribble(x, y, ConstraintType.Background, Constants.MIN_BRUSH_WIDTH);
                        }
                    }
                    break;

                default:
                    Release.Assert(false);
                    break;
                }
            }
        }
Ejemplo n.º 22
0
    private static ChangeLogData ProduceChangeLogList(string name)
    {
        var result = new ChangeLogData();

        try
        {
            System.Text.StringBuilder s = new System.Text.StringBuilder();

            var github = new GitHubClient(new ProductHeaderValue("vswebessentials.com"));
            IReadOnlyList <Release> lst = github.Release.GetAll("madskristensen", name).Result;

            // Only display releases from the last 6 months
            var sixMonthAgoDate = DateTime.Now.AddMonths(-_monthsBack);
            // Display an link for the full list on GitHub if older releases found
            bool isMoreReleasesAvailable = false;

            s.AppendFormat("<div class='panel-group' id='accordion" + name + "'>");

            for (var i = 0; i < lst.Count; i++)
            {
                Release r = lst[i];
                s.Append("<div class='panel panel-default'>");
                s.Append("<div class='panel-heading'>");
                s.Append("<h4 class='panel-title'>");
                s.AppendFormat("<a data-toggle='collapse' data-parent='#accordion{0}' href='#id{1}'>", name, r.Id);
                string publishedAt = "[Unknow published date]";
                if (r.PublishedAt.HasValue)
                {
                    publishedAt = r.PublishedAt.Value.Date.ToString("MMM dd. yyyy");
                }

                string releaseName = r.Name;
                // At least will display tagName (usually release version)
                if (string.IsNullOrWhiteSpace(r.Name))
                {
                    releaseName = r.TagName;
                }

                s.AppendFormat("{0} <em style=\"float:right;margin-right:6em\">{1}</em>", releaseName, publishedAt);
                s.AppendFormat("<a class='btn btn-success btn-nightly-download' href='{0}'><i class='fa fa-download'></i>Download</a>", r.HtmlUrl);
                s.Append("</a></h4></div>");
                var collapseClass = i == 0 ? "in" : "collapse";
                s.AppendFormat("<div id='id{0}' class='panel-collapse {1}'>", r.Id, collapseClass);
                s.Append("<div class='panel-body'>");
                s.Append(r.BodyHtml);
                s.Append("</div></div></div>");

                if (r.PublishedAt < sixMonthAgoDate)
                {
                    isMoreReleasesAvailable = true;
                    break;
                }
            }

            s.AppendFormat("</div>");

            if (isMoreReleasesAvailable)
            {
                s.Append("<div><p>For the complete list of releases, go to the <a class='' target='_blank' href='https://github.com/madskristensen/" + name + "/releases'>GitHub Release page of the project</a>.</p></div>");
            }

            result.ChangeLogOutput      = s.ToString();
            result.IsGitHubApiSuccessed = true;
        }
        catch
        {
            result.ChangeLogOutput      = GenerateErrorSection(name);
            result.IsGitHubApiSuccessed = false;
        }

        return(result);
    }
Ejemplo n.º 23
0
 public BadgePointLimitsModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget)
 {
 }
        public async Task UpdateComment()
        {
            var comment = new Comment
            {
                Content     = "Existing comment",
                CreatedById = Guid.NewGuid(),
            };
            var release = new Release
            {
                Content = AsList(
                    new ReleaseContentSection
                {
                    ContentSection = new ContentSection
                    {
                        Content = AsList <ContentBlock>(
                            new HtmlBlock
                        {
                            Comments = AsList(comment)
                        }
                            )
                    }
                }
                    )
            };

            var contentDbContextId = Guid.NewGuid().ToString();

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                await contentDbContext.AddAsync(release);

                await contentDbContext.SaveChangesAsync();
            }

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                var userId  = Guid.NewGuid();
                var service = SetupCommentService(
                    contentDbContext: contentDbContext,
                    userId: userId);
                var result = await service.UpdateComment(comment.Id,
                                                         new CommentSaveRequest { Content = "Existing comment updated" });

                var viewModel = result.AssertRight();
                Assert.Equal("Existing comment updated", viewModel.Content);
                Assert.NotNull(viewModel.Updated);
                Assert.InRange(DateTime.UtcNow.Subtract(viewModel.Updated !.Value).Milliseconds, 0, 1500);
                Assert.Null(viewModel.Resolved);
                Assert.Null(viewModel.ResolvedBy);
            }

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                var comments = contentDbContext.Comment.ToList();
                Assert.Single(comments);
                Assert.Equal("Existing comment updated", comments[0].Content);
                Assert.Equal(comment.CreatedById, comments[0].CreatedById);
                Assert.NotNull(comments[0].Updated);
                Assert.InRange(DateTime.UtcNow.Subtract(comments[0].Updated !.Value).Milliseconds, 0, 1500);
                Assert.Null(comments[0].ResolvedById);
            }
        }
        public async Task DeleteComment()
        {
            var comment1 = new Comment
            {
                Content     = "Comment 1",
                CreatedById = Guid.NewGuid(),
            };
            var comment2 = new Comment
            {
                Content     = "Comment 2",
                CreatedById = Guid.NewGuid(),
            };
            var comment3 = new Comment
            {
                Content     = "Comment 3",
                CreatedById = Guid.NewGuid(),
            };
            var release = new Release
            {
                Content = AsList(
                    new ReleaseContentSection
                {
                    ContentSection = new ContentSection
                    {
                        Content = AsList <ContentBlock>(
                            new HtmlBlock
                        {
                            Comments = AsList(comment1, comment2, comment3)
                        }
                            )
                    }
                }
                    )
            };

            var contentDbContextId = Guid.NewGuid().ToString();

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                await contentDbContext.AddAsync(release);

                await contentDbContext.SaveChangesAsync();
            }

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                var service = SetupCommentService(contentDbContext);
                var result  = await service.DeleteComment(comment2.Id);

                var resultRight = result.AssertRight();
                Assert.True(resultRight);
            }

            await using (var contentDbContext = InMemoryApplicationDbContext(contentDbContextId))
            {
                var comments = contentDbContext.Comment.ToList();
                Assert.Equal(2, comments.Count);
                Assert.Equal("Comment 1", comments[0].Content);
                Assert.Equal(comment1.CreatedById, comments[0].CreatedById);
                Assert.Equal("Comment 3", comments[1].Content);
                Assert.Equal(comment3.CreatedById, comments[1].CreatedById);
            }
        }
Ejemplo n.º 26
0
 public override string ToString()
 {
     return("Hash: " + Hash.ToString("X8") + ", Release date: " + Release.ToString("yyyy/MM/dd") + "\r\nTitle: " + Title);
 }
Ejemplo n.º 27
0
 public void List() =>
 _client
 .GetAsync(Release.Definitions("manuel", "packer-tasks"))
 .ToEnumerable()
 .Should()
 .NotBeEmpty();
Ejemplo n.º 28
0
        public void installZip(Release jObject, ReleaseAsset file)
        {
            string fileName = file.Name;
            string fileUrl  = file.BrowserDownloadUrl;
            string fileTag  = jObject.TagName;
            string tempPath = Path.GetTempPath() + "\\ModManager";

            this.modManager.utils.DirectoryDelete(tempPath);
            Directory.CreateDirectory(tempPath);
            string zipPath = tempPath + "\\" + fileName;

            try {
                using (var client = new WebClient())
                {
                    client.DownloadFile(fileUrl, zipPath);
                }
            }
            catch
            {
                MessageBox.Show("Can't reach Mod Manager server.\nPlease verify your internet connection and try again !", "Mod Manager server unavailable", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Environment.Exit(0);
            }
            this.modManager.utils.DirectoryDelete(tempPath + "\\BepInEx");
            this.modManager.utils.DirectoryDelete(tempPath + "\\Assets");
            this.modManager.utils.DirectoryDelete(tempPath + "\\mono");
            this.modManager.utils.FileDelete(tempPath + "\\doorstop_config.ini");
            this.modManager.utils.FileDelete(tempPath + "\\winhttp.dll");
            ZipFile.ExtractToDirectory(zipPath, tempPath);
            // Install dll
            DirectoryInfo dirInfo = new DirectoryInfo(tempPath + "\\BepInEx\\plugins");
            List <string> plugins = new List <string>();

            if (dirInfo.Exists)
            {
                FileInfo[] files = dirInfo.GetFiles("*.dll");
                foreach (FileInfo f in files)
                {
                    if (!(f.Name.Contains("Essentials-") || f.Name.Contains("Reactor-")))
                    {
                        this.modManager.utils.FileCopy(f.FullName, this.modManager.config.amongUsPath + "\\BepInEx\\plugins\\" + f.Name);
                        plugins.Add(f.Name);
                    }
                }
            }
            DirectoryInfo dirInfo2 = new DirectoryInfo(tempPath + "\\Assets");
            List <string> assets   = new List <string>();

            if (dirInfo2.Exists)
            {
                FileInfo[] files = dirInfo2.GetFiles();
                foreach (FileInfo f in files)
                {
                    this.modManager.utils.FileCopy(f.FullName, this.modManager.config.amongUsPath + "\\Assets\\" + f.Name);
                    assets.Add(f.Name);
                }
            }
            InstalledMod newMod = new InstalledMod(this.currentMod.id, fileTag, assets, plugins);

            this.modManager.config.installedMods.Add(newMod);
            this.modManager.config.update();
            return;
        }
Ejemplo n.º 29
0
 public static E TriggerADSR(double t0, double e0, double attack, double decay, Amplitude sustainLevel, double sustainDuration, double release)
 => (t)
 => !HasElapsed(t0, t, attack) ? Attack(t0, e0, attack)(t)
             : !HasElapsed(t0 + attack, t, decay) ? Decay(t0 + attack, e0, decay, sustainLevel)(t)
             : !HasElapsed(t0 + attack + decay, t, sustainDuration) ? Sustain(sustainLevel)(t)
             : !HasElapsed(t0 + attack + decay + sustainDuration, t, release) ? Release(t0 + attack + decay + sustainDuration, Normalize(sustainLevel), release)(t)
             : Mute()(t);
Ejemplo n.º 30
0
        public void LoadDataFromRelease(Release release, ICollectionImageHandler imageHandler)
        {
            if (release.DiscCount != this.DatabaseRelease.DiscCount || release.Tracklist.Count != this.DatabaseRelease.Tracklist.Count)
            {
                Dialogs.Error("Tracklists do not match. Can not continue.");
                return;
            }

            this.DatabaseRelease.AdditionalFiles.Clear();
            this.DatabaseRelease.AdditionalFiles.AddRange(release.AdditionalFiles);

            this.DatabaseRelease.Artists.Clear();
            this.DatabaseRelease.Artists.AddRange(release.Artists.Select(ra => new ReleaseArtist()
            {
                Artist     = this.CollectionManager.GetOrCreateArtist(ra.Artist.Name),
                JoinString = ra.JoinString
            }));

            this.DatabaseRelease.CatalogNumber = release.CatalogNumber;
            this.DatabaseRelease.Country       = release.Country;
            //this.DatabaseRelease.DateAdded = release.DateAdded;
            //this.DatabaseRelease.DateModified = release.DateModified;
            //this.DatabaseRelease.DateAudioModified = release.DateAudioModified;
            this.DatabaseRelease.DiscogsReleaseId    = release.DiscogsReleaseId;
            this.DatabaseRelease.DiscogsMasterId     = release.DiscogsMasterId;
            this.DatabaseRelease.FlagMessage         = release.FlagMessage;
            this.DatabaseRelease.Genre               = release.Genre;
            this.DatabaseRelease.IsFlagged           = release.IsFlagged;
            this.DatabaseRelease.JoinedAlbumArtists  = release.JoinedAlbumArtists;
            this.DatabaseRelease.Label               = release.Label;
            this.DatabaseRelease.Notes               = release.Notes;
            this.DatabaseRelease.WikipediaPageName   = release.WikipediaPageName;
            this.DatabaseRelease.OriginalReleaseDate = release.OriginalReleaseDate;
            this.DatabaseRelease.ReleaseDate         = release.ReleaseDate;
            this.DatabaseRelease.Title               = release.Title;

            this.additionalFilesEditor.Release = null;
            this.additionalFilesEditor.Release = this.DatabaseRelease;

            this.DatabaseRelease.Images.Clear();
            this.imagesEditor.Release = null;
            this.imagesEditor.Release = this.DatabaseRelease;
            foreach (var image in release.Images)
            {
                var newImage = new MusicDatabase.Engine.Entities.Image()
                {
                    Description = image.Description,
                    Extension   = image.Extension,
                    IsMain      = image.IsMain,
                    MimeType    = image.MimeType,
                    Type        = image.Type
                };
                this.DatabaseRelease.Images.Add(newImage);
                this.imagesEditor.AddImage(newImage, imageHandler.LoadImage(image));
            }

            for (int i = 0; i < release.Tracklist.Count; ++i)
            {
                this.DatabaseRelease.Tracklist[i].Artists.Clear();
                this.DatabaseRelease.Tracklist[i].Artists.AddRange(release.Tracklist[i].Artists.Select(a => new TrackArtist()
                {
                    Artist     = this.CollectionManager.GetOrCreateArtist(a.Artist.Name),
                    JoinString = a.JoinString
                }));
                this.DatabaseRelease.Tracklist[i].JoinedArtists = release.Tracklist[i].JoinedArtists;
                this.DatabaseRelease.Tracklist[i].Title         = release.Tracklist[i].Title;
            }

            this.detailsEditor.Release = null;
            this.detailsEditor.Release = this.DatabaseRelease;
            this.RefreshAllDiscs();
        }
Ejemplo n.º 31
0
        /* Checks for updates and returns release informations when there is newer one.
         * Returns null if there is no newer release.
         * If Prerelease argument is true, it will return also Pre-release, otherwise Pre-releases are ignored.
         * An existing last checked release will be discarded.
         * Throws UpdaterException if error occurs.
         */
        public static Release CheckForUpdates(bool Prerelease = true)
        {
            if (Latest != null)
            {
                if (Latest.IsDownloading)
                {
                    throw new UpdaterException(L10n.Message("Download already in progress"));
                }

                // If release was installed, report no update.
                if (Latest.IsInstalled)
                {
                    return(null);
                }

                Dispose();
            }

            if (IsNewerProductInstalled())
            {
                // Newer product is installed, there is no update.
                IsChecked = true;

                return(null);
            }

            var webClient = new UpdaterWebClient();

            webClient.Encoding = Encoding.UTF8;

            try
            {
                string json     = webClient.DownloadString(GitAPILatestReleaseURL);
                JArray releases = JArray.Parse(json);
                if (releases.Count < 1)
                {
                    throw new UpdaterException(L10n.Message("No release found"));
                }

                Version current = GetCurrentVersion(); // Current version (tag).

                // Iterate thru avialable releases.
                foreach (JObject release in (JArray)releases)
                {
                    // Drafts are not returned by API, but just in case...
                    bool draft = release["draft"].Value <bool>();
                    if (draft)
                    {
                        continue;        // Ignore drafts.
                    }
                    // Check if there are assets attached.
                    JArray assets = (JArray)release["assets"];
                    if (assets.Count < 1)
                    {
                        continue;                   // No assets, ignore it.
                    }
                    // Compare release tag with our version (tag).
                    string  tag     = release["tag_name"].Value <string>();
                    Version version = new Version(tag);
                    if (version.CompareTo(current) <= 0)
                    {
                        // Same or older version.
                        IsChecked = true;

                        return(null);
                    }

                    // Check if it is pre-release and we want to update to it.
                    bool prerelease = release["prerelease"].Value <bool>();
                    if (prerelease && !Prerelease)
                    {
                        continue;                            // Found unwanted pre-release, ignore it.
                    }
                    // Find release package.
                    string  fileName = null;
                    JObject pkgAsset = null;
                    foreach (JObject asset in assets)
                    {
                        // Check if asset upload completed.
                        if (asset["state"].Value <string>() != "uploaded")
                        {
                            continue;
                        }

                        string content_type = asset["content_type"].Value <string>();
                        if (content_type != PackageContentType)
                        {
                            continue;                                     // Not a package, ignore it.
                        }
                        fileName = asset["name"].Value <string>();
                        Match m = RePackage.Match(fileName);
                        if (m.Success)
                        {
                            // Found release package.
                            pkgAsset = asset;
                            break;
                        }
                    }
                    if (pkgAsset == null)
                    {
                        continue;                   // No package found.
                    }
                    // This is newer release.
                    IsChecked = true;
                    Latest    = new Release
                    {
                        Name         = release["name"].Value <string>(),
                        Description  = release["body"].Value <string>(),
                        IsPrerelease = prerelease,
                        // A release is an update, if file name starts with our PackageName.
                        IsUpdate        = fileName.StartsWith(GetPackageName(Properties.Version.ProductName) + "-"),
                        PackageFileName = fileName,
                        Version         = tag,
                        URI             = new Uri(pkgAsset["browser_download_url"].Value <string>())
                    };

                    // We are done, exit loop.
                    break;
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    throw new UpdaterException("HTTP " + ((int)((HttpWebResponse)e.Response).StatusCode) + " " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                else
                {
                    throw new UpdaterException(e.Message, e);
                }
            }
            catch (Exception e)
            {
                throw new UpdaterException(e.Message, e);
            }

            return(Latest);
        }
Ejemplo n.º 32
0
        public void GetThemes()
        {
            var builder = new DbContextOptionsBuilder <StatisticsDbContext>();

            builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
            var options = builder.Options;

            using (var context = new StatisticsDbContext(options, null))
            {
                var themeA = new Theme
                {
                    Id    = Guid.NewGuid(),
                    Title = "Theme A",
                    Slug  = "theme-a",
                };

                var themeB = new Theme
                {
                    Id    = Guid.NewGuid(),
                    Title = "Theme B",
                    Slug  = "theme-b",
                };

                var themeATopicA = new Topic
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic A",
                    ThemeId = themeA.Id,
                    Slug    = "theme-a-topic-a"
                };

                var themeATopicB = new Topic
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic B",
                    ThemeId = themeA.Id,
                    Slug    = "theme-a-topic-b"
                };

                var themeBTopicA = new Topic
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic A",
                    ThemeId = themeB.Id,
                    Slug    = "theme-b-topic-a"
                };

                var themeBTopicB = new Topic
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic B",
                    ThemeId = themeB.Id,
                    Slug    = "theme-b-topic-b"
                };

                var themeATopicAPublicationA = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic A publication A",
                    TopicId = themeATopicA.Id,
                    Slug    = "theme-a-topic-a-publication-a"
                };

                var themeATopicAPublicationB = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic A publication B",
                    TopicId = themeATopicA.Id,
                    Slug    = "theme-a-topic-a-publication-B"
                };

                var themeATopicBPublicationA = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic B publication A",
                    TopicId = themeATopicB.Id,
                    Slug    = "theme-a-topic-b-publication-a"
                };

                var themeATopicBPublicationB = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme A topic B publication B",
                    TopicId = themeATopicB.Id,
                    Slug    = "theme-a-topic-b-publication-B"
                };

                var themeBTopicAPublicationA = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic A publication A",
                    TopicId = themeBTopicA.Id,
                    Slug    = "theme-b-topic-a-publication-a"
                };

                var themeBTopicAPublicationB = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic A publication B",
                    TopicId = themeBTopicA.Id,
                    Slug    = "theme-b-topic-a-publication-B"
                };

                var themeBTopicBPublicationA = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic B publication A",
                    TopicId = themeBTopicB.Id,
                    Slug    = "theme-b-topic-b-publication-a"
                };

                var themeBTopicBPublicationB = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Theme B topic B publication B",
                    TopicId = themeBTopicB.Id,
                    Slug    = "theme-b-topic-b-publication-B"
                };

                var themeATopicAPublicationARelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeATopicAPublicationA,
                    Published   = DateTime.UtcNow
                };

                var themeATopicAPublicationBRelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeATopicAPublicationB,
                    Published   = DateTime.UtcNow
                };

                var themeATopicBPublicationARelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeATopicBPublicationA,
                    Published   = DateTime.UtcNow
                };

                var themeATopicBPublicationBRelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeATopicBPublicationB,
                    Published   = DateTime.UtcNow
                };

                var themeBTopicAPublicationARelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeBTopicAPublicationA,
                    Published   = DateTime.UtcNow
                };

                var themeBTopicAPublicationBRelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeBTopicAPublicationB,
                    Published   = DateTime.UtcNow
                };

                var themeBTopicBPublicationARelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeBTopicBPublicationA,
                    Published   = DateTime.UtcNow
                };

                var themeBTopicBPublicationBRelease = new Release
                {
                    Id          = Guid.NewGuid(),
                    Publication = themeBTopicBPublicationB,
                    Published   = DateTime.UtcNow
                };

                context.AddRange(new List <Theme>
                {
                    themeA, themeB
                });

                context.AddRange(new List <Topic>
                {
                    themeATopicA, themeATopicB, themeBTopicA, themeBTopicB
                });

                context.AddRange(new List <Publication>
                {
                    themeATopicAPublicationA,
                    themeATopicAPublicationB,
                    themeATopicBPublicationA,
                    themeATopicBPublicationB,
                    themeBTopicAPublicationA,
                    themeBTopicAPublicationB,
                    themeBTopicBPublicationA,
                    themeBTopicBPublicationB
                });

                context.AddRange(new List <Release>
                {
                    themeATopicAPublicationARelease,
                    themeATopicAPublicationBRelease,
                    themeATopicBPublicationARelease,
                    themeATopicBPublicationBRelease,
                    themeBTopicAPublicationARelease,
                    themeBTopicAPublicationBRelease,
                    themeBTopicBPublicationARelease,
                    themeBTopicBPublicationBRelease
                });

                context.SaveChanges();

                var service =
                    new ThemeMetaService(context, MapperUtils.MapperForProfile <DataServiceMappingProfiles>());

                var result = service.GetThemes().ToList();

                Assert.Equal(2, result.Count);
                Assert.Equal(themeA.Id, result[0].Id);
                Assert.Equal(themeA.Slug, result[0].Slug);
                Assert.Equal(themeA.Title, result[0].Title);
                var themeATopics = result[0].Topics.ToList();

                Assert.Equal(2, themeATopics.Count);
                Assert.Equal(themeATopicA.Id, themeATopics[0].Id);
                Assert.Equal(themeATopicA.Slug, themeATopics[0].Slug);
                Assert.Equal(themeATopicA.Title, themeATopics[0].Title);
                var themeATopicAPublications = themeATopics[0].Publications.ToList();

                Assert.Equal(2, themeATopicAPublications.Count);
                Assert.Equal(themeATopicAPublicationA.Id, themeATopicAPublications[0].Id);
                Assert.Equal(themeATopicAPublicationA.Slug, themeATopicAPublications[0].Slug);
                Assert.Equal(themeATopicAPublicationA.Title, themeATopicAPublications[0].Title);
                Assert.Equal(themeATopicAPublicationB.Id, themeATopicAPublications[1].Id);
                Assert.Equal(themeATopicAPublicationB.Slug, themeATopicAPublications[1].Slug);
                Assert.Equal(themeATopicAPublicationB.Title, themeATopicAPublications[1].Title);

                Assert.Equal(themeATopicB.Id, themeATopics[1].Id);
                Assert.Equal(themeATopicB.Slug, themeATopics[1].Slug);
                Assert.Equal(themeATopicB.Title, themeATopics[1].Title);
                var themeATopicBPublications = themeATopics[1].Publications.ToList();

                Assert.Equal(2, themeATopicBPublications.Count);
                Assert.Equal(themeATopicBPublicationA.Id, themeATopicBPublications[0].Id);
                Assert.Equal(themeATopicBPublicationA.Slug, themeATopicBPublications[0].Slug);
                Assert.Equal(themeATopicBPublicationA.Title, themeATopicBPublications[0].Title);
                Assert.Equal(themeATopicBPublicationB.Id, themeATopicBPublications[1].Id);
                Assert.Equal(themeATopicBPublicationB.Slug, themeATopicBPublications[1].Slug);
                Assert.Equal(themeATopicBPublicationB.Title, themeATopicBPublications[1].Title);

                Assert.Equal(themeB.Id, result[1].Id);
                Assert.Equal(themeB.Slug, result[1].Slug);
                Assert.Equal(themeB.Title, result[1].Title);
                var themeBTopics = result[1].Topics.ToList();

                Assert.Equal(2, themeBTopics.Count);
                Assert.Equal(themeBTopicA.Id, themeBTopics[0].Id);
                Assert.Equal(themeBTopicA.Slug, themeBTopics[0].Slug);
                Assert.Equal(themeBTopicA.Title, themeBTopics[0].Title);
                var themeBTopicAPublications = themeBTopics[0].Publications.ToList();

                Assert.Equal(2, themeBTopicAPublications.Count);
                Assert.Equal(themeBTopicAPublicationA.Id, themeBTopicAPublications[0].Id);
                Assert.Equal(themeBTopicAPublicationA.Slug, themeBTopicAPublications[0].Slug);
                Assert.Equal(themeBTopicAPublicationA.Title, themeBTopicAPublications[0].Title);
                Assert.Equal(themeBTopicAPublicationB.Id, themeBTopicAPublications[1].Id);
                Assert.Equal(themeBTopicAPublicationB.Slug, themeBTopicAPublications[1].Slug);
                Assert.Equal(themeBTopicAPublicationB.Title, themeBTopicAPublications[1].Title);

                Assert.Equal(themeBTopicB.Id, themeBTopics[1].Id);
                Assert.Equal(themeBTopicB.Slug, themeBTopics[1].Slug);
                Assert.Equal(themeBTopicB.Title, themeBTopics[1].Title);
                var themeBTopicBPublications = themeBTopics[1].Publications.ToList();

                Assert.Equal(2, themeBTopicBPublications.Count);
                Assert.Equal(themeBTopicBPublicationA.Id, themeBTopicBPublications[0].Id);
                Assert.Equal(themeBTopicBPublicationA.Slug, themeBTopicBPublications[0].Slug);
                Assert.Equal(themeBTopicBPublicationA.Title, themeBTopicBPublications[0].Title);
                Assert.Equal(themeBTopicBPublicationB.Id, themeBTopicBPublications[1].Id);
                Assert.Equal(themeBTopicBPublicationB.Slug, themeBTopicBPublications[1].Slug);
                Assert.Equal(themeBTopicBPublicationB.Title, themeBTopicBPublications[1].Title);
            }
        }
Ejemplo n.º 33
0
 static async Task <ReleaseAsset> UploadWithRetry(string projDir, GitHubClient client, Release release2, string fileName)
 {
     for (var i = 0; i < 5; i++)
     {
         try
         {
             return(await client.Repository.Release.UploadAsset(release2, new ReleaseAssetUpload(fileName, "application/zip", File.OpenRead(projDir + "/bb/bin/Release/netcoreapp3.1/" + fileName), TimeSpan.FromMinutes(14))));
         }
         catch (Exception)
         {
             Console.WriteLine("Upload Asset " + fileName + " failed " + i);
         }
     }
     throw new OperationCanceledException("Upload Asset " + fileName + " failed");
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Get release dates for all releases of economic data. Corresponds to http://api.stlouisfed.org/fred/releases/dates
        /// </summary>
        /// <param name="realtimeStart">The start of the real-time period. </param>
        /// <param name="realtimeEnd">The end of the real-time period. </param>
        /// <param name="limit">The maximum number of results to return. An integer between 1 and 1000, optional, default: 1000</param>
        /// <param name="offset">non-negative integer, optional, default: 0</param>
        /// <param name="orderBy">Order results by values of the specified attribute.</param>
        /// <param name="order">Sort results is ascending or descending release date order.</param>
        /// <param name="includeReleaseWithNoData">Determines whether release dates with no data available are returned. The default value 'false' excludes release dates that do not have data.</param>
        /// <returns>Release dates for all releases of economic data.</returns>
        public async Task<IEnumerable<ReleaseDate>> GetReleasesDatesAsync(DateTime realtimeStart, DateTime realtimeEnd, int limit = 1000,
                                                         int offset = 0,
                                                         Release.OrderBy orderBy = Release.OrderBy.ReleaseId,
                                                         SortOrder order = SortOrder.Ascending,
                                                         bool includeReleaseWithNoData = false)
        {
            var url = String.Format(Urls.ReleasesDates, _key, realtimeStart.ToFredDateString(),
                                    realtimeEnd.ToFredDateString(), limit, offset, Extensions.ToString(orderBy),
                                    Extensions.ToString(order),
                                    includeReleaseWithNoData.ToString(CultureInfo.GetCultureInfo("en-US")).
                                        ToLowerInvariant());

            var root = await GetRootAsync(url);
            return (from releaseDate in root.Elements("release_date")
                    select new ReleaseDate
                    {
                        ReleaseId = int.Parse(releaseDate.Attribute("release_id").Value),
                        ReleaseName = releaseDate.Attribute("release_name").Value,
                        Date = releaseDate.Value.ToFredDate()
                    }).ToList();
        }
Ejemplo n.º 35
0
        public void GetThemes_PublicationHasReleasesNotPublished()
        {
            var builder = new DbContextOptionsBuilder <StatisticsDbContext>();

            builder.UseInMemoryDatabase(Guid.NewGuid().ToString());
            var options = builder.Options;

            using (var context = new StatisticsDbContext(options, null))
            {
                var theme = new Theme
                {
                    Id    = Guid.NewGuid(),
                    Title = "Theme",
                    Slug  = "theme"
                };

                var topic = new Topic
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Topic",
                    Slug    = "topic",
                    ThemeId = theme.Id
                };

                var publicationA = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Publication A",
                    Slug    = "publication-a",
                    TopicId = topic.Id
                };

                var publicationB = new Publication
                {
                    Id      = Guid.NewGuid(),
                    Title   = "Publication B",
                    Slug    = "publication-b",
                    TopicId = topic.Id
                };

                var publicationARelease = new Release
                {
                    Id            = Guid.NewGuid(),
                    PublicationId = publicationA.Id,
                    Published     = DateTime.UtcNow
                };

                var publicationBRelease = new Release
                {
                    Id            = Guid.NewGuid(),
                    PublicationId = publicationB.Id,
                    Published     = null
                };

                context.Add(theme);
                context.Add(topic);

                context.AddRange(new List <Publication>
                {
                    publicationA, publicationB
                });

                context.AddRange(new List <Release>
                {
                    publicationARelease, publicationBRelease
                });

                context.SaveChanges();

                var service =
                    new ThemeMetaService(context, MapperUtils.MapperForProfile <DataServiceMappingProfiles>());

                var result = service.GetThemes().ToList();

                Assert.Single(result);
                Assert.Equal(theme.Id, result[0].Id);
                Assert.Equal(theme.Slug, result[0].Slug);
                Assert.Equal(theme.Title, result[0].Title);
                var topics = result[0].Topics.ToList();

                Assert.Single(topics);
                Assert.Equal(topic.Id, topics[0].Id);
                Assert.Equal(topic.Slug, topics[0].Slug);
                Assert.Equal(topic.Title, topics[0].Title);
                var publications = topics[0].Publications.ToList();

                Assert.Single(publications);
                Assert.Equal(publicationA.Id, publications[0].Id);
                Assert.Equal(publicationA.Slug, publications[0].Slug);
                Assert.Equal(publicationA.Title, publications[0].Title);

                // Publication B is not included because it's Release is not published
            }
        }
Ejemplo n.º 36
0
 public ReleaseTests()
 {
     this.release = TestHelper.GetJson <Release>("release-get.json");
 }
Ejemplo n.º 37
0
 public SwfDataModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget)
 {
 }
            public void EnsuresArgumentsNotNull()
            {
                var releasesClient = new ObservableReleasesClient(Substitute.For<IGitHubClient>());

                var release = new Release { UploadUrl = "https://uploads.github.com/anything" };
                var uploadData = new ReleaseAssetUpload { FileName = "good", ContentType = "good/good", RawData = Stream.Null };

                Assert.Throws<ArgumentNullException>(() => releasesClient.UploadAsset(null, uploadData));
                Assert.Throws<ArgumentNullException>(() => releasesClient.UploadAsset(release, null));
            }
Ejemplo n.º 39
0
        public TrackCollection LoadTracksForGivenRelease(Release release)
        {
            String sql = "SELECT * FROM track, release, artist WHERE (release.ID = track.album) AND (artist.ID = track.artist) AND (artist.ID = track.artist)  AND " +
                "release.identifier = '" + release.Identifier + "'";
            DataSet result = MakeDataSet(sql);
            TrackCollection tc = new TrackCollection(this, release, new List<Track>());
            foreach (DataRow row in result.Tables[0].Rows)
            {
                Track t = TrackFromDataRow(row);
                tc.Add(t);
            }

            return tc;
        }
Ejemplo n.º 40
0
            public async Task EnsuresArgumentsNotNull()
            {
                var releasesClient = new ReleasesClient(Substitute.For<IApiConnection>());

                var release = new Release { UploadUrl = "https://uploads.github.com/anything" };
                var uploadData = new ReleaseAssetUpload { FileName = "good", ContentType = "good/good", RawData = Stream.Null };
                await AssertEx.Throws<ArgumentNullException>(async () => await releasesClient.UploadAsset(null, uploadData));
                await AssertEx.Throws<ArgumentNullException>(async () => await releasesClient.UploadAsset(release, null));
            }
Ejemplo n.º 41
0
		public ReleaseAttribute(string name, string created, string revision) {
			release = new Release();
			release.Version.Name = name;
			release.Version.Created = DateTime.Parse(created);
			release.Version.Revision = revision;
		}
Ejemplo n.º 42
0
        // Dispose of current update process.
        public static void Dispose()
        {
            if (Latest != null)
            {
                if (Latest.IsDownloading)
                    throw new UpdaterException(L10n.Message("Download still in progress"));
                Latest.Dispose();
                Latest = null;
            }

            IsChecked = false;
        }
Ejemplo n.º 43
0
        public int CompareTo(PackageVersion other)
        {
            Exception error;

            if (!Validate(out error))
            {
                throw error;
            }
            if (!other.Validate(out error))
            {
                throw new ArgumentException("Invalid version", "other", error);
            }

            int c = Epoch.CompareTo(other.Epoch);

            if (c != 0)
            {
                return(c);
            }

            if (Release != null && other.Release != null)
            {
                for (int i = 0; i < Release.Count || i < other.Release.Count; ++i)
                {
                    c = Release.ElementAtOrDefault(i).CompareTo(other.Release.ElementAtOrDefault(i));
                    if (c != 0)
                    {
                        return(c);
                    }
                }
            }
            else if (Release == null)
            {
                // No release, so we sort earlier if other has one
                return(other.Release == null ? 0 : -1);
            }
            else
            {
                // We have a release and other doesn't, so we sort later
                return(1);
            }

            if (PreReleaseName != other.PreReleaseName)
            {
                // Regular comparison mishandles None
                if (PreReleaseName == PackageVersionPreReleaseName.None)
                {
                    return(1);
                }
                else if (other.PreReleaseName == PackageVersionPreReleaseName.None)
                {
                    return(-1);
                }
                // Neither value is None, so CompareTo will be correct
                return(PreReleaseName.CompareTo(other.PreReleaseName));
            }

            c = PreRelease.CompareTo(other.PreRelease);
            if (c != 0)
            {
                return(c);
            }

            c = PostRelease.CompareTo(other.PostRelease);
            if (c != 0)
            {
                return(c);
            }

            c = DevRelease.CompareTo(other.DevRelease);
            if (c != 0)
            {
                if (DevRelease == 0 || other.DevRelease == 0)
                {
                    // When either DevRelease is zero, the sort order needs to
                    // be reversed.
                    return(-c);
                }
                return(c);
            }

            if (string.IsNullOrEmpty(LocalVersion))
            {
                if (string.IsNullOrEmpty(other.LocalVersion))
                {
                    // No local versions, so we are equal
                    return(0);
                }
                // other has a local version, so we sort earlier
                return(-1);
            }
            else if (string.IsNullOrEmpty(other.LocalVersion))
            {
                // we have a local version, so we sort later
                return(1);
            }

            var lv1 = LocalVersion.Split('.');
            var lv2 = other.LocalVersion.Split('.');

            for (int i = 0; i < lv1.Length || i < lv2.Length; ++i)
            {
                if (i >= lv1.Length)
                {
                    // other has a longer local version, so we sort earlier
                    return(-1);
                }
                else if (i >= lv2.Length)
                {
                    // we have a longer local version, so we sort later
                    return(1);
                }
                var p1 = lv1[i];
                var p2 = lv2[i];

                int i1, i2;
                if (int.TryParse(p1, out i1))
                {
                    if (int.TryParse(p2, out i2))
                    {
                        c = i1.CompareTo(i2);
                    }
                    else
                    {
                        // we have a number and other doesn't, so we sort later
                        return(1);
                    }
                }
                else if (int.TryParse(p2, out i2))
                {
                    // other has a number and we don't, so we sort earlier
                    return(-1);
                }
                else
                {
                    c = p1.CompareTo(p2);
                }

                if (c != 0)
                {
                    return(c);
                }
            }

            // After all that, we are equal!
            return(0);
        }
Ejemplo n.º 44
0
 public static E TriggerRelease(double t0, double e0, Amplitude sustainLevel, double release)
 => (t)
 => !HasElapsed(t0, t, release)
             ? Release(t0, e0 > Normalize(sustainLevel) ? e0 : Normalize(sustainLevel), release)(t)
             : Mute()(t);
            public void CallsIntoClient()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var releasesClient = new ObservableReleasesClient(gitHubClient);
                var release = new Release { UploadUrl = "https://uploads.test.dev/does/not/matter/releases/1/assets{?name}" };
                var rawData = Substitute.For<Stream>();
                var upload = new ReleaseAssetUpload { FileName = "example.zip", ContentType = "application/zip", RawData = rawData };

                releasesClient.UploadAsset(release, upload);

                gitHubClient.Release.Received(1).UploadAsset(release, upload);
            }
Ejemplo n.º 46
0
        internal static async Task CheckForUpdates()
        {
            // Delay the update check for 3 seconds so that it has the minimal impact on startup.
            await Task.Delay(3000);

            // A self-built pwsh for development purpose has the SHA1 commit hash baked in 'GitCommitId',
            // which is 40 characters long. So we can quickly check the length of 'GitCommitId' to tell
            // if this is a self-built pwsh, and skip the update check if so.
            if (PSVersionInfo.GitCommitId.Length > 40)
            {
                return;
            }

            // Daily builds do not support update notifications
            string preReleaseLabel = PSVersionInfo.PSCurrentVersion.PreReleaseLabel;

            if (preReleaseLabel != null && preReleaseLabel.StartsWith("daily", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            // If the host is not connect to a network, skip the rest of the check.
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                return;
            }

            // Create the update cache directory if it doesn't exists
            if (!Directory.Exists(s_cacheDirectory))
            {
                Directory.CreateDirectory(s_cacheDirectory);
            }

            bool parseSuccess = TryParseUpdateFile(
                out string updateFilePath,
                out SemanticVersion lastUpdateVersion,
                out DateTime lastUpdateDate);

            DateTime today = DateTime.UtcNow;

            if (parseSuccess && updateFilePath != null && (today - lastUpdateDate).TotalDays < 7)
            {
                // There is an existing update file, and the last update was less than 1 week ago.
                // It's unlikely a new version is released within 1 week, so we can skip this check.
                return;
            }

            // Construct the sentinel file paths for today's check.
            string todayDoneFileName = string.Format(
                CultureInfo.InvariantCulture,
                s_doneFileNameTemplate,
                today.Year.ToString(),
                today.Month.ToString(),
                today.Day.ToString());

            string todayDoneFilePath = Path.Combine(s_cacheDirectory, todayDoneFileName);

            if (File.Exists(todayDoneFilePath))
            {
                // A successful update check has been done today.
                // We can skip this update check.
                return;
            }

            try
            {
                // Use 's_sentinelFileName' as the file lock.
                // The update-check tasks started by every 'pwsh' process of the same version will compete on holding this file.
                string sentinelFilePath = Path.Combine(s_cacheDirectory, s_sentinelFileName);
                using (new FileStream(sentinelFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, bufferSize: 1, FileOptions.DeleteOnClose))
                {
                    if (File.Exists(todayDoneFilePath))
                    {
                        // After acquiring the file lock, it turns out a successful check has already been done for today.
                        // Then let's skip this update check.
                        return;
                    }

                    // Now it's guaranteed that this is the only process that reaches here.
                    // Clean up the old '.done' file, there should be only one of it.
                    foreach (string oldFile in Directory.EnumerateFiles(s_cacheDirectory, s_doneFileNamePattern, s_enumOptions))
                    {
                        File.Delete(oldFile);
                    }

                    if (!parseSuccess)
                    {
                        // The update file is corrupted, either because more than one update files were found unexpectedly,
                        // or because the update file name failed to be parsed into a release version and a publish date.
                        // This is **very unlikely** to happen unless the file is accidentally altered manually.
                        // We try to recover here by cleaning up all update files for the configured notification type.
                        foreach (string file in Directory.EnumerateFiles(s_cacheDirectory, s_updateFileNamePattern, s_enumOptions))
                        {
                            File.Delete(file);
                        }
                    }

                    // Do the real update check:
                    //  - Send HTTP request to query for the new release/pre-release;
                    //  - If there is a valid new release that should be reported to the user,
                    //    create the file `update<NotificationType>_<tag>_<publish-date>` when no `update` file exists,
                    //    or rename the existing file to `update<NotificationType>_<new-version>_<new-publish-date>`.
                    SemanticVersion baselineVersion = lastUpdateVersion ?? PSVersionInfo.PSCurrentVersion;
                    Release         release         = await QueryNewReleaseAsync(baselineVersion);

                    if (release != null)
                    {
                        // The date part of the string is 'YYYY-MM-DD'.
                        const int dateLength        = 10;
                        string    newUpdateFileName = string.Format(
                            CultureInfo.InvariantCulture,
                            s_updateFileNameTemplate,
                            release.TagName,
                            release.PublishAt.Substring(0, dateLength));

                        string newUpdateFilePath = Path.Combine(s_cacheDirectory, newUpdateFileName);

                        if (updateFilePath == null)
                        {
                            new FileStream(newUpdateFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close();
                        }
                        else
                        {
                            File.Move(updateFilePath, newUpdateFilePath);
                        }
                    }

                    // Finally, create the `todayDoneFilePath` file as an indicator that a successful update check has finished today.
                    new FileStream(todayDoneFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None).Close();
                }
            }
            catch (Exception)
            {
                // There are 2 possible reason for the exception:
                // 1. An update check initiated from another `pwsh` process is in progress.
                //    It's OK to just return and let that update check to finish the work.
                // 2. The update check failed (ex. internet connectivity issue, GitHub service failure).
                //    It's OK to just return and let another `pwsh` do the check at later time.
            }
        }
Ejemplo n.º 47
0
 public PacketModifierBase(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget)
 {
     Connection     = connection;
     PacketOriginal = packetOriginal;
     ReleaseFrom    = releaseFrom;
     ReleaseTarget  = releaseTarget;
     PacketModified = CreatePacket(Registar.GetPacketIdModified(packetOriginal.Header, packetOriginal.Type, releaseFrom, releaseTarget));
 }
Ejemplo n.º 48
0
            public async Task EnsuresNonNullArguments()
            {
                var releasesClient = new ReleasesClient(Substitute.For<IApiConnection>());

                var release = new Release("https://uploads.github.com/anything");
                var uploadData = new ReleaseAssetUpload("good", "good/good", Stream.Null, null);

                await Assert.ThrowsAsync<ArgumentNullException>(() => releasesClient.UploadAsset(null, uploadData));
                await Assert.ThrowsAsync<ArgumentNullException>(() => releasesClient.UploadAsset(release, null));
            }
Ejemplo n.º 49
0
        public Release ReleaseFromDataRow(DataRow releaseRow)
        {
            Release r = new Release(this);
            r.Name = (String)releaseRow["release.title"];
            r.Image = (String)releaseRow["release.image"];
            r.Identifier = (String)releaseRow["release.identifier"];
            r.ReleaseDate = (DateTime)releaseRow["release_date"];
                r.Status = (Spider.Media.Resource.State)releaseRow["release.status"];

            r.Artist = new Artist(this)
            {
                Name = (String)releaseRow["artist.title"],
                Identifier = (String)releaseRow["artist.identifier"]
            };
            return r;
        }
Ejemplo n.º 50
0
        public void Parse(TextReader reader)
        {
            string publisher = null;
            bool startParsing = false;
            string line;

            DateTime shippingDate = DateTime.MinValue;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();

                if (line.Length == 0)
                    continue;

                if (line.Contains("PREMIER PUBLISHERS"))
                {
                    startParsing = true;
                    continue;
                }

                var headerPattern = new Regex(@"ITEM\s+CODE\s+TITLE\s+PRICE", RegexOptions.IgnoreCase);

                if (!startParsing && shippingDate == DateTime.MinValue)
                {
                    shippingDate = ShippingDate(line);

                    if (shippingDate == DateTime.MinValue)
                        continue;

                    using (var db = session.SessionFactory("test"))
                    {
                        using (var s = db.OpenSession())
                        {
                            using (var transaction = s.BeginTransaction())
                            {
                                var date = shippingDate;
                                var release = s.QueryOver<Release>().Where(r => r.Date == date).SingleOrDefault<Release>();
                                if (release == null)
                                {
                                    release = new Release { Created = DateTime.Now, Date = shippingDate };
                                    s.SaveOrUpdate(release);
                                    transaction.Commit();
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    continue;
                }

                if (headerPattern.IsMatch(line))
                {
                    startParsing = true;
                    continue;
                }

                if (!startParsing && Publisher.IsPublisher(line))
                {
                    publisher = Publisher.PrettyName(line);
                    startParsing = true;
                }

                if (!startParsing)
                    continue;

                if (Publisher.IsPublisher(line))
                {
                    publisher = Publisher.PrettyName(line);
                    continue;
                }

                var titleInfo = parser.BuildTitleInfo(line, publisher, shippingDate);

                if (titleInfo == null)
                    continue;

                titleInfo.Insert(session);
            }
        }
Ejemplo n.º 51
0
        /* Checks for updates and returns release informations when there is newer one.
         * Returns null if there is no newer release.
         * If Prerelease argument is true, it will return also Pre-release, otherwise Pre-releases are ignored.
         * An existing last checked release will be discarded.
         * Throws UpdaterException if error occurs.
         */
        public static Release CheckForUpdates(bool Prerelease = true)
        {
            if (Latest != null)
            {
                if (Latest.IsDownloading)
                    throw new UpdaterException(L10n.Message("Download already in progress"));

                // If release was installed, report no update.
                if (Latest.IsInstalled) return null;

                Dispose();
            }

            if (IsNewerProductInstalled())
            {
                // Newer product is installed, there is no update.
                IsChecked = true;

                return null;
            }

            var webClient = new UpdaterWebClient();
            webClient.Encoding = Encoding.UTF8;

            try
            {
                string json = webClient.DownloadString(GitAPILatestReleaseURL);
                JArray releases = JArray.Parse(json);
                if (releases.Count < 1)
                    throw new UpdaterException(L10n.Message("No release found"));

                Version current = GetCurrentVersion(); // Current version (tag).

                // Iterate thru avialable releases.
                foreach (JObject release in (JArray)releases)
                {
                    // Drafts are not returned by API, but just in case...
                    bool draft = release["draft"].Value<bool>();
                    if (draft) continue; // Ignore drafts.

                    // Check if there are assets attached.
                    JArray assets = (JArray)release["assets"];
                    if (assets.Count < 1) continue; // No assets, ignore it.

                    // Compare release tag with our version (tag).
                    string tag = release["tag_name"].Value<string>();
                    Version version = new Version(tag);
                    if (version.CompareTo(current) <= 0)
                    {
                        // Same or older version.
                        IsChecked = true;

                        return null;
                    }

                    // Check if it is pre-release and we want to update to it.
                    bool prerelease = release["prerelease"].Value<bool>();
                    if (prerelease && !Prerelease) continue; // Found unwanted pre-release, ignore it.

                    // Find release package.
                    string fileName = null;
                    JObject pkgAsset = null;
                    foreach (JObject asset in assets)
                    {
                        // Check if asset upload completed.
                        if (asset["state"].Value<string>() != "uploaded")
                            continue;

                        string content_type = asset["content_type"].Value<string>();
                        if (content_type != PackageContentType) continue; // Not a package, ignore it.

                        fileName = asset["name"].Value<string>();
                        Match m = RePackage.Match(fileName);
                        if (m.Success)
                        {
                            // Found release package.
                            pkgAsset = asset;
                            break;
                        }
                    }
                    if (pkgAsset == null) continue; // No package found.

                    // This is newer release.
                    IsChecked = true;
                    Latest = new Release
                    {
                        Name = release["name"].Value<string>(),
                        Description = release["body"].Value<string>(),
                        IsPrerelease = prerelease,
                        // A release is an update, if file name starts with our PackageName.
                        IsUpdate = fileName.StartsWith(GetPackageName(Properties.Version.ProductName) + "-"),
                        PackageFileName = fileName,
                        Version = tag,
                        URI = new Uri(pkgAsset["browser_download_url"].Value<string>())
                    };

                    // We are done, exit loop.
                    break;
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                    throw new UpdaterException("HTTP " + ((int)((HttpWebResponse)e.Response).StatusCode) + " " + ((HttpWebResponse)e.Response).StatusDescription);
                else
                    throw new UpdaterException(e.Message, e);
            }
            catch (Exception e)
            {
                throw new UpdaterException(e.Message, e);
            }

            return Latest;
        }
            public void EnsuresArgumentsNotNull()
            {
                var releasesClient = new ObservableReleasesClient(Substitute.For<IGitHubClient>());

                var release = new Release("https://uploads.github.com/anything");
                var uploadData = new ReleaseAssetUpload("good", "good/good", Stream.Null, null);

                Assert.Throws<ArgumentNullException>(() => releasesClient.UploadAsset(null, uploadData));
                Assert.Throws<ArgumentNullException>(() => releasesClient.UploadAsset(release, null));
            }
Ejemplo n.º 53
0
 public void Save(Release release)
 {
     this.releasesCollection.Save(release);
 }
Ejemplo n.º 54
0
        public async Task <int> changeCheckListHandlingStartDate(int ReleaseID, List <int> changedMilestonesIds, Release newRelease)
        {
            int count = 0, employeeId;
            var histories = new List <History>();

            using (IReleaseChecklistAnswerRepository db = new ReleaseChecklistAnswerRepository())
            {
                IEnumerable <ReleaseChecklistAnswer> releaseChecklistAnswer = db.Where(cl => cl.ReleaseID == ReleaseID).Include(cl => cl.Question).Where(cl => changedMilestonesIds.Where(m => m == cl.Question.MilestoneID || m == cl.Question.PreviousMilestoneID).Count() > 0);

                if (releaseChecklistAnswer != null && releaseChecklistAnswer.ToList().Count() > 0)
                {
                    using (IEmployeeRepository current_db = new EmployeeRepository())
                    {
                        employeeId = current_db.GetEmployee(ConfigurationManager.AppSettings["SystemUserNtnet"]);
                    }

                    //ActivityLog activityLog = new ActivityLog(employeeId, ActivityType.Edit);
                    //using (IActivityLogRepository current_db = new ActivityLogRepository())
                    //{
                    //    current_db.Add(activityLog);
                    //    await current_db.SaveChangesAsync();
                    //}

                    foreach (ReleaseChecklistAnswer cl in releaseChecklistAnswer)
                    {
                        var history = new History();
                        history.ReleaseID = cl.ReleaseID;
                        history.ItemID    = cl.ReleaseChecklistAnswerID;
                        history.TableID   = StaticResources.GetTableID(ConfigurationManager.AppSettings["ReleaseChecklistAnswer"]);
                        //  history.ActivityLogID = activityLog.ActivityLogID;
                        history.OldValue     = cl.HandlingStartDate.ToString();
                        history.FieldName    = "HandlingStartDate";
                        cl.HandlingStartDate = new QuestionRepository().HandlingStartDatecalculation(newRelease, cl.Question.MilestoneID, cl.Question.PreviousMilestoneID, cl.Question.RatioBetweenMilestones);
                        history.NewValue     = cl.HandlingStartDate.ToString();
                        if (history.OldValue != history.NewValue)
                        {
                            histories.Add(history);
                        }
                    }



                    //    var history = new History();
                    //    history.OldValue = cl.HandlingStartDate.ToString();
                    //    history.FieldName = "HandlingStartDate";
                    //    cl.HandlingStartDate = new QuestionRepository().HandlingStartDatecalculation(newRelease, cl.Question.MilestoneID, cl.Question.PreviousMilestoneID, cl.Question.RatioBetweenMilestones);
                    //    history.NewValue = cl.HandlingStartDate.ToString();
                    //    histories.Add(history);
                    //    history.ActivityLogs = new List<ActivityLog>() { new ActivityLog(employeeId,
                    //            cl.ReleaseChecklistAnswerID, cl.ReleaseID, 26 , ActivityType.Edit)};
                    //});



                    //await releaseChecklistAnswer.ForEachAsync(cl =>
                    //{

                    //});
                    count += await db.SaveAsync(null, true, histories);
                }
            }

            return(count);
        }
Ejemplo n.º 55
0
            public async Task OverrideDefaultTimeout()
            {
                var newTimeout = TimeSpan.FromSeconds(100);

                var apiConnection = Substitute.For<IApiConnection>();

                var fixture = new ReleasesClient(apiConnection);

                var release = new Release("https://uploads.github.com/anything");
                var uploadData = new ReleaseAssetUpload("good", "good/good", Stream.Null, newTimeout);

                await fixture.UploadAsset(release, uploadData);

                apiConnection.Received().Post<ReleaseAsset>(Arg.Any<Uri>(), uploadData.RawData, Arg.Any<string>(), uploadData.ContentType, newTimeout);
            }
Ejemplo n.º 56
0
        public static void SetPlayer(PlayerMobile mobile)
        {
            Player = mobile;

            PlayerInitializedEvent?.Invoke(mobile);

            mobile.MobileStatusUpdated += (status, newStatus) =>
            {
                if (!Options.CurrentOptions.UseDeathScreenWhilstHidden)
                {
                    return;
                }

                if (newStatus.HasFlag(MobileStatus.Hidden))
                {
                    SendPacketToClient(new MobileUpdate(mobile.Serial, mobile.ID == 0x191 ? 0x193 : 0x192, mobile.Hue,
                                                        newStatus, mobile.X, mobile.Y, mobile.Z, mobile.Direction));
                }
            };

            Task.Run(async() =>
            {
                try
                {
                    GitHubClient client = new GitHubClient(new ProductHeaderValue("ClassicAssist"));

                    IReadOnlyList <Release> releases =
                        await client.Repository.Release.GetAll("Reetus", "ClassicAssist");

                    Release latestRelease = releases.FirstOrDefault();

                    if (latestRelease == null)
                    {
                        return;
                    }

                    Version latestVersion = Version.Parse(latestRelease.TagName);

                    if (!Version.TryParse(
                            FileVersionInfo.GetVersionInfo(Path.Combine(StartupPath, "ClassicAssist.dll"))
                            .ProductVersion, out Version localVersion))
                    {
                        return;
                    }

                    if (latestVersion > localVersion && AssistantOptions.UpdateGumpVersion < latestVersion)
                    {
                        IReadOnlyList <GitHubCommit> commits =
                            await client.Repository.Commit.GetAll("Reetus", "ClassicAssist");

                        IEnumerable <GitHubCommit> latestCommits =
                            commits.OrderByDescending(c => c.Commit.Author.Date).Take(15);

                        StringBuilder commitMessage = new StringBuilder();

                        foreach (GitHubCommit gitHubCommit in latestCommits)
                        {
                            commitMessage.AppendLine($"{gitHubCommit.Commit.Author.Date.Date.ToShortDateString()}:");
                            commitMessage.AppendLine();
                            commitMessage.AppendLine(gitHubCommit.Commit.Message);
                            commitMessage.AppendLine();
                        }

                        StringBuilder message = new StringBuilder();
                        message.AppendLine(Strings.ProductName);
                        message.AppendLine(
                            $"{Strings.New_version_available_} <A HREF=\"https://github.com/Reetus/ClassicAssist/releases/tag/{latestVersion}\">{latestVersion}</A>");
                        message.AppendLine();
                        message.AppendLine(commitMessage.ToString());
                        message.AppendLine(
                            $"<A HREF=\"https://github.com/Reetus/ClassicAssist/commits/master\">{Strings.See_More}</A>");

                        UpdateMessageGump gump = new UpdateMessageGump(_hWnd, message.ToString(), latestVersion);
                        gump.SendGump();
                    }
                }
                catch (Exception)
                {
                    // Squash all
                }
            });

            AbilitiesManager.GetInstance().Enabled = AbilityType.None;
            AbilitiesManager.GetInstance().ResendGump(AbilityType.None);

            Task.Run(async() =>
            {
                await Task.Delay(3000);
                MacroManager.GetInstance().Autostart();
            });
        }
            public void CallsIntoClient()
            {
                var gitHubClient = Substitute.For<IGitHubClient>();
                var releasesClient = new ObservableReleasesClient(gitHubClient);
                var release = new Release("https://uploads.test.dev/does/not/matter/releases/1/assets{?name}");
                var rawData = Substitute.For<Stream>();
                var upload = new ReleaseAssetUpload("example.zip", "application/zip", rawData, null);

                releasesClient.UploadAsset(release, upload);

                gitHubClient.Repository.Release.Received(1).UploadAsset(release, upload);
            }
Ejemplo n.º 58
0
        async Task UpdateFromReleaseAsync(Release pendingUpdateRelease)
        {
            var assets = await client.Release.GetAllAssets(RepositoryOwner, RepositoryName, pendingUpdateRelease.Id);

            await UpdateFromAssetsAsync(assets);
        }
        /// <summary>
        /// Uploads a <see cref="ReleaseAsset"/> for the specified release.
        /// </summary>
        /// <remarks>
        /// See the <a href="http://developer.github.com/v3/repos/releases/#upload-a-release-asset">API documentation</a> for more information.
        /// </remarks>
        /// <param name="release">The <see cref="Release"/> to attach the uploaded asset to</param>
        /// <param name="data">Description of the asset with its data</param>
        /// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
        public IObservable<ReleaseAsset> UploadAsset(Release release, ReleaseAssetUpload data)
        {
            Ensure.ArgumentNotNull(release, "release");
            Ensure.ArgumentNotNull(data, "data");

            return _client.UploadAsset(release, data).ToObservable();
        }
Ejemplo n.º 60
0
 public NewFriendRequestModifier(ClientConnection connection, IPacket packetOriginal, Release releaseFrom, Release releaseTarget) : base(connection, packetOriginal, releaseFrom, releaseTarget)
 {
 }