/// <summary>
		/// 默认构造函数
		/// </summary>
		public SystemPrivilegeBase()
		{
			_privilege_id = 0; 
			_operation_id =  null; 
			_resources_id =  null; 
			_privilegecnname = String.Empty; 
			_privilegeenname = String.Empty; 
			_defaultvalue = String.Empty; 
			_description = String.Empty; 
			_privilegeorder = 0; 
		}
        private void RetrieveFrame(Frame frame)
        {
            if (_stopAllActivity)
            {
                return;
            }

            try
            {
                //just return if the available memory is getting low - only retrieve and decompress on-demand now.
                if (SystemResources.GetAvailableMemory(SizeUnits.Megabytes) < Prefetch.Default.AvailableMemoryLimitMegabytes)
                {
                    return;
                }

                Interlocked.Increment(ref _activeRetrieveThreads);

                //TODO (CR May 2010): do we need to do this all the time?
                string message = String.Format("Retrieving Frame (active threads: {0})", Thread.VolatileRead(ref _activeRetrieveThreads));
                Trace.WriteLine(message);
                Console.WriteLine(message);

                //TODO: try to trigger header retrieval for data luts?
                frame.GetNormalizedPixelData();
            }
            catch (OutOfMemoryException)
            {
                _stopAllActivity = true;
                Platform.Log(LogLevel.Error, "Out of memory trying to retrieve pixel data.  Prefetching will not resume unless memory becomes available.");
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Error retrieving frame pixel data.");
            }
            finally
            {
                Interlocked.Decrement(ref _activeRetrieveThreads);
            }
        }
        public void Test4()
        {
            var systemResources = new[]
            {
                new SystemResource(ResourceName.A, 2),
                new SystemResource(ResourceName.B, 1),
                new SystemResource(ResourceName.C, 3),
            };

            var system = new SystemResources(systemResources, new NoOpSystemLog());

            var processResources = new[]
            {
                new BankProcessResource(ResourceName.A, 1),
                new BankProcessResource(ResourceName.B, 2),
                new BankProcessResource(ResourceName.C, 1),
            };

            var process = new BankProcess("P1", 100, processResources);

            system.ClaimResources(process).Should().BeFalse();
            system.GetSystemSummary().Should().Be("Name A - Cur:2 Max:2 | Name B - Cur:1 Max:1 | Name C - Cur:3 Max:3");
        }
Example #4
0
        private static void CheckMemoryAvailable()
        {
            ApplicationServiceSettings settings = new ApplicationServiceSettings();

            if (settings.MinimumFreeMemoryMB <= 0)
            {
                return;
            }

            bool memoryAvailable = SystemResources.GetAvailableMemory(SizeUnits.Megabytes) > settings.MinimumFreeMemoryMB;

            if (!memoryAvailable)
            {
                string error = String.Format(
                    "Application server out of resources.  Minimum free memory not available ({0}MB required, {1}MB available).",
                    settings.MinimumFreeMemoryMB,
                    SystemResources.GetAvailableMemory(SizeUnits.Megabytes));

                Platform.Log(LogLevel.Warn, error);
                throw new FaultException <OutOfResourceFault>(new OutOfResourceFault {
                    ErrorMessage = error
                });
            }
        }
 public Task <IReadOnlyList <Resource> > GetResourcesAsync(object target, IPropertyInfo property, CancellationToken cancelToken)
 {
     return(Task.FromResult <IReadOnlyList <Resource> > (SystemResources.Where(r => property.Type.IsAssignableFrom(r.GetType().GetGenericArguments()[0])).ToList()));
 }
Example #6
0
        // This routine handles the following cases:
        // 1) a parent window is present, build the child window
        // 2) a parent is present, reparent the child window to it
        // 3) a parent window is not present, hide the child window by parenting it to SystemResources.Hwnd window.
        private void BuildOrReparentWindow()
        {
            DemandIfUntrusted();

            // Verify the thread has access to the context.
            // VerifyAccess();

            // Prevent reentry while building a child window,
            // also prevent the reconstruction of Disposed objects.
            if (_isBuildingWindow || _isDisposed)
            {
                return;
            }

            _isBuildingWindow = true;

            // Find the source window, this must be the parent window of
            // the child window.
            IntPtr             hwndParent = IntPtr.Zero;
            PresentationSource source     = PresentationSource.CriticalFromVisual(this, false /* enable2DTo3DTransition */);

            if (source != null)
            {
                HwndSource hwndSource = source as HwndSource;
                if (hwndSource != null)
                {
                    hwndParent = hwndSource.CriticalHandle;
                }
            }
            else
            {
                // attempt to also walk through 3D - if we get a non-null result then we know we are inside of
                // a 3D scene which is not supported
                PresentationSource goingThrough3DSource = PresentationSource.CriticalFromVisual(this, true /* enable2DTo3DTransition */);
                if (goingThrough3DSource != null)
                {
                    if (TraceHwndHost.IsEnabled)
                    {
                        TraceHwndHost.Trace(TraceEventType.Warning, TraceHwndHost.HwndHostIn3D);
                    }
                }
            }

            try
            {
                if (hwndParent != IntPtr.Zero)
                {
                    if (_hwnd.Handle == IntPtr.Zero)
                    {
                        // We now have a parent window, so we can create the child
                        // window.
                        BuildWindow(new HandleRef(null, hwndParent));
                        this.LayoutUpdated    += _handlerLayoutUpdated;
                        this.IsEnabledChanged += _handlerEnabledChanged;
                        this.IsVisibleChanged += _handlerVisibleChanged;
                    }
                    else if (hwndParent != UnsafeNativeMethods.GetParent(_hwnd))
                    {
                        // We have a different parent window.  Just reparent the
                        // child window under the new parent window.
                        UnsafeNativeMethods.SetParent(_hwnd, new HandleRef(null, hwndParent));
                    }
                }
                else
                {
                    // Reparent the window to notification-only window provided by SystemResources
                    // This keeps the child window around, but it is not visible.  We can reparent the
                    // window later when a new parent is available
                    var hwnd = SystemResources.GetDpiAwarenessCompatibleNotificationWindow(_hwnd);
                    UnsafeNativeMethods.SetParent(_hwnd, new HandleRef(null, hwnd.Handle));
                    // ...But we have a potential problem: If the SystemResources listener window gets
                    // destroyed ahead of the call to HwndHost.OnDispatcherShutdown(), the HwndHost's window
                    // will be destroyed too, before the "logical" Dispose has had a chance to do proper
                    // shutdown. This turns out to be very significant for WebBrowser/ActiveXHost, which shuts
                    // down the hosted control through the COM interfaces, and the control destroys its
                    // window internally. Evidently, the WebOC fails to do full, proper cleanup if its
                    // window is destroyed unexpectedly.
                    // To avoid this situation, we make sure SystemResources responds to the Dispatcher
                    // shutdown event after this HwndHost.
                    SystemResources.DelayHwndShutdown();
                }
            }
            finally
            {
                // Be careful to clear our guard bit.
                _isBuildingWindow = false;
            }
        }
Example #7
0
        private void BuildOrReparentWindow()
        {
            this.DemandIfUntrusted();
            if (this._isBuildingWindow || this._isDisposed)
            {
                return;
            }
            this._isBuildingWindow = true;
            IntPtr             intPtr             = IntPtr.Zero;
            PresentationSource presentationSource = PresentationSource.CriticalFromVisual(this, false);

            if (presentationSource != null)
            {
                HwndSource hwndSource = presentationSource as HwndSource;
                if (hwndSource != null)
                {
                    intPtr = hwndSource.CriticalHandle;
                }
            }
            else
            {
                PresentationSource presentationSource2 = PresentationSource.CriticalFromVisual(this, true);
                if (presentationSource2 != null && TraceHwndHost.IsEnabled)
                {
                    TraceHwndHost.Trace(TraceEventType.Warning, TraceHwndHost.HwndHostIn3D);
                }
            }
            try
            {
                if (intPtr != IntPtr.Zero)
                {
                    if (this._hwnd.Handle == IntPtr.Zero)
                    {
                        this.BuildWindow(new HandleRef(null, intPtr));
                        base.LayoutUpdated    += this._handlerLayoutUpdated;
                        base.IsEnabledChanged += this._handlerEnabledChanged;
                        base.IsVisibleChanged += this._handlerVisibleChanged;
                    }
                    else if (intPtr != UnsafeNativeMethods.GetParent(this._hwnd))
                    {
                        UnsafeNativeMethods.SetParent(this._hwnd, new HandleRef(null, intPtr));
                    }
                }
                else
                {
                    IntPtr value = (!FrameworkAppContextSwitches.DisableDevDiv1035544) ? this.Handle : this._hwnd.Handle;
                    if (value != IntPtr.Zero)
                    {
                        HwndWrapper dpiAwarenessCompatibleNotificationWindow = SystemResources.GetDpiAwarenessCompatibleNotificationWindow(this._hwnd);
                        if (dpiAwarenessCompatibleNotificationWindow != null)
                        {
                            UnsafeNativeMethods.SetParent(this._hwnd, new HandleRef(null, dpiAwarenessCompatibleNotificationWindow.Handle));
                            SystemResources.DelayHwndShutdown();
                        }
                        else
                        {
                            Trace.WriteLineIf(dpiAwarenessCompatibleNotificationWindow == null, string.Format("- Warning - Notification Window is null\n{0}", new StackTrace(true).ToString()));
                        }
                    }
                }
            }
            finally
            {
                this._isBuildingWindow = false;
            }
        }
Example #8
0
        /// <summary>
        /// The processing thread.
        /// </summary>
        /// <remarks>
        /// This method queries the database for WorkQueue entries to work on, and then uses
        /// a thread pool to process the entries.
        /// </remarks>
        public void Run()
        {
            // Force the alert to be displayed right away, if it happens
            DateTime lastLog = Platform.Time.AddMinutes(-61);

            if (!_threadPool.Active)
            {
                _threadPool.Start();
            }

            Platform.Log(LogLevel.Info, "Work Queue Processor running...");

            while (true)
            {
                if (_stop)
                {
                    return;
                }

                bool threadsAvailable = _threadPool.CanQueueItem;
                bool memoryAvailable  = WorkQueueSettings.Instance.WorkQueueMinimumFreeMemoryMB == 0
                                        ||
                                        SystemResources.GetAvailableMemory(SizeUnits.Megabytes) >
                                        WorkQueueSettings.Instance.WorkQueueMinimumFreeMemoryMB;

                if (threadsAvailable && memoryAvailable)
                {
                    try
                    {
                        Model.WorkQueue queueListItem = GetWorkQueueItem(ServerPlatform.ProcessorId);
                        if (queueListItem == null)
                        {
                            /* No result found, or reach max queue entries for each type */
                            _terminateEvent.WaitOne(WorkQueueSettings.Instance.WorkQueueQueryDelay, false);
                            continue;
                        }

                        if (!_extensions.ContainsKey(queueListItem.WorkQueueTypeEnum))
                        {
                            Platform.Log(LogLevel.Error,
                                         "No extensions loaded for WorkQueue item type: {0}.  Failing item.",
                                         queueListItem.WorkQueueTypeEnum);

                            //Just fail the WorkQueue item, not much else we can do
                            FailQueueItem(queueListItem, "No plugin to handle WorkQueue type: " + queueListItem.WorkQueueTypeEnum);
                            continue;
                        }

                        try
                        {
                            IWorkQueueProcessorFactory factory   = _extensions[queueListItem.WorkQueueTypeEnum];
                            IWorkQueueItemProcessor    processor = factory.GetItemProcessor();

                            // Enqueue the actual processing of the item to the thread pool.
                            _threadPool.Enqueue(processor, queueListItem, ExecuteProcessor);
                        }
                        catch (Exception e)
                        {
                            Platform.Log(LogLevel.Error, e, "Unexpected exception creating WorkQueue processor.");
                            FailQueueItem(queueListItem, "Failure getting WorkQueue processor: " + e.Message);
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        // Wait for only 1.5 seconds
                        Platform.Log(LogLevel.Error, e, "Exception occured when processing WorkQueue item.");
                        _terminateEvent.WaitOne(3000, false);
                    }
                }
                else
                {
                    if ((lastLog.AddMinutes(60) < Platform.Time) && !memoryAvailable)
                    {
                        lastLog = Platform.Time;
                        Platform.Log(LogLevel.Error, "Unable to process WorkQueue entries, Minimum memory not available, minimum MB required: {0}, current MB available:{1}",
                                     WorkQueueSettings.Instance.WorkQueueMinimumFreeMemoryMB,
                                     SystemResources.GetAvailableMemory(SizeUnits.Megabytes));

                        ServerPlatform.Alert(AlertCategory.Application, AlertLevel.Critical, "WorkQueue", AlertTypeCodes.NoResources,
                                             null, TimeSpan.Zero,
                                             "Unable to process WorkQueue entries, Minimum memory not available, minimum MB required: {0}, current MB available:{1}",
                                             WorkQueueSettings.Instance.WorkQueueMinimumFreeMemoryMB,
                                             SystemResources.GetAvailableMemory(SizeUnits.Megabytes));
                    }
                    // wait for new opening in the pool or termination
                    WaitHandle.WaitAny(new WaitHandle[] { _threadStop, _terminateEvent }, 3000, false);
                    _threadStop.Reset();
                }
            }
        }
Example #9
0
        public void Run()
        {
            var systemResources = new[]
            {
                new SystemResource(ResourceName.A, 10),
                new SystemResource(ResourceName.B, 10),
                new SystemResource(ResourceName.C, 10),
                new SystemResource(ResourceName.D, 10),
            };

            var stopwatch = new Stopwatch();

            var consoleSystemLog = new ConsoleSystemLog(
                stopwatch);

            var system = new SystemResources(systemResources, consoleSystemLog);

            // **

            var processes = new List <BankProcess>();

            var resourcesSignal = new ManualResetEvent(false);

            var process1 = new BankProcess("P1", 500, new[]
            {
                new BankProcessResource(ResourceName.A, 5),
                new BankProcessResource(ResourceName.B, 5),
                new BankProcessResource(ResourceName.C, 6),
                new BankProcessResource(ResourceName.D, 5),
            },
                                           resourcesSignal);

            processes.Add(process1);

            var process2 = new BankProcess("P2", 10, new[]
            {
                new BankProcessResource(ResourceName.A, 7),
                new BankProcessResource(ResourceName.B, 1),
                new BankProcessResource(ResourceName.C, 3),
                new BankProcessResource(ResourceName.D, 9),
            },
                                           resourcesSignal);

            processes.Add(process2);

            var process3 = new BankProcess("P3", 300, new[]
            {
                new BankProcessResource(ResourceName.A, 1),
                new BankProcessResource(ResourceName.B, 1),
                new BankProcessResource(ResourceName.C, 1),
                new BankProcessResource(ResourceName.D, 1),
            },
                                           resourcesSignal);

            processes.Add(process3);

            var tasks = new List <Task>();

            stopwatch.Start();

            foreach (var process in processes)
            {
                var task = Task.Run(() => { process.Start(system); });

                tasks.Add(task);
            }

            foreach (var task in tasks)
            {
                task.Wait();
            }

            stopwatch.Stop();
            resourcesSignal.Dispose();
        }