예제 #1
0
        public void ManyDays()
        {
            DateTime one = new DateTime(2014, 1, 1);
            DateTime two = new DateTime(2014, 1, 5);
            var      ts  = two - one;
            var      str = TimeSpanFormatter.GetTimeSpanString(ts, 3);

            Assert.AreEqual("4 дня", str);
        }
예제 #2
0
        public void Common()
        {
            DateTime one = new DateTime(2014, 1, 1, 0, 0, 0);
            DateTime two = new DateTime(2014, 1, 3, 6, 5, 0);
            var      ts  = two - one;
            var      str = TimeSpanFormatter.GetTimeSpanString(ts, 3);

            Assert.AreEqual("2 дня 6 ч 5 м", str);
        }
예제 #3
0
        public void LessThanDay()
        {
            DateTime one = new DateTime(2014, 1, 1, 19, 5, 0);
            DateTime two = new DateTime(2014, 1, 2, 15, 6, 0);
            var      ts  = two - one;
            var      str = TimeSpanFormatter.GetTimeSpanString(ts, 3);

            Assert.AreEqual("20 ч 1 м", str);
        }
예제 #4
0
    public static string AxisLabel(TimeSpan timeSpan)
    {
        if (timeSpan <= TransactionFeeHelper.CalculateConfirmationTime(WalletWasabi.Helpers.Constants.FastestConfirmationTarget))
        {
            return("fastest");
        }

        return(TimeSpanFormatter.Format(timeSpan, new TimeSpanFormatter.Configuration("d", "h", "m")));
    }
예제 #5
0
    public static string SliderLabel(TimeSpan timeSpan)
    {
        if (timeSpan <= TransactionFeeHelper.CalculateConfirmationTime(WalletWasabi.Helpers.Constants.FastestConfirmationTarget))
        {
            return("fastest");
        }

        return("~" + TimeSpanFormatter.Format(timeSpan, new TimeSpanFormatter.Configuration(" days", " hours", " minutes")));
    }
예제 #6
0
        public void SameTime()
        {
            DateTime one = new DateTime(2014, 1, 1, 15, 5, 0);
            DateTime two = new DateTime(2014, 1, 3, 15, 5, 0);
            var      ts  = two - one;
            var      str = TimeSpanFormatter.GetTimeSpanString(ts, 3);

            Assert.AreEqual("2 дня 0 ч", str);
        }
예제 #7
0
        public void UpdateList()
        {
            ListView.ListViewItemCollection listViewItemCollection = lvwDownloadTasks.Items;
            for (int i = 0; i < listViewItemCollection.Count; i++)
            {
                ListViewItem item = listViewItemCollection[i];
                if (item == null)
                {
                    return;
                }

                Guid guid = m_DownloadTaskItemMap[item];
                DownloadTaskStatistics downloadTaskStatistics = m_DownloadHelper.GetDownloadTaskStatistics(guid);
                if (downloadTaskStatistics == null)
                {
                    return;
                }

                DownloadTaskState state;

                if (item.Tag == null)
                {
                    state = DownloadTaskState.Working;
                }
                else
                {
                    state = (DownloadTaskState)item.Tag;
                }

                if (state != downloadTaskStatistics.DownloadTaskState ||
                    state == DownloadTaskState.Working ||
                    state == DownloadTaskState.WaitingForReconnect)
                {
                    item.SubItems[1].Text = ByteFormatter.ToString(downloadTaskStatistics.FileSize);
                    item.SubItems[2].Text = ByteFormatter.ToString(downloadTaskStatistics.TransferedDownload);
                    item.SubItems[3].Text = GetDownloadProgressText(downloadTaskStatistics);
                    item.SubItems[4].Text = TimeSpanFormatter.ToString(downloadTaskStatistics.RemainingTime);
                    item.SubItems[5].Text = GetDownloadRateText(downloadTaskStatistics);
                    item.SubItems[6].Text = GetAverageDownloadRateText(downloadTaskStatistics);

                    if (!string.IsNullOrWhiteSpace(downloadTaskStatistics.LastError))
                    {
                        item.SubItems[8].Text = string.Format(CultureInfo.CurrentCulture, "{0}, {1}", downloadTaskStatistics.DownloadTaskState, downloadTaskStatistics.LastError);
                    }
                    else
                    {
                        item.SubItems[8].Text = string.IsNullOrEmpty(downloadTaskStatistics.StatusMessage) ? downloadTaskStatistics.DownloadTaskState.ToString() : string.Format(CultureInfo.CurrentCulture, "{0}, {1}", downloadTaskStatistics.DownloadTaskState, downloadTaskStatistics.StatusMessage);
                    }

                    item.SubItems[9].Text  = GetResumeText(downloadTaskStatistics);
                    item.SubItems[10].Text = downloadTaskStatistics.FileUri.OriginalString;
                    item.Tag = downloadTaskStatistics.DownloadTaskState;
                }
            }

            UpdateSegments();
        }
 public void Format_Days_ReturnsCorrectValue()
 {
     var f = new TimeSpanFormatter();
     var span = new TimeSpan(1, 7, 3, 2);
     Assert.AreEqual("01", string.Format(f, "{0:DD}", span));
     Assert.AreEqual("1", string.Format(f, "{0:D}", span));
     Assert.AreEqual("1 07", string.Format(f, "{0:D hh}", span));
     Assert.AreEqual("01 07 03 02", string.Format(f, "{0:DD hh mm ss}", span));
 }
예제 #9
0
        public void Format_Days_ReturnsCorrectValue()
        {
            var f    = new TimeSpanFormatter();
            var span = new TimeSpan(1, 7, 3, 2);

            Assert.AreEqual("01", string.Format(f, "{0:DD}", span));
            Assert.AreEqual("1", string.Format(f, "{0:D}", span));
            Assert.AreEqual("1 07", string.Format(f, "{0:D hh}", span));
            Assert.AreEqual("01 07 03 02", string.Format(f, "{0:DD hh mm ss}", span));
        }
예제 #10
0
        public void BasicTest()
        {
            ITextFormatter <TimeSpan> formatter = new TimeSpanFormatter();

            Assert.Equal("1 hour, 0 minutes, 0 seconds", formatter.WriteToString(TimeSpan.FromHours(1)));
            Assert.Equal("1 hour, 5 minutes, 1 second", formatter.WriteToString(new TimeSpan(1, 5, 1)));
            Assert.Equal("6 days, 1 hour, 5 minutes, 1 second", formatter.WriteToString(new TimeSpan(6, 1, 5, 1)));
            Assert.Equal("1 week, 1 day, 1 hour, 5 minutes, 1 second", formatter.WriteToString(new TimeSpan(8, 1, 5, 1)));
            Assert.Equal("2 weeks, 1 day, 1 hour, 5 minutes, 1 second", formatter.WriteToString(new TimeSpan(15, 1, 5, 1)));
        }
 public static string ToString(this TimeSpan timeSpan, string format, ICustomFormatter formatter)
 {
     if (formatter == null)
     {
         throw new ArgumentNullException();
     }
     TimeSpanFormatter tsFormatter = (TimeSpanFormatter)formatter;
     format = Regex.Replace(format, CustomFormatsRegex, new MatchEvaluator(m => MatchReplacer(m, timeSpan, tsFormatter)));
     return timeSpan.ToString(format);
 }
예제 #12
0
        public void BasicLocalizationTest()
        {
            var formatter = new TimeSpanFormatter(TimeLocalization.Create("de"));

            // ReSharper disable StringLiteralTypo
            Assert.Equal("1 Stunde, 0 Minuten, 0 Sekunden", formatter.WriteToString(TimeSpan.FromHours(1)));
            Assert.Equal("1 Stunde, 5 Minuten, 1 Sekunde", formatter.WriteToString(new TimeSpan(1, 5, 1)));
            Assert.Equal("6 Tage, 1 Stunde, 5 Minuten, 1 Sekunde", formatter.WriteToString(new TimeSpan(6, 1, 5, 1)));
            Assert.Equal("1 Woche, 1 Tag, 1 Stunde, 5 Minuten, 1 Sekunde", formatter.WriteToString(new TimeSpan(8, 1, 5, 1)));
            Assert.Equal("2 Wochen, 1 Tag, 1 Stunde, 5 Minuten, 1 Sekunde", formatter.WriteToString(new TimeSpan(15, 1, 5, 1)));
            // ReSharper restore StringLiteralTypo
        }
예제 #13
0
        private void AddDownload(Downloader d)
        {
            d.RestartingSegment += new EventHandler <SegmentEventArgs>(download_RestartingSegment);
            d.SegmentStoped     += new EventHandler <SegmentEventArgs>(download_SegmentEnded);
            d.SegmentFailed     += new EventHandler <SegmentEventArgs>(download_SegmentFailed);
            d.SegmentStarted    += new EventHandler <SegmentEventArgs>(download_SegmentStarted);
            d.InfoReceived      += new EventHandler(download_InfoReceived);
            d.SegmentStarting   += new EventHandler <SegmentEventArgs>(Downloader_SegmentStarting);

            string ext = Path.GetExtension(d.LocalFile);

            ListViewItem item = new ListViewItem();

            //ListViewItem.ListViewSubItem subItem;

            item.ImageIndex = FileTypeImageList.GetImageIndexByExtention(ext);
            //lvwDownloads.Columns["columnFile"].ImageIndex = FileTypeImageList.GetImageIndexByExtention(ext);
            //lvwDownloads.Columns[1].ImageIndex = FileTypeImageList.GetImageIndexByExtention(ext);

            //item.Text = Path.GetFileName(d.LocalFile);
            //item.Text = d.Id.ToString();
            item.Text = (d.OrderedIndex + 1).ToString();

            // Id
            item.SubItems.Add(d.Id.ToString());
            //File
            item.SubItems.Add(Path.GetFileName(d.LocalFile));
            // size
            item.SubItems.Add(ByteFormatter.ToString(d.FileSize));
            // completed
            item.SubItems.Add(ByteFormatter.ToString(d.Transfered));
            // progress
            item.SubItems.Add(String.Format("{0:0.##}%", d.Progress));
            // left
            item.SubItems.Add(TimeSpanFormatter.ToString(d.Left));
            // rate
            item.SubItems.Add("0");
            // added
            item.SubItems.Add(d.CreatedDateTime.ToShortDateString() + " " + d.CreatedDateTime.ToShortTimeString());
            // state
            item.SubItems.Add(d.State.ToString());
            // resume
            item.SubItems.Add(GetResumeStr(d));
            // url
            item.SubItems.Add(d.ResourceLocation.URL);

            //mapDownloadToItem[d] = item;
            //mapItemToDownload[item] = d;

            lvwDownloads.Items.Add(item);
        }
예제 #14
0
        public TestResultSummaryViewModel(TestSummaryItem summaryItem, PipelineConfiguration pipelineConfiguration, bool includeOthersInTotal)
        {
            PassedTests = summaryItem.GetPassedTestsCount();
            FailedTests = summaryItem.GetFailedTestsCount();
            OtherTests  = summaryItem.GetOtherTestsCount();

            TotalTests = TestResultsHelper.GetTotalTestCountBasedOnUserConfiguration(summaryItem.TestCountByOutCome,
                                                                                     includeOthersInTotal);

            PassingRate = TestResultsHelper.GetTestOutcomePercentageString(PassedTests, TotalTests);

            Duration = TimeSpanFormatter.FormatDurationWithUnit(summaryItem.Duration);

            Url = pipelineConfiguration.TestTabLink;
        }
예제 #15
0
        public void TimeSpanFormatterTests()
        {
            Assert.AreEqual("01:02:03", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3), FormatVerbosities.SuperBrief, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
            Assert.AreEqual("01:02:03.123", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3) + TimeSpan.FromMilliseconds(123), FormatVerbosities.SuperBrief, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
            Assert.AreEqual("2.04:02:03.456", TimeSpanFormatter.Format(new TimeSpan(4, 2, 3) + TimeSpan.FromDays(2) + TimeSpan.FromMilliseconds(456), FormatVerbosities.SuperBrief, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));

            Assert.AreEqual("1h2m3s", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3), FormatVerbosities.Brief, unitSpacer: false, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
            Assert.AreEqual("1 h 2 m 3 s", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3), FormatVerbosities.Brief, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
            Assert.AreEqual("1 h 2 m 3.456 s", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3) + TimeSpan.FromMilliseconds(456), FormatVerbosities.Brief, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));

            Assert.AreEqual("1 hour 2 min 3 sec", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3), FormatVerbosities.Normal, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
            Assert.AreEqual("1 hour 2 min 3.456 sec", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3) + TimeSpan.FromMilliseconds(456), FormatVerbosities.Normal, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));

            Assert.AreEqual("1 hour 2 minutes 3 seconds", TimeSpanFormatter.Format(new TimeSpan(1, 2, 3), FormatVerbosities.Verbose, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));

            Assert.AreEqual("2 days 4 hours 2 minutes 3.456 seconds", TimeSpanFormatter.Format(new TimeSpan(4, 2, 3) + TimeSpan.FromDays(2) + TimeSpan.FromMilliseconds(456), FormatVerbosities.Verbose, unitSpacer: true, numberFormatCulture: System.Globalization.CultureInfo.InvariantCulture));
        }
예제 #16
0
        private void UpdateSegmentsWithoutInsert(SegmentDownloaderInfoCollection segmentDownloaderInfoCollection)
        {
            for (int i = 0; i < segmentDownloaderInfoCollection.Count; i++)
            {
                ISegmentDownloaderInfo segmentDownloaderInfo = segmentDownloaderInfoCollection[i];
                ListViewItem           listViewItem          = lvwDownloadTaskSegments.Items[i];
                listViewItem.SubItems[0].Text = string.Format("{0:0.##}%", segmentDownloaderInfo.DownloadProgress);
                listViewItem.SubItems[1].Text = ByteFormatter.ToString(segmentDownloaderInfo.TransferedDownload);
                listViewItem.SubItems[2].Text = ByteFormatter.ToString(segmentDownloaderInfo.EndPosition - segmentDownloaderInfo.StartPosition);
                listViewItem.SubItems[3].Text = ByteFormatter.ToString(segmentDownloaderInfo.StartPosition);
                listViewItem.SubItems[4].Text = ByteFormatter.ToString(segmentDownloaderInfo.EndPosition);
                listViewItem.SubItems[5].Text = string.Format("{0:0.##}", segmentDownloaderInfo.DownloadRate / 1024.0);
                listViewItem.SubItems[6].Text = TimeSpanFormatter.ToString(segmentDownloaderInfo.RemainingTime);
                listViewItem.SubItems[7].Text = segmentDownloaderInfo.LastException != null?string.Format(CultureInfo.CurrentCulture, "{0}, {1}", segmentDownloaderInfo.State, segmentDownloaderInfo.LastException.Message) : segmentDownloaderInfo.State.ToString();

                listViewItem.SubItems[8].Text = segmentDownloaderInfo.Uri.OriginalString;
            }
        }
예제 #17
0
 private void Fill(Segment s)
 {
     CurrentTry           = s.CurrentTry;
     Progress             = String.Format("{0:0.##}%", s.Progress);
     ProgressInt          = (int)s.Progress;
     Transferred          = ByteFormatter.ToString(s.Transfered);
     TotalToTransfer      = ByteFormatter.ToString(s.TotalToTransfer);
     InitialStartPosition = ByteFormatter.ToString(s.InitialStartPosition);
     EndPosition          = ByteFormatter.ToString(s.EndPosition);
     TransferRate         = TransferRateFormatter.ToString(s.Rate);
     TimeLeft             = TimeSpanFormatter.ToString(s.Left);
     if (s.LastError != null)
     {
         StateMessage = s.State.ToString() + ", " + s.LastError.Message;
     }
     else
     {
         StateMessage = s.State.ToString();
     }
     CurrentUrl = s.CurrentURL;
 }
예제 #18
0
        void Fill(Downloader d)
        {
            FileName = System.IO.Path.GetFileName(d.LocalFile);
            // size
            FileSize = ByteFormatter.ToString(d.FileSize);
            // completed
            Transferred = ByteFormatter.ToString(d.Transfered);
            // progress
            Progress = String.Format("{0:0.##}%", d.Progress);
            // left
            TimeLeft = TimeSpanFormatter.ToString(d.Left);
            // rate
            TransferRate = String.Format("{0:0.##}", d.Rate / 1024.0);
            // added
            DateAdded = d.CreatedDateTime.ToShortDateString() + " " + d.CreatedDateTime.ToShortTimeString();
            // resume
            SupportsResume = DownloadList.GetResumeStr(d);
            // url
            Url = d.ResourceLocation.URL;

            SaveTo = d.LocalFile;

            if (d.LastError != null)
            {
                StateMessage = d.State.ToString() + ", " + d.LastError.Message;
            }
            else
            {
                if (String.IsNullOrEmpty(d.StatusMessage))
                {
                    StateMessage = d.State.ToString();
                }
                else
                {
                    StateMessage = d.State.ToString() + ", " + d.StatusMessage;
                }
            }

            Tag = d.State;
        }
        private void InitializeDuration(List <TaskData> tasks)
        {
            if (tasks.Count == 1)
            {
                var firstTask = tasks.First();
                if (firstTask.FinishTime.HasValue && firstTask.StartTime.HasValue)
                {
                    Duration = TimeSpanFormatter.FormatDuration(firstTask.FinishTime.Value.Subtract(firstTask.StartTime.Value),
                                                                true);
                }
            }
            else if (tasks.Any(t => t.FinishTime.HasValue && t.StartTime.HasValue))
            {
                var minTime = tasks.Where(t => t.FinishTime.HasValue && t.StartTime.HasValue).Min(t => t.FinishTime.Value.Subtract(t.StartTime.Value));
                var maxTime = tasks.Where(t => t.FinishTime.HasValue && t.StartTime.HasValue).Max(t => t.FinishTime.Value.Subtract(t.StartTime.Value));

                if (minTime != null && maxTime != null)
                {
                    Duration = $"{TimeSpanFormatter.FormatDuration(minTime, false)} - {TimeSpanFormatter.FormatDuration(maxTime, false)}";
                }
            }
        }
 private static string MatchReplacer(Match m, TimeSpan timeSpan, TimeSpanFormatter formatter)
 {
     string input;
     // the matched non-'\' char before the stuff we actually care about
     string firstChar = m.Groups[1].Success ? m.Groups[1].Value : string.Empty;
     
     if (m.Groups[4].Success)
     {
         // has additional formatting
         input = string.Format("{0},{1}", m.Groups[2].Value, m.Groups[4].Value);
     }
     else
     {
         input = m.Groups[2].Value;
     }
     string replacement = formatter.Format(input, timeSpan, formatter);
     if (string.IsNullOrEmpty(replacement))
     {
         return firstChar;
     }
     return string.Format("{0}\\{1}", firstChar, string.Join("\\", replacement.ToCharArray()));
 }
예제 #21
0
        private void UpdateSegmentsInserting(ListViewItem newSelection, SegmentDownloaderInfoCollection segmentDownloaderInfoCollection)
        {
            m_LastDownloadTaskSelection = newSelection;

            lvwDownloadTaskSegments.Items.Clear();

            for (int i = 0; i < segmentDownloaderInfoCollection.Count; i++)
            {
                ListViewItem item = new ListViewItem();

                ISegmentDownloaderInfo segmentDownloaderInfo = segmentDownloaderInfoCollection[i];
                item.Text = string.Format("{0:0.##}%", segmentDownloaderInfo.DownloadProgress);
                item.SubItems.Add(ByteFormatter.ToString(segmentDownloaderInfo.TransferedDownload));
                item.SubItems.Add(ByteFormatter.ToString(segmentDownloaderInfo.EndPosition - segmentDownloaderInfo.StartPosition));
                item.SubItems.Add(ByteFormatter.ToString(segmentDownloaderInfo.StartPosition));
                item.SubItems.Add(ByteFormatter.ToString(segmentDownloaderInfo.EndPosition));
                item.SubItems.Add(string.Format("{0:0.##}", segmentDownloaderInfo.DownloadRate / 1024.0));
                item.SubItems.Add(TimeSpanFormatter.ToString(segmentDownloaderInfo.RemainingTime));
                item.SubItems.Add(segmentDownloaderInfo.State.ToString());
                item.SubItems.Add(segmentDownloaderInfo.Uri.OriginalString);

                lvwDownloadTaskSegments.Items.Add(item);
            }
        }
예제 #22
0
 public static FormatterBase Create(string format)
 {
     if (TimeSpanFormatter.CanFormat(format))
     {
         return(new TimeSpanFormatter(format));
     }
     if (TimeStampFormatter.CanFormat(format))
     {
         return(new TimeStampFormatter(format));
     }
     if (DecibelFormatter.CanFormat(format))
     {
         return(new DecibelFormatter(format));
     }
     if (FloatFormatter.CanFormat(format))
     {
         return(new FloatFormatter(format));
     }
     if (IntegerFormatter.CanFormat(format))
     {
         return(new IntegerFormatter(format));
     }
     return(new StringFormatter(format));
 }
예제 #23
0
        /// <summary>
        /// Updates the 'State' of the filesystem associated with the 'FilesystemDelete' <see cref="ServiceLock"/> item
        /// </summary>
        /// <param name="item"></param>
        /// <param name="fs"></param>
        private static void UpdateState(Model.ServiceLock item, ServerFilesystemInfo fs)
        {
            FilesystemState state = null;

            if (item.State != null && item.State.DocumentElement != null)
            {
                //load from datatabase
                state = XmlUtils.Deserialize <FilesystemState>(item.State.DocumentElement);
            }

            if (state == null)
            {
                state = new FilesystemState();
            }

            if (fs.AboveHighWatermark)
            {
                // we don't want to generate alert if the filesystem is offline or not accessible.
                if (fs.Online && (fs.Readable || fs.Writeable))
                {
                    TimeSpan ALERT_INTERVAL = TimeSpan.FromMinutes(ServiceLockSettings.Default.HighWatermarkAlertInterval);

                    if (state.AboveHighWatermarkTimestamp == null)
                    {
                        state.AboveHighWatermarkTimestamp = Platform.Time;
                    }

                    TimeSpan elapse = (state.LastHighWatermarkAlertTimestamp != null) ? Platform.Time - state.LastHighWatermarkAlertTimestamp.Value : Platform.Time - state.AboveHighWatermarkTimestamp.Value;

                    if (elapse.Duration() >= ALERT_INTERVAL)
                    {
                        ServerPlatform.Alert(AlertCategory.System, AlertLevel.Warning, "Filesystem",
                                             AlertTypeCodes.LowResources, null, TimeSpan.Zero,
                                             SR.AlertFilesystemAboveHW,
                                             fs.Filesystem.Description,
                                             TimeSpanFormatter.Format(Platform.Time - state.AboveHighWatermarkTimestamp.Value, true));


                        state.LastHighWatermarkAlertTimestamp = Platform.Time;
                    }
                }
                else
                {
                    state.AboveHighWatermarkTimestamp     = null;
                    state.LastHighWatermarkAlertTimestamp = null;
                }
            }
            else
            {
                state.AboveHighWatermarkTimestamp     = null;
                state.LastHighWatermarkAlertTimestamp = null;
            }


            XmlDocument stateXml = new XmlDocument();

            stateXml.AppendChild(stateXml.ImportNode(XmlUtils.Serialize(state), true));

            IPersistentStore store = PersistentStoreRegistry.GetDefaultStore();

            using (IUpdateContext ctx = store.OpenUpdateContext(UpdateContextSyncMode.Flush))
            {
                ServiceLockUpdateColumns columns = new ServiceLockUpdateColumns();
                columns.State = stateXml;

                IServiceLockEntityBroker broker = ctx.GetBroker <IServiceLockEntityBroker>();
                broker.Update(item.GetKey(), columns);
                ctx.Commit();
            }
        }
예제 #24
0
        public void UpdateList()
        {
            lvwDownloads.BeginUpdate();

            for (int i = 0; i < lvwDownloads.Items.Count; i++)
            {
                ListViewItem item = lvwDownloads.Items[i];
                if (item == null)
                {
                    return;
                }
                Downloader d = mapItemToDownload[item] as Downloader;
                if (d == null)
                {
                    return;
                }

                DownloaderState state;

                if (item.Tag == null)
                {
                    state = DownloaderState.Working;
                }
                else
                {
                    state = (DownloaderState)item.Tag;
                }

                if (state != d.State ||
                    state == DownloaderState.Working ||
                    state == DownloaderState.WaitingForReconnect)
                {
                    item.SubItems[0].Text = d.FileName;
                    item.SubItems[1].Text = ByteFormatter.ToString(d.FileSize);
                    item.SubItems[2].Text = ByteFormatter.ToString(d.Transfered);
                    item.SubItems[3].Text = String.Format("{0:0.##}%", d.Progress);
                    item.SubItems[4].Text = TimeSpanFormatter.ToString(d.Left);
                    item.SubItems[5].Text = String.Format("{0:0.##}", d.Rate / 1024.0);

                    if (d.LastError != null)
                    {
                        item.SubItems[7].Text = d.ScheduleState.ToString() + ", " + d.LastError.Message;
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(d.StatusMessage))
                        {
                            item.SubItems[7].Text = d.ScheduleState.ToString();
                        }
                        else
                        {
                            item.SubItems[7].Text = d.ScheduleState.ToString() + ", " + d.StatusMessage;
                        }
                    }

                    item.SubItems[8].Text = GetResumeStr(d);
                    item.SubItems[9].Text = d.ResourceLocation.URL;
                    item.Tag = d.State;
                }
            }

            UpdateSegments();
            lvwDownloads.EndUpdate();
        }
예제 #25
0
        /// <summary>
        /// Migrates the study to new tier
        /// </summary>
        /// <param name="storage"></param>
        /// <param name="newFilesystem"></param>
        private void DoMigrateStudy(StudyStorageLocation storage, ServerFilesystemInfo newFilesystem)
        {
            Platform.CheckForNullReference(storage, "storage");
            Platform.CheckForNullReference(newFilesystem, "newFilesystem");

            TierMigrationStatistics stat = new TierMigrationStatistics {
                StudyInstanceUid = storage.StudyInstanceUid
            };

            stat.ProcessSpeed.Start();
            StudyXml studyXml = storage.LoadStudyXml();

            stat.StudySize = (ulong)studyXml.GetStudySize();

            Platform.Log(LogLevel.Info, "About to migrate study {0} from {1} to {2}",
                         storage.StudyInstanceUid, storage.FilesystemTierEnum, newFilesystem.Filesystem.Description);

            string   newPath            = Path.Combine(newFilesystem.Filesystem.FilesystemPath, storage.PartitionFolder);
            DateTime startTime          = Platform.Time;
            DateTime lastLog            = Platform.Time;
            int      fileCounter        = 0;
            ulong    bytesCopied        = 0;
            long     instanceCountInXml = studyXml.NumberOfStudyRelatedInstances;

            using (ServerCommandProcessor processor = new ServerCommandProcessor("Migrate Study"))
            {
                TierMigrationContext context = new TierMigrationContext
                {
                    OriginalStudyLocation = storage,
                    Destination           = newFilesystem
                };

                // The multiple CreateDirectoryCommands are done so that rollback of the directories being created happens properly if either of the directories already exist.
                var origFolder = context.OriginalStudyLocation.GetStudyPath();
                processor.AddCommand(new CreateDirectoryCommand(newPath));

                newPath = Path.Combine(newPath, context.OriginalStudyLocation.StudyFolder);
                processor.AddCommand(new CreateDirectoryCommand(newPath));

                newPath = Path.Combine(newPath, context.OriginalStudyLocation.StudyInstanceUid);
                // don't create this directory so that it won't be backed up by MoveDirectoryCommand

                var copyDirCommand = new CopyDirectoryCommand(origFolder, newPath,
                                                              delegate(string path)
                {
                    // Update the progress. This is useful if the migration takes long time to complete.

                    FileInfo file = new FileInfo(path);
                    bytesCopied  += (ulong)file.Length;
                    fileCounter++;
                    if (file.Extension != null && file.Extension.Equals(ServerPlatform.DicomFileExtension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        TimeSpan elapsed          = Platform.Time - lastLog;
                        TimeSpan totalElapsed     = Platform.Time - startTime;
                        double speedInMBPerSecond = 0;
                        if (totalElapsed.TotalSeconds > 0)
                        {
                            speedInMBPerSecond = (bytesCopied / 1024f / 1024f) / totalElapsed.TotalSeconds;
                        }

                        if (elapsed > TimeSpan.FromSeconds(WorkQueueSettings.Instance.TierMigrationProgressUpdateInSeconds))
                        {
                            #region Log Progress

                            StringBuilder stats = new StringBuilder();
                            if (instanceCountInXml != 0)
                            {
                                float pct = (float)fileCounter / instanceCountInXml;
                                stats.AppendFormat("{0} files moved [{1:0.0}MB] since {2} ({3:0}% completed). Speed={4:0.00}MB/s",
                                                   fileCounter, bytesCopied / 1024f / 1024f, startTime, pct * 100, speedInMBPerSecond);
                            }
                            else
                            {
                                stats.AppendFormat("{0} files moved [{1:0.0}MB] since {2}. Speed={3:0.00}MB/s",
                                                   fileCounter, bytesCopied / 1024f / 1024f, startTime, speedInMBPerSecond);
                            }

                            Platform.Log(LogLevel.Info, "Tier migration for study {0}: {1}", storage.StudyInstanceUid, stats.ToString());
                            try
                            {
                                using (IUpdateContext ctx = PersistentStoreRegistry.GetDefaultStore().OpenUpdateContext(UpdateContextSyncMode.Flush))
                                {
                                    IWorkQueueEntityBroker broker     = ctx.GetBroker <IWorkQueueEntityBroker>();
                                    WorkQueueUpdateColumns parameters = new WorkQueueUpdateColumns
                                    {
                                        FailureDescription = stats.ToString()
                                    };
                                    broker.Update(WorkQueueItem.GetKey(), parameters);
                                    ctx.Commit();
                                }
                            }
                            catch
                            {
                                // can't log the progress so far... just ignore it
                            }
                            finally
                            {
                                lastLog = DateTime.Now;
                            }
                            #endregion
                        }
                    }
                });
                processor.AddCommand(copyDirCommand);

                DeleteDirectoryCommand delDirCommand = new DeleteDirectoryCommand(origFolder, false)
                {
                    RequiresRollback = false
                };
                processor.AddCommand(delDirCommand);

                TierMigrateDatabaseUpdateCommand updateDbCommand = new TierMigrateDatabaseUpdateCommand(context);
                processor.AddCommand(updateDbCommand);

                Platform.Log(LogLevel.Info, "Start migrating study {0}.. expecting {1} to be moved", storage.StudyInstanceUid, ByteCountFormatter.Format(stat.StudySize));
                if (!processor.Execute())
                {
                    if (processor.FailureException != null)
                    {
                        throw processor.FailureException;
                    }
                    throw new ApplicationException(processor.FailureReason);
                }

                stat.DBUpdate      = updateDbCommand.Statistics;
                stat.CopyFiles     = copyDirCommand.CopySpeed;
                stat.DeleteDirTime = delDirCommand.Statistics;
            }

            stat.ProcessSpeed.SetData(bytesCopied);
            stat.ProcessSpeed.End();

            Platform.Log(LogLevel.Info, "Successfully migrated study {0} from {1} to {2} in {3} [ {4} files, {5} @ {6}, DB Update={7}, Remove Dir={8}]",
                         storage.StudyInstanceUid,
                         storage.FilesystemTierEnum,
                         newFilesystem.Filesystem.FilesystemTierEnum,
                         TimeSpanFormatter.Format(stat.ProcessSpeed.ElapsedTime),
                         fileCounter,
                         ByteCountFormatter.Format(bytesCopied),
                         stat.CopyFiles.FormattedValue,
                         stat.DBUpdate.FormattedValue,
                         stat.DeleteDirTime.FormattedValue);

            string originalPath = storage.GetStudyPath();

            if (Directory.Exists(storage.GetStudyPath()))
            {
                Platform.Log(LogLevel.Info, "Original study folder could not be deleted. It must be cleaned up manually: {0}", originalPath);
                ServerPlatform.Alert(AlertCategory.Application, AlertLevel.Warning, WorkQueueItem.WorkQueueTypeEnum.ToString(), 1000, GetWorkQueueContextData(WorkQueueItem), TimeSpan.Zero,
                                     "Study has been migrated to a new tier. Original study folder must be cleaned up manually: {0}", originalPath);
            }

            UpdateAverageStatistics(stat);
        }
예제 #26
0
 public void Setup()
 {
     _formatter = new TimeSpanFormatter(UnitsOfTime.All);
 }
예제 #27
0
        private static void RetrieveImages(string serverAE, string studyPath)
        {
            Console.WriteLine("server={0}", serverAE);
            string          baseUri         = String.Format("http://{0}:{1}", serverHost, serverPort);
            StreamingClient client          = new StreamingClient(new Uri(baseUri));
            int             totalFrameCount = 0;

            DirectoryInfo directoryInfo = new DirectoryInfo(studyPath);
            string        studyUid      = directoryInfo.Name;

            RateStatistics        frameRate    = new RateStatistics("Speed", "frame");
            RateStatistics        speed        = new RateStatistics("Speed", RateType.BYTES);
            AverageRateStatistics averageSpeed = new AverageRateStatistics(RateType.BYTES);
            ByteCountStatistics   totalSize    = new ByteCountStatistics("Size");

            frameRate.Start();
            speed.Start();

            Console.WriteLine("\n------------------------------------------------------------------------------------------------------------------------");

            string[] seriesDirs = Directory.GetDirectories(studyPath);
            foreach (string seriesPath in seriesDirs)
            {
                DirectoryInfo dirInfo       = new DirectoryInfo(seriesPath);
                string        seriesUid     = dirInfo.Name;
                string[]      objectUidPath = Directory.GetFiles(seriesPath, "*.dcm");

                foreach (string uidPath in objectUidPath)
                {
                    FileInfo fileInfo = new FileInfo(uidPath);
                    string   uid      = fileInfo.Name.Replace(".dcm", "");
                    Console.Write("{0,-64}... ", uid);

                    try
                    {
                        Stream imageStream;
                        StreamingResultMetaData      imageMetaData;
                        FrameStreamingResultMetaData frameMetaData;

                        switch (type)
                        {
                        case ContentTypes.Dicom:
                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 dicom sop [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;

                        case ContentTypes.RawPixel:
                            TimeSpanStatistics elapsedTime = new TimeSpanStatistics();
                            elapsedTime.Start();
                            ulong instanceSize = 0;
                            int   frameCount   = 0;
                            do
                            {
                                RetrievePixelDataResult result = client.RetrievePixelData(serverAE, studyUid, seriesUid, uid, frameCount);
                                frameMetaData = result.MetaData;
                                totalFrameCount++;
                                frameCount++;
                                averageSpeed.AddSample(frameMetaData.Speed);
                                totalSize.Value += (ulong)frameMetaData.ContentLength;
                                instanceSize    += (ulong)frameMetaData.ContentLength;
                            } while (!frameMetaData.IsLast);

                            elapsedTime.End();
                            Console.WriteLine("{0,3} frame(s) [{1,10}] in {2,12}\t[mime={3}]", frameCount, ByteCountFormatter.Format(instanceSize), elapsedTime.FormattedValue, frameMetaData.ResponseMimeType);
                            break;

                        default:

                            imageStream = client.RetrieveImage(serverAE, studyUid, seriesUid, uid, out imageMetaData);
                            totalFrameCount++;
                            averageSpeed.AddSample(imageMetaData.Speed);
                            totalSize.Value += (ulong)imageMetaData.ContentLength;

                            Console.WriteLine("1 object [{0,10}] in {1,12}\t[mime={2}]", ByteCountFormatter.Format((ulong)imageStream.Length), TimeSpanFormatter.Format(imageMetaData.Speed.ElapsedTime), imageMetaData.ResponseMimeType);

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebException)
                        {
                            HttpWebResponse rsp = ((ex as WebException).Response as HttpWebResponse);

                            string msg = String.Format("Error: {0} : {1}", rsp.StatusCode, HttpUtility.HtmlDecode(rsp.StatusDescription)
                                                       );
                            Console.WriteLine(msg);
                        }
                        else
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            frameRate.SetData(totalFrameCount);
            frameRate.End();
            speed.SetData(totalSize.Value);
            speed.End();


            Console.WriteLine("\nTotal {0,3} image(s)/frame(s) [{1,10}] in {2,12}   ==>  [ Speed: {3,12} or {4,12}]",
                              totalFrameCount, totalSize.FormattedValue,
                              TimeSpanFormatter.Format(frameRate.ElapsedTime),
                              frameRate.FormattedValue,
                              speed.FormattedValue
                              );
        }
예제 #28
0
        public void UpdateList(bool all = true)
        {
            for (int i = 0; i < lvwDownloads.Items.Count; i++)
            {
                ListViewItem item = lvwDownloads.Items[i];
                if (item == null)
                {
                    return;
                }
                //Downloader d = mapItemToDownload[item] as Downloader;
                Downloader d = DownloadManager.Instance.GetOrderedDownloader(item.Index);
                if (d == null)
                {
                    return;
                }

                DownloaderState state;

                if (item.Tag == null)
                {
                    state = DownloaderState.Working;
                }
                else
                {
                    state = (DownloaderState)item.Tag;
                }

                if (all || state != d.State || state == DownloaderState.Working || state == DownloaderState.WaitingForReconnect)
                {
                    item.Text = (d.OrderedIndex + 1).ToString();
                    int indexColumnSize = 3;
                    int indexColumn     = indexColumnSize;
                    item.SubItems[indexColumn++].Text = ByteFormatter.ToString(d.FileSize);
                    item.SubItems[indexColumn++].Text = ByteFormatter.ToString(d.Transfered);
                    item.SubItems[indexColumn++].Text = String.Format("{0:0.##}%", d.Progress);
                    item.SubItems[indexColumn++].Text = TimeSpanFormatter.ToString(d.Left);
                    item.SubItems[indexColumn++].Text = String.Format("{0:0.##}", d.Rate / 1024.0);
                    indexColumn++; // column Added
                    if (d.LastError != null)
                    {
                        item.SubItems[indexColumn].Text = d.State.ToString() + ", " + d.LastError.Message;
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(d.StatusMessage))
                        {
                            item.SubItems[indexColumn].Text = d.State.ToString();
                        }
                        else
                        {
                            item.SubItems[indexColumn].Text = d.State.ToString() + ", " + d.StatusMessage;
                        }
                    }
                    indexColumn++; // column State

                    item.SubItems[indexColumn++].Text = GetResumeStr(d);
                    item.SubItems[indexColumn++].Text = d.ResourceLocation.URL;
                    item.Tag = d.State;
                }
            }

            UpdateSegments();
        }