Exemplo n.º 1
0
        /// <summary>
        /// Queues a work item.
        /// </summary>
        /// <param name="item"></param>
        protected void Enqueue(object item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            // mbr - 07-11-2005 - stop?
            if (this.IsDisposing)
            {
                throw new InvalidOperationException("The queue is being disposed.");
            }

            // lock...
            Lock.AcquireWriterLock(-1);
            try
            {
                // add...
                this.Queue.Enqueue(item);
            }
            finally
            {
                Lock.ReleaseLock();
            }

            // tick now...
            this.Tick();
        }
Exemplo n.º 2
0
        internal static SourceState GetSourceState(string fullyQualifiedReference)
        {
            SourceState sourceState = GetSourceStateFromCache(fullyQualifiedReference);

            if (sourceState == null)
            {
                // Create the source.

                sourceState = CreateSourceState(fullyQualifiedReference);

                // Cache it so that next time it is available.

                Lock.AcquireWriterLock(Timeout.Infinite);
                try
                {
                    SourceStates[fullyQualifiedReference] = sourceState;
                }
                finally
                {
                    Lock.ReleaseWriterLock();
                }
            }

            return(sourceState);
        }
Exemplo n.º 3
0
 void RecalcBar(AggregateBar bar)
 {
     l.Info("RecalcBar " + bar.Number);
     Lock.AcquireWriterLock(1000);
     try
     {
         bar.Clear();
         m_TickBars.Lock.AcquireReaderLock(1000);
         try
         {
             IBar tick = m_TickBars.First;
             while (tick != null)
             {
                 if (TimeAlignment(tick.DT) == bar.DT)
                 {
                     bar.AddTick(tick);
                 }
                 tick = m_TickBars.GetNext(tick);
             }
         }
         finally
         {
             m_TickBars.Lock.ReleaseReaderLock();
         }
     }
     finally
     {
         Lock.ReleaseWriterLock();
     }
 }
Exemplo n.º 4
0
        void m_TickBars_NewBarEvent(object sender, BarsEventArgs e) // TODO возможная оптимизация (слишком часто вызываю TimeAlignment(e.bar.dt))
        {
            if (l.IsDebugEnabled)
            {
                l.Debug(debKey + "m_TickBars_NewBarEvent новый тик " + e.bar);
            }
            Lock.AcquireWriterLock(1000);
            try
            {
                AggregateBar bar = FindBar(e.bar.DT) as AggregateBar;

                if (bar == null)
                {
                    int timeAlignment = TimeAlignment(e.bar.DT);

                    if (l.IsDebugEnabled)
                    {
                        l.Debug(debKey + "m_TickBars_NewBarEvent Создаю новый бар " + DateTime2Int.DateTime(timeAlignment));
                    }

                    bar = new AggregateBar(timeAlignment, timeAlignment + scale.interval - 1, e.bar.Number, e.bar.Close, e.bar.Close, e.bar.Close, e.bar.Close, e.bar.Volume);

                    bars.Add(bar);

                    EventHandler <BarsEventArgs> ev = NewBarEvent;
                    if (ev != null)
                    {
                        ev(this, new BarsEventArgs(this, bar));
                    }
                }
                else
                {
                    l.Debug(debKey + "m_TickBars_NewBarEvent Добавляю тик в бар");

                    if ((m_LastTick != null) &&
                        ((m_LastTick.DT > e.bar.DT) ||
                         ((m_LastTick.DT == e.bar.DT) && (m_LastTick.Number > e.bar.Number))))
                    {
                        l.Debug(debKey + "Тики пришли не по порядку. Пересчитываю весь бар");
                        RecalcBar(bar);
                    }
                    else
                    {
                        bar.AddTick(e.bar);
                    }

                    m_LastTick = e.bar;

                    EventHandler <BarsEventArgs> changeBarEvent = ChangeBarEvent;
                    if (changeBarEvent != null)
                    {
                        changeBarEvent(this, new BarsEventArgs(this, bar));
                    }
                }
            }
            finally
            {
                Lock.ReleaseWriterLock();
            }
        }
Exemplo n.º 5
0
 public void Kill()
 {
     // stop any threads belonging to this
     Lock.AcquireWriterLock(Timeout.Infinite);
     Cancelled     = true;
     StatusMessage = "Cancelling...";
     Lock.ReleaseWriterLock();
 }
Exemplo n.º 6
0
        public bool IsComplete()
        {
            Lock.AcquireWriterLock(Timeout.Infinite);
            bool running = Running;

            Lock.ReleaseWriterLock();
            return(!running);
        }
Exemplo n.º 7
0
 private void CheckForCancel()
 {
     Lock.AcquireWriterLock(Timeout.Infinite);
     _killFlag = Cancelled;
     Lock.ReleaseWriterLock();
     if (_killFlag)
     {
         throw new Exception("Action cancelled...");
     }
 }
Exemplo n.º 8
0
 /// <summary>
 /// Clears the collection.
 /// </summary>
 public void Clear()
 {
     Lock.AcquireWriterLock(-1);
     try
     {
         // mbr - 2010-01-20 - this was wrong...
         //_innerValues = new HybridDictionary();
         _innerValues = this.CreateDictionary();
     }
     finally
     {
         Lock.ReleaseLock();
     }
 }
Exemplo n.º 9
0
        public MediaRefreshReport Report()
        {
            Lock.AcquireWriterLock(Timeout.Infinite);
            var report = new MediaRefreshReport
            {
                Complete      = PercentComplete,
                Succeeded     = Succeeded,
                Processed     = Processed,
                Running       = Running,
                HasRun        = HasRun,
                StatusMessage = StatusMessage,
                Total         = Total
            };

            Lock.ReleaseWriterLock();
            return(report);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Dequeues the given work item.
 /// </summary>
 /// <returns></returns>
 private object Dequeue()
 {
     Lock.AcquireWriterLock(-1);
     try
     {
         if (this.Queue.Count > 0)
         {
             return(this.Queue.Dequeue());
         }
         else
         {
             return(null);
         }
     }
     finally
     {
         Lock.ReleaseLock();
     }
 }
Exemplo n.º 11
0
        public void Add(IDataProvider system, IBar bar)
        {
            Lock.AcquireWriterLock(1000);
            try
            {
                bars.Add(bar);
            }
            finally
            {
                Lock.ReleaseWriterLock();
            }

            EventHandler <BarsEventArgs> e = NewBarEvent;

            if (e != null)
            {
                e(this, new BarsEventArgs(this, bar));
            }
        }
Exemplo n.º 12
0
        public bool RunUpdate(HttpContext context)
        {
            try
            {
                Lock.AcquireWriterLock(Timeout.Infinite);
                Total           = 0;
                Processed       = 0;
                PercentComplete = 0.0;
                Running         = true;
                HasRun          = true;
                Cancelled       = false;
                Succeeded       = false;
                StatusMessage   = "Starting update...";
                _context        = context;
                // Get a new instance of the HoodDbContext for this import.
                var options = new DbContextOptionsBuilder <HoodDbContext>();
                options.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
                Database = new HoodDbContext(options.Options);

                _media = new MediaManager(_env, _config);

                Lock.ReleaseWriterLock();

                ThreadStart pts    = new ThreadStart(RefreshAllMedia);
                Thread      thread = new Thread(pts)
                {
                    Name     = "RefreshAllMedia",
                    Priority = ThreadPriority.Normal
                };
                thread.Start();

                return(true);
            }
            catch (Exception ex)
            {
                Lock.AcquireWriterLock(Timeout.Infinite);
                Running       = false;
                StatusMessage = ex.Message;
                Lock.ReleaseWriterLock();
                return(false);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Clears the temporary folder used for downloading remote data.
        /// </summary>
        private void CleanTempFolder()
        {
            Lock.AcquireWriterLock(Timeout.Infinite);
            StatusMessage = "Cleaning the temporary files folder...";
            Lock.ReleaseWriterLock();

            CheckForCancel();

            if (!Directory.Exists(TempFolder))
            {
                Directory.CreateDirectory(TempFolder);
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(TempFolder);

            FileInfo[] oldFiles = directoryInfo.GetFiles();
            foreach (FileInfo fi in oldFiles)
            {
                // Delete the files in the directory.
                fi.Delete();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// This is the main thread, controls the whole update process.
        /// All other functions are fired of from here and once complete, the update is complete.
        /// </summary>
        private async void RefreshAllMedia()
        {
            try
            {
                // Start by cleaning the temp folder.
                CleanTempFolder();

                var all = Database.Media;

                Lock.AcquireWriterLock(Timeout.Infinite);
                Total = all.Count();
                Lock.ReleaseWriterLock();

                foreach (var media in all)
                {
                    CheckForCancel();
                    try
                    {
                        await _media.RefreshMedia(media, TempFolder);
                    }
                    catch (WebException ex)
                    {
                        StatusMessage = string.Format("Downloading file failed: {0} - {1}", media.Filename, ex.Message);
                    }
                    catch (Exception ex)
                    {
                        StatusMessage = string.Format("Error updating media: {0} -  {1}", media.Filename, ex.Message);
                    }

                    Lock.AcquireWriterLock(Timeout.Infinite);
                    Processed++;
                    PercentComplete = (Processed / Total) * 60;
                    StatusMessage   = string.Format("Processed file: {0}", media.Filename);
                    Lock.ReleaseWriterLock();
                }
                Lock.AcquireWriterLock(Timeout.Infinite);
                PercentComplete = 60;
                StatusMessage   = string.Format("Processed all files, commencing Content updates...");
                Lock.ReleaseWriterLock();

                await Database.SaveChangesAsync();

                // now we need to iterate through any items that may have media attached, and re-attach.
                // content
                // properties
                // app users

                foreach (var content in Database.Content)
                {
                    if (content.FeaturedImage != null)
                    {
                        var media = Database.Media.Find(content.FeaturedImage.Id);
                        content.FeaturedImage = new ContentMedia(media);
                        StatusMessage         = string.Format("Refreshing content featured image: {0} {1}", content.Id, content.Title);
                    }
                }
                await Database.SaveChangesAsync();

                Lock.AcquireWriterLock(Timeout.Infinite);
                PercentComplete = 70;
                StatusMessage   = string.Format("Content updated, commencing Properties updates...");
                Lock.ReleaseWriterLock();

                foreach (var property in Database.Properties)
                {
                    if (property.FeaturedImage != null)
                    {
                        property.FeaturedImage = Database.Media.Find(property.FeaturedImage.Id);
                        StatusMessage          = string.Format("Refreshing property featured image: {0} {1}", property.Id, property.Title);
                    }
                    if (property.InfoDownload != null)
                    {
                        property.FeaturedImage = Database.Media.Find(property.FeaturedImage.Id);
                        StatusMessage          = string.Format("Refreshing property info download: {0} {1}", property.Id, property.Title);
                    }
                }
                await Database.SaveChangesAsync();

                Lock.AcquireWriterLock(Timeout.Infinite);
                PercentComplete = 80;
                StatusMessage   = string.Format("Properties updated, commencing Users updates...");
                Lock.ReleaseWriterLock();

                foreach (var user in Database.Users)
                {
                    if (user.Avatar != null)
                    {
                        user.Avatar   = Database.Media.Find(user.Avatar.Id);
                        StatusMessage = string.Format("Refreshing user avatar: {0} {1}", user.Id, user.ToInternalName());
                    }
                }
                await Database.SaveChangesAsync();

                Lock.AcquireWriterLock(Timeout.Infinite);
                PercentComplete = 90;
                StatusMessage   = string.Format("All done, emailing results...");
                Lock.ReleaseWriterLock();

                MailObject message = new MailObject()
                {
                    PreHeader = "All media files have been refreshed.",
                    Subject   = "All media files have been refreshed."
                };
                message.AddH1("Complete!");
                message.AddParagraph("All media files have been successfully refreshed on " + _context.GetSiteUrl());

                IEmailSender emailSender = Engine.Services.Resolve <IEmailSender>();
                await emailSender.NotifyRoleAsync(message, "SuperUser");

                // Clean the temp directory...
                CleanTempFolder();

                Lock.AcquireWriterLock(Timeout.Infinite);
                PercentComplete = 100;
                Succeeded       = true;
                Running         = false;
                StatusMessage   = "Update completed at " + DateTime.UtcNow.ToShortTimeString() + " on " + DateTime.UtcNow.ToLongDateString() + ".";
                Lock.ReleaseWriterLock();

                return;
            }
            catch (Exception ex)
            {
                Lock.AcquireWriterLock(Timeout.Infinite);
                Running       = false;
                StatusMessage = ex.Message;
                Lock.ReleaseWriterLock();
                return;
            }
        }