Example #1
0
        private static void RunProcess(IServerProcess process, BackgroundProcessContext context)
        {
            // Long-running tasks are based on custom threads (not threadpool ones) as in
            // .NET Framework 4.5, so we can try to set custom thread name to simplify the
            // debugging experience.
            TrySetThreadName(process.ToString());

            // LogProvider.GetLogger does not throw any exception, that is why we are not
            // using the `try` statement here. It does not return `null` value as well.
            var logger = LogProvider.GetLogger(process.GetProcessType());

            logger.DebugFormat("Background process '{0}' started.", process);

            try
            {
                process.Execute(context);
            }
            catch (OperationCanceledException)
            {
            }
            catch (Exception ex)
            {
                logger.FatalException(
                    String.Format(
                        "Fatal error occurred during execution of '{0}' process. It will be stopped. See the exception for details.",
                        process),
                    ex);
            }

            logger.DebugFormat("Background process '{0}' stopped.", process);
        }
Example #2
0
        public void TestDeleteAtBOF()
        {
            IServerProcess LProcess = DataSession.ServerSession.StartProcess(new ProcessInfo(DataSession.SessionInfo));

            try
            {
                var LFetchCount = DataSession.ServerSession.SessionInfo.FetchCount;
                LProcess.Execute("create table TestDeleteAtBOF { ID : Integer, Name : String, key { ID } };", null);
                LProcess.Execute("insert row { 1 ID, 'Joe' Name } into TestDeleteAtBOF;", null);
                LProcess.Execute("insert row { 2 ID, 'John' Name } into TestDeleteAtBOF;", null);

                IServerCursor LCursor = LProcess.OpenCursor("select TestDeleteAtBOF browse by { ID } capabilities { navigable, backwardsnavigable, bookmarkable, searchable, updateable } isolation browse", null);
                try
                {
                    var LRow = LCursor.Plan.RequestRow();
                    try
                    {
                        LCursor.Last();
                        LCursor.Prior();
                        LCursor.Prior();
                        LCursor.Delete();
                        if (LCursor.BOF() && !LCursor.Next())
                        {
                            throw new Exception("Delete At BOF failed");
                        }
                    }
                    finally
                    {
                        LCursor.Plan.ReleaseRow(LRow);
                    }
                }
                finally
                {
                    LProcess.CloseCursor(LCursor);
                }
            }
            finally
            {
                DataSession.ServerSession.StopProcess(LProcess);
            }
        }
Example #3
0
        private static void InsertDocument(IServerProcess process, Guid documentID, Guid rootElementID)
        {
            DataParams paramsValue = new DataParams();

            paramsValue.Add(DataParam.Create(process, "ADocumentID", documentID));
            paramsValue.Add(DataParam.Create(process, "AElementID", rootElementID));
            process.Execute
            (
                "insert table { row { ADocumentID ID, AElementID Root_Element_ID }, key { } } into .System.Internet.XMLDocument",
                paramsValue
            );
        }
Example #4
0
        private void AsyncStop(int processID, IServerSession session)
        {
            IServerProcess process = session.StartProcess(new ProcessInfo(_session.SessionInfo));

            try
            {
                process.Execute("StopProcess(" + processID + ")", null);
            }
            finally
            {
                session.StopProcess(process);
            }
        }
Example #5
0
        private static void WriteContent(IServerProcess process, Guid elementID, string content, int childSequence, byte type)
        {
            DataParams paramsValue = new DataParams();

            paramsValue.Add(DataParam.Create(process, "AElementID", elementID));
            paramsValue.Add(DataParam.Create(process, "ASequence", childSequence));
            paramsValue.Add(DataParam.Create(process, "AContent", content));
            paramsValue.Add(DataParam.Create(process, "AType", type));
            process.Execute
            (
                "insert table { row { AElementID Element_ID, ASequence Sequence, AContent Content, AType Type }, key { } } into .System.Internet.XMLContent",
                paramsValue
            );
        }
Example #6
0
        public void Execute(BackgroundProcessContext context)
        {
            for (var i = 0; i <= MaxRetryAttempts; i++)
            {
                try
                {
                    _innerProcess.Execute(context);
                    return;
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    // Break the loop after the retry attempts number exceeded.
                    if (i >= MaxRetryAttempts - 1)
                    {
                        throw;
                    }

                    var nextTry  = DelayCallback(i);
                    var logLevel = GetLogLevel(i);

                    _logger.Log(
                        logLevel,
                        () => String.Format(
                            "Error occurred during execution of '{0}' process. Execution will be retried (attempt {1} of {2}) in {3} seconds.",
                            _innerProcess,
                            i + 1,
                            MaxRetryAttempts,
                            nextTry),
                        ex);

                    context.Wait(nextTry);

                    if (context.IsShutdownRequested)
                    {
                        break;
                    }
                }
            }
        }
        public void Execute(BackgroundProcessContext context)
        {
            for (var i = 0; i <= MaxRetryAttempts; i++)
            {
                try
                {
                    _innerProcess.Execute(context);
                    return;
                }
                catch (Exception ex)
                {
                    if (ex is OperationCanceledException && context.IsShutdownRequested)
                    {
                        throw;
                    }

                    // Break the loop after the retry attempts number exceeded.
                    if (i >= MaxRetryAttempts - 1)
                    {
                        throw;
                    }

                    var nextTry  = DelayCallback(i);
                    var logLevel = GetLogLevel(i);

                    _logger.Log(
                        logLevel,
                        // ReSharper disable once AccessToModifiedClosure
                        () => $"Error occurred during execution of '{_innerProcess}' process. Execution will be retried (attempt #{i + 1}) in {nextTry} seconds.",
                        ex);

                    context.Wait(nextTry);

                    if (context.IsShutdownRequested)
                    {
                        break;
                    }
                }
            }
        }
Example #8
0
        /// <summary>
        /// 在当前进程中运行
        /// </summary>
        /// <param name="process"></param>
        /// <param name="context"></param>
        private static void RunProcess(IServerProcess process, BackgroundProcessContext context)
        {
            // Long-running tasks are based on custom threads (not threadpool ones) as in .NET Framework 4.5, so we can try to set custom thread name to simplify the debugging experience.
            // 与. net Framework 4.5中一样,长时间运行的任务基于自定义线程(而不是线程池线程),因此我们可以尝试设置自定义线程名,以简化调试体验。
            TrySetThreadName(process.ToString());

            // LogProvider.GetLogger does not throw any exception, that is why we are not using the `try` statement here.
            // GetLogger不会抛出任何异常,这就是我们在这里不使用‘try’语句的原因。
            // It does not return `null` value as well.
            // 它也不返回' null '值。
            var logger = LogProvider.GetLogger(process.GetProcessType());

            //logger.Debug($"Background process '{process}' started.");
            logger.Debug($"后台进程 '{process}' 启动了。");

            try
            {
                process.Execute(context);
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException && context.IsShutdownRequested)
                {
                    // Graceful shutdown
                    //logger.Trace($"Background process '{process}' was stopped due to a shutdown request.");
                    logger.Trace($"后台进程 '{process}' 由于关闭请求而停止。");
                }
                else
                {
                    logger.FatalException(
                        $"Fatal error occurred during execution of '{process}' process. It will be stopped. See the exception for details.",
                        ex);
                }
            }

            //logger.Debug($"Background process '{process}' stopped.");
            logger.Debug($"后台进程 '{process}' 停止了。");
        }
Example #9
0
 private void AsyncCancelCurrent(object state)
 {
     try
     {
         // Stop the current process
         IServerProcess process = _serverSession.StartProcess(new ProcessInfo(_serverSession.SessionInfo));
         try
         {
             process.Execute("StopProcess(" + ((int)state).ToString() + ")", null);
         }
         finally
         {
             _serverSession.StopProcess(process);
         }
     }
     catch
     {
         // Do nothing, but catch all exceptions; the framework aborts the app if a thread leaves unhandled exceptions
     }
     finally
     {
         _cancellingCurrent = false;
     }
 }
Example #10
0
        public void TestCLI()
        {
            IServerProcess LProcess = DataSession.ServerSession.StartProcess(new ProcessInfo(DataSession.SessionInfo));

            try
            {
                var LFetchCount = DataSession.ServerSession.SessionInfo.FetchCount;
                LProcess.Execute("create table Test { ID : Integer, key { ID } };", null);
                LProcess.Execute(String.Format("for var LIndex := 1 to {0} do insert row {{ LIndex ID }} into Test;", LFetchCount.ToString()), null);

                IServerCursor LCursor = LProcess.OpenCursor("select Test order by { ID } capabilities { navigable, backwardsnavigable, bookmarkable, searchable, updateable }", null);
                try
                {
                    var LCounter = 0;
                    while (LCursor.Next())
                    {
                        using (IRow LRow = LCursor.Select())
                        {
                            LCounter += (int)LRow[0];
                        }
                    }

                    if (LCounter != (LFetchCount * (LFetchCount + 1)) / 2)
                    {
                        throw new Exception("Fetch count summation failed");
                    }

                    LCursor.Reset();
                    LCounter = 0;

                    while (LCursor.Next())
                    {
                        using (IRow LRow = LCursor.Select())
                        {
                            LCounter++;
                            if (LCounter != (int)LRow[0])
                            {
                                throw new Exception("Select failed");
                            }
                        }
                    }

                    LCursor.Reset();
                    LCounter = 0;

                    LCursor.Next();
                    LCursor.Next();

                    using (IRow LRow = LCursor.Select())
                    {
                        LRow[0] = -1;
                        LCursor.Update(LRow);
                    }

                    using (IRow LRow = LCursor.Select())
                    {
                        if ((int)LRow[0] != -1)
                        {
                            throw new Exception("Update failed");
                        }
                    }

                    LCursor.Delete();

                    using (IRow LRow = LCursor.Select())
                    {
                        if ((int)LRow[0] != 1)
                        {
                            throw new Exception("Delete failed");
                        }

                        LRow[0] = 2;
                        LCursor.Insert(LRow);
                    }

                    using (IRow LRow = LCursor.Select())
                    {
                        if ((int)LRow[0] != 2)
                        {
                            throw new Exception("Insert failed");
                        }
                    }

                    LCursor.Reset();
                    LCounter = 0;
                    Guid LBookmark = Guid.Empty;

                    while (LCursor.Next())
                    {
                        using (IRow LRow = LCursor.Select())
                        {
                            LCounter++;
                            if (LCounter == 5)
                            {
                                LBookmark = LCursor.GetBookmark();
                            }
                        }
                    }

                    if (!LCursor.GotoBookmark(LBookmark, true))
                    {
                        throw new Exception("GotoBookmark failed");
                    }

                    using (IRow LRow = LCursor.Select())
                    {
                        if ((int)LRow[0] != 5)
                        {
                            throw new Exception("GotoBookmark failed");
                        }
                    }

                    LCursor.DisposeBookmark(LBookmark);
                }
                finally
                {
                    LProcess.CloseCursor(LCursor);
                }

                LProcess.Execute("delete Test;", null);
                LFetchCount *= 10;
                LProcess.Execute(String.Format("for var LIndex := 1 to {0} do insert row {{ LIndex ID }} into Test;", LFetchCount.ToString()), null);

                LCursor = LProcess.OpenCursor("select Test order by { ID } capabilities { navigable, backwardsnavigable, bookmarkable, searchable, updateable }", null);
                try
                {
                    var LCounter = 0;
                    while (LCursor.Next())
                    {
                        using (IRow LRow = LCursor.Select())
                        {
                            LCounter += (int)LRow[0];
                        }
                    }

                    if (LCounter != (LFetchCount * (LFetchCount + 1)) / 2)
                    {
                        throw new Exception("Fetch count summation failed");
                    }

                    LCursor.Reset();
                    LCounter = 0;

                    while (LCursor.Next())
                    {
                        using (IRow LRow = LCursor.Select())
                        {
                            LCounter++;
                            if (LCounter != (int)LRow[0])
                            {
                                throw new Exception("Select failed");
                            }
                        }
                    }
                }
                finally
                {
                    LProcess.CloseCursor(LCursor);
                }
            }
            finally
            {
                DataSession.ServerSession.StopProcess(LProcess);
            }
        }
        private static void RunProcess(IServerProcess process, BackgroundProcessContext context)
        {
            // Long-running tasks are based on custom threads (not threadpool ones) as in 
            // .NET Framework 4.5, so we can try to set custom thread name to simplify the
            // debugging experience.
            TrySetThreadName(process.ToString());

            // LogProvider.GetLogger does not throw any exception, that is why we are not
            // using the `try` statement here. It does not return `null` value as well.
            var logger = LogProvider.GetLogger(process.GetProcessType());
            logger.Debug($"Background process '{process}' started.");

            try
            {
                process.Execute(context);
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException && context.IsShutdownRequested)
                {
                    // Graceful shutdown
                    logger.Trace($"Background process '{process}' was stopped due to a shutdown request.");
                }
                else
                {
                    logger.FatalException(
                        $"Fatal error occurred during execution of '{process}' process. It will be stopped. See the exception for details.",
                        ex);
                }
            }

            logger.Debug($"Background process '{process}' stopped.");
        }
Example #12
0
        private static Guid InsertElement(IServerProcess process, Guid documentID, XmlTextReader reader, Guid parentID, int sequence)
        {
            Guid       elementID   = Guid.NewGuid();
            DataParams paramsValue = new DataParams();

            // Insert the element
            paramsValue.Add(DataParam.Create(process, "AElementID", elementID));
            paramsValue.Add(DataParam.Create(process, "ADocumentID", documentID));
            paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.Prefix));
            paramsValue.Add(DataParam.Create(process, "AName", reader.LocalName));
            process.Execute
            (
                "insert table { row { AElementID ID, ADocumentID Document_ID, ANamespaceAlias NamespaceAlias, "
                + "AName Name }, key { } } into .System.Internet.XMLElement",
                paramsValue
            );

            // Attach to parent
            if (parentID != Guid.Empty)
            {
                paramsValue.Clear();
                paramsValue.Add(DataParam.Create(process, "AElementID", elementID));
                paramsValue.Add(DataParam.Create(process, "AParentElementID", parentID));
                paramsValue.Add(DataParam.Create(process, "ASequence", sequence));
                process.Execute
                (
                    "insert table { row { AElementID Element_ID, AParentElementID Parent_Element_ID, ASequence Sequence }, key { } } into .System.Internet.XMLElementParent",
                    paramsValue
                );
            }

            // Add attributes
            while (reader.MoveToNextAttribute())
            {
                paramsValue.Clear();
                paramsValue.Add(DataParam.Create(process, "AElementID", elementID));
                paramsValue.Add(DataParam.Create(process, "AValue", reader.Value));
                if (String.Compare(reader.Name, "xmlns", true) == 0)                    // Default namespace
                {
                    process.Execute
                    (
                        "insert table { row { AElementID Element_ID, AValue URI }, key { } } into .System.Internet.XMLDefaultNamespace",
                        paramsValue
                    );
                }
                else if (String.Compare(reader.Prefix, "xmlns", true) == 0)                     // Namespace alias
                {
                    paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.LocalName));
                    process.Execute
                    (
                        "insert table { row { AElementID Element_ID, ANamespaceAlias NamespaceAlias, AValue URI }, key { } } into .System.Internet.XMLNamespaceAlias",
                        paramsValue
                    );
                }
                else                    // regular attribute
                {
                    paramsValue.Add(DataParam.Create(process, "ANamespaceAlias", reader.Prefix));
                    paramsValue.Add(DataParam.Create(process, "AName", reader.LocalName));
                    process.Execute
                    (
                        "insert table { row { AElementID Element_ID, ANamespaceAlias NamespaceAlias, AName Name, AValue Value }, key { } } into .System.Internet.XMLAttribute",
                        paramsValue
                    );
                }
            }

            reader.MoveToElement();
            if (!reader.IsEmptyElement)
            {
                int         childSequence = 0;
                XmlNodeType nodeType;

                // Add child elements
                do
                {
                    reader.Read();
                    nodeType = reader.NodeType;
                    switch (nodeType)
                    {
                    case XmlNodeType.Text: WriteContent(process, elementID, reader.Value, childSequence++, 0); break;

                    case XmlNodeType.CDATA: WriteContent(process, elementID, reader.Value, childSequence++, 1); break;

                    case XmlNodeType.Element: InsertElement(process, documentID, reader, elementID, childSequence++); break;
                    }
                } while (nodeType != XmlNodeType.EndElement);
            }

            return(elementID);
        }
Example #13
0
        protected internal void WaitForCacheTimeStamp(IServerProcess process, long clientCacheTimeStamp)
        {
                        #if LOGCACHEEVENTS
            FInternalServer.LogMessage(LogEntryType.Information, String.Format("Thread {0} checking for cache time stamp {1}", Thread.CurrentThread.GetHashCode(), AClientCacheTimeStamp.ToString()));
                        #endif
            try
            {
                ManualResetEvent signal      = null;
                bool             signalAdded = false;

                                #if USESPINLOCK
                while (Interlocked.CompareExchange(ref _cacheSyncRoot, 1, 0) == 1)
                {
                    Thread.SpinWait(100);                      // Prevents CPU starvation
                }
                try
                                #else
                lock (FCacheSyncRoot)
                                #endif
                {
                    if (_clientCacheTimeStamp == clientCacheTimeStamp)
                    {
                        return;
                    }

                    if (_clientCacheTimeStamp > clientCacheTimeStamp)
                    {
                        process.Execute(".System.UpdateTimeStamps();", null);
                        throw new ServerException(ServerException.Codes.CacheSerializationError, clientCacheTimeStamp, _clientCacheTimeStamp);
                    }

                    signalAdded = !_cacheSignals.TryGetValue(clientCacheTimeStamp, out signal);
                    if (signalAdded)
                    {
                        signal = _cacheSignalPool.Acquire();
                        _cacheSignals.Add(clientCacheTimeStamp, signal);
                    }

                    //Error.AssertFail(FCacheSyncEvent.Reset(), "Internal error: CacheSyncEvent reset failed");
                }
                                #if USESPINLOCK
                finally
                {
                    Interlocked.Decrement(ref _cacheSyncRoot);
                }
                                #endif

                                #if LOGCACHEEVENTS
                FInternalServer.LogMessage(LogEntryType.Information, String.Format("Thread {0} waiting for cache time stamp {1}", Thread.CurrentThread.GetHashCode(), AClientCacheTimeStamp.ToString()));
                                #endif

                try
                {
                    if (!(signal.WaitOne(CacheSerializationTimeout)))
                    {
                        throw new ServerException(ServerException.Codes.CacheSerializationTimeout);
                    }
                }
                finally
                {
                    if (signalAdded)
                    {
                                                #if USESPINLOCK
                        while (Interlocked.CompareExchange(ref _cacheSyncRoot, 1, 0) == 1)
                        {
                            Thread.SpinWait(100);                             // Prevents CPU starvation
                        }
                        try
                                                #else
                        lock (FCacheSyncRoot)
                                                #endif
                        {
                            _cacheSignals.Remove(clientCacheTimeStamp);
                        }
                                                #if USESPINLOCK
                        finally
                        {
                            Interlocked.Decrement(ref _cacheSyncRoot);
                        }
                                                #endif

                        _cacheSignalPool.Relinquish(signal);
                    }
                }
            }
            catch (Exception E)
            {
                _internalServer.LogError(E);
                throw E;
            }
        }