private void ReportStatusError(string info)
 {
     if ((_Logger != null) && (_Logger.IsErrorEnabled))
     {
         _Logger.Error(info);
     }
 }
예제 #2
0
        /// <summary>
        /// Process Start
        /// </summary>
        /// <param name="startFileName"></param>
        /// <param name="startFileArg"></param>
        public static bool ProcessStart(string startFileName, string startFileArg = null)
        {
            ThrowHelper.ThrowIfNull(startFileName, "startFileName");

            var cmdProcess = new Process();
            var si         = cmdProcess.StartInfo;

            si.FileName = startFileName;      // 命令
            if (startFileArg.HasValue())
            {
                si.Arguments = startFileArg;      // 参数
            }
            try
            {
                cmdProcess.Start();
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("ProcessStart-startFileName:{0}-startFileArg:{1}-ex:{2}"
                          .Fmt(startFileName, startFileArg, ex));

                //Console.WriteLine("ProcessHelper-file:{0}-arg:{1}-ex:{2}",
                //                    startFileName, startFileArg, ex);
                return(false);
            }
        }
예제 #3
0
        // Request Lifecycle
        private void Listen()
        {
            listener.Start();

            try{
                while (!exitFlag)
                {
                    listener.GetContextAsync()
                    .ContinueWith(task => {
                        Task.Run(() => {
                            try{
                                HandleRequest(task.Result);
                            }catch (Exception e) {
                                logger.Error(this.GetType(), e);
                            }
                        });
                    }).Wait();
                    // Here we wait for a request to be recieved, then we dispatch
                    // the HandleRequest method, but we dont wait for that to finish before we
                    // we start trying to get the next context.
                }
            }finally{
                listener.Close();
            }
        }
예제 #4
0
        /// <summary>
        /// Queues a method for execution, and specifies an object containing data to
        /// be used by the method. The method executes when a thread pool thread becomes
        /// available.
        /// </summary>
        /// <param name="callBack"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static void ThreadPool_QueueUserWorkItem(WaitCallback callBack,
                                                        object state,
                                                        Action <Exception> failedAction = null)
        {
            ThrowHelper.ThrowIfNull(callBack, "action");

            ThreadPool.QueueUserWorkItem(_ =>
            {
                try
                {
                    callBack(_);
                }
                catch (Exception ex)
                {
                    Log.Error("ThreadPool_QueueUserWorkItem-EX:{0}".Fmt(ex));

                    if (failedAction != null)
                    {
                        failedAction(ex);
                    }
#if DEBUG
                    throw ex;
#else
                    ex = null;
#endif
                }
            }, state);
        }
예제 #5
0
        internal static void DoStep(PipMod.Step step, Assembly assembly)
        {
            var methods = GetStepHandlersFor(assembly, step);

            if (methods.Count > 0)
            {
                Logger.Verbose("{0}: {1}", step.ToString().ToUpper(), assembly.FullName);
                foreach (var method in methods)
                {
                    try
                    {
                        Logger.Debug("Invoking step handler in: {0}", method.DeclaringType.FullName);
                        var args = method.GetParameters();
                        if (args.Length == 1 && typeof(IPipMod).IsAssignableFrom(args[0].ParameterType))
                        {
                            method.Invoke(null, new object[] { GetModForAssembly(assembly) });
                        }
                        else if (args.Length == 1 && typeof(Assembly).IsAssignableFrom(args[0].ParameterType))
                        {
                            method.Invoke(null, new object[] { assembly });
                        }
                        else
                        {
                            method.Invoke(null, new object[0]);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("Failed running {0} for '{1}' at {2}.{3}:", step.ToString().ToUpper(), assembly.FullName, method.DeclaringType.FullName, method.Name);
                        Logger.Log(ex);
                        // ModHadError(mod, step);
                    }
                }
            }
        }
예제 #6
0
        private async ValueTask OnFinish(EditContext editContext)
        {
            var messageStore = new ValidationMessageStore(editContext);

            //verify credential
            try
            {
                var client  = AppRuntimeContext.Current.Resolve <ExamAssistantClient>();
                var isValid = await client.ValidateFirebaseSettingAsync(Options.To <FirebaseSettingDto>());

                if (!isValid)
                {
                    messageStore.Add(editContext.Field("JsonCredentials"), $"Failed to validate the provided credential. Please check again.");
                    editContext.NotifyValidationStateChanged();
                    return;
                }
                //var examService = new ExamService(Options.ProjectId, Options.JsonCredentials);
            }
            catch (System.Exception ex)
            {
                Logger.Error("Failed to valid the JsonCredentials provided", ex);
                messageStore.Add(editContext.Field("JsonCredentials"), $"Failed to validate the provided credential. Please check again.");
                editContext.NotifyValidationStateChanged();
                return;
            }
            await((DrawerRef <bool>)base.FeedbackRef)?.CloseAsync(true);
            // await this.OkCancelRefWithResult.OkAsync(true);
            // await this.CloseFeedbackAsync();
            // await this.CloseAsync(true);
        }
예제 #7
0
        /// <summary>
        /// </summary>
        /// <param name="dataItem"></param>
        /// <returns></returns>
        public void Enqueue(TData dataItem)
        {
            try
            {
                if (_itemQueue.IsAddingCompleted)
                {
                    return;
                }

                _itemQueue.Add(dataItem);
            }
            catch (Exception ex)
            {
                Log.Error("Enqueue(itemQueue.Add)", ex);
            }
        }
예제 #8
0
        private static List <string> GetPlanMenuByCategory(HashedString category)
        {
            var i = BUILDINGS.PLANORDER.FindIndex(v => category == v.category);

            if (i < 0)
            {
                Logger.Error("Failed to find plan order category by ID: {0}", category);
                return(null);
            }

            return((List <string>)BUILDINGS.PLANORDER[i].data);
        }
 public bool RefreshWorkingCopy()
 {
     _Logger.Info("Starting to refresh the working copy folder");
     if (!IsSvnControlled(WorkingCopyPath))
     {
         _Logger.Info("No working copy folder or currently not under SVN control. Checking out content");
         SvnCheckOutArgs checkoutArgs = new SvnCheckOutArgs();
         checkoutArgs.Depth   = SvnDepth.Infinity;
         checkoutArgs.Notify += new EventHandler <SvnNotifyEventArgs>(CheckoutNotificationHandler);
         try
         {
             SvnUpdateResult result;
             bool            returncode = _SvnClient.CheckOut(SvnUriTarget.FromString(RepositoryUri), WorkingCopyPath, out result);
             if (returncode)
             {
                 _RepositoryRevision = (int)result.Revision;
                 _Logger.Info(String.Format("Sucessfully checked out revision {0} from {1} to {2}", _RepositoryRevision, RepositoryUri, WorkingCopyPath));
             }
         }
         catch (Exception ex)
         {
             _Logger.Fatal(String.Format("Checkout from {0} to {1} failed! - {2}", RepositoryUri, WorkingCopyPath, ex));
             return(false);
         }
     }
     else
     {
         _Logger.Info("Updating working copy folder");
         SvnUpdateArgs updateArgs = new SvnUpdateArgs();
         updateArgs.Depth     = SvnDepth.Infinity;
         updateArgs.Notify   += new EventHandler <SvnNotifyEventArgs>(CheckoutNotificationHandler);
         updateArgs.Conflict += new EventHandler <SvnConflictEventArgs>(ConflictHandler);
         try
         {
             SvnUpdateResult result;
             bool            returncode = _SvnClient.Update(WorkingCopyPath, updateArgs, out result);
             if (!returncode || (result.Revision < 0))
             {
                 _Logger.Error(String.Format("Updating from {0} to {1} failed!", RepositoryUri, WorkingCopyPath));
                 return(false);
             }
             _RepositoryRevision = (int)result.Revision;
             _Logger.Info(String.Format("Sucessfully updated  to revision {0}", _RepositoryRevision));
         }
         catch (Exception ex)
         {
             _Logger.Fatal(String.Format("Checkout from {0} to {1} failed! - {2}", RepositoryUri, WorkingCopyPath, ex));
             return(false);
         }
     }
     return(true);
 }
예제 #10
0
 /// <summary>
 /// Adds an item to the given tech, by ID
 /// </summary>
 /// <param name="techID">The ID of the tech to add to</param>
 /// <param name="prefabID">The ID of the prefab to add</param>
 public static void AddTechItem(string techID, string prefabID)
 {
     if (Techs.TECH_GROUPING.TryGetValue(techID, out var techItems))
     {
         var len = techItems.Length;
         Array.Resize(ref techItems, len + 1);
         techItems[len] = prefabID;
         Techs.TECH_GROUPING[techID] = techItems;
     }
     else
     {
         Logger.Error("Tried to add prefab '{0}' to non-existant tech '{1}'", prefabID, techID);
     }
 }
예제 #11
0
파일: ExecResult.cs 프로젝트: juna0613/ETB
        public static void PrettyLog(this ExecResult self, Logging.ILogger logger, string prefix = "", string suffix = "")
        {
            var content = prefix + self.PrettyPrint() + suffix;

            switch (self.Status)
            {
            case ExecStatus.Success:
                logger.Info(content);
                break;

            case ExecStatus.Warn:
                logger.Warn(content);
                break;

            case ExecStatus.Error:
                logger.Error(content);
                break;

            case ExecStatus.Fatal:
            default:
                logger.Fatal(content);
                break;
            }
        }
예제 #12
0
 /// <summary>
 /// Issues a formatted error.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="message">Message with formats.</param>
 /// <param name="data">The data into message.</param>
 public static void ErrorFormatted([NotNull] Type type, [NotEmpty] string message, [NotNull] params object[] data)
 {
     Logging.ILogger logger = GetLogger(type);
     logger.Error(string.Format(message, data));
 }
예제 #13
0
 /// <summary>
 /// Issues a error.
 /// </summary>
 /// <param name="type">The type of class/...</param>
 /// <param name="message">The message of warning.</param>
 public static void Error([NotNull] Type type, [NotEmpty] string message)
 {
     Logging.ILogger logger = GetLogger(type);
     logger.Error(message);
 }
예제 #14
0
        /// <summary>
        /// Processa os dados carregados do LoadNext.
        /// </summary>
        /// <param name="data"></param>
        private void ProcessDataFromLoadNext(OrderedDictionary data)
        {
            int num = 0;

            byte[] buffer = null;
            foreach (DictionaryEntry entry in data)
            {
                EvictionHint hint2;
                num = 0;
                object            key  = null;
                ProviderCacheItem item = null;
                Colosoft.Caching.Expiration.ExpirationHint expiryHint = null;
                string    resyncProviderName = null;
                Hashtable queryInfo          = null;
                try
                {
                    if ((!(entry.Key is string) || !(entry.Value is ProviderCacheItem)))
                    {
                        throw new InvalidOperationException("Invalid Key/Value type specified");
                    }
                    key  = entry.Key;
                    item = (ProviderCacheItem)entry.Value;
                    if (item == null)
                    {
                        continue;
                    }
                    CacheLoaderUtil.EvaluateExpirationParameters(item.AbsoluteExpiration, item.SlidingExpiration);
                    expiryHint = Expiration.DependencyHelper.GetExpirationHint(item.Dependency, item.AbsoluteExpiration, item.SlidingExpiration);
                    if ((expiryHint != null) && item.ResyncItemOnExpiration)
                    {
                        expiryHint.SetBit(2);
                    }
                    resyncProviderName = (item.ResyncProviderName == null) ? null : item.ResyncProviderName.ToLower();
                    queryInfo          = new Hashtable();
                    TypeInfoMap typeInfoMap = _cache.GetTypeInfoMap();
                    if (typeInfoMap != null)
                    {
                        queryInfo["query-info"] = CacheLoaderUtil.GetQueryInfo(item.Value, typeInfoMap);
                    }
                    if (item.Tags != null)
                    {
                        queryInfo["tag-info"] = CacheLoaderUtil.GetTagInfo(item.Value, item.Tags);
                    }
                    if (item.NamedTags != null)
                    {
                        Hashtable hashtable2 = CacheLoaderUtil.GetNamedTagsInfo(item.Value, item.NamedTags, typeInfoMap);
                        if (hashtable2 != null)
                        {
                            queryInfo["named-tag-info"] = hashtable2;
                        }
                    }
                }
                catch (Exception exception3)
                {
                    OnProcessEntryError(entry, exception3);
                    continue;
                }
                var    set          = new BitSet();
                object currentValue = item.Value;
                try
                {
                    hint2 = new PriorityEvictionHint(item.ItemPriority);
                    if (!(currentValue is ICacheItemRecord))
                    {
                        buffer = this.SafeSerialize(currentValue) as byte[];
                        if ((buffer != null) && _cache.CompressionEnabled)
                        {
                            buffer = IO.Compression.CompressionUtil.Compress(buffer, ref set, _cache.CompressThresholdSize);
                        }
                        if (buffer != null)
                        {
                            currentValue = UserBinaryObject.CreateUserBinaryObject(buffer);
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnLoadProcessingError(ex);
                    continue;
                }
                while (num <= this.NoOfRetries)
                {
                    if (_cache.IsRunning)
                    {
                        if (!CanInsertEntry(key, currentValue))
                        {
                            break;
                        }
                        try
                        {
                            _cache.Insert(key, currentValue, expiryHint, null, hint2, item.Group, item.SubGroup, queryInfo, set, null, 0, LockAccessType.IGNORE_LOCK, null, resyncProviderName, new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation));
                        }
                        catch (Exception exception4)
                        {
                            num++;
                            System.Threading.Thread.Sleep(this.RetryInterval);
                            if (num > this.NoOfRetries)
                            {
                                OnInsertEntryError(key, currentValue, exception4);
                                if (exception4 is OperationFailedException)
                                {
                                    if (((OperationFailedException)exception4).IsTracable || !_logger.IsErrorEnabled)
                                    {
                                        continue;
                                    }
                                    _logger.Error("CacheStartupLoader.Load()".GetFormatter(), exception4);
                                    break;
                                }
                                if (_logger.IsErrorEnabled)
                                {
                                    _logger.Error("CacheStartupLoader.Load()".GetFormatter(), exception4);
                                    break;
                                }
                            }
                            continue;
                        }
                        OnInsertedEntry(key, currentValue);
                    }
                    break;
                }
            }
        }
예제 #15
0
        /// <summary>
        ///     PSOT 方式下载指定 URL 的流数据内容, 本方法可指定待下载页面的引用页面/页面编码/下载超时时间/HTTP 代理
        /// </summary>
        /// <param name="url">待下载 URL</param>
        /// <param name="headerReferer">待下载页面的引用页</param>
        /// <param name="isPost">是否 POST 方式下载页面</param>
        /// <param name="postData">POST 方式下载页面的参数</param>
        /// <param name="timeout">下载页面的超时时间, -1 将忽略本项, 单位:毫秒, 默认值为 100,000 毫秒</param>
        /// <param name="webProxy">当前下载操作使用的 HTTP 代理</param>
        /// <returns>下载得到的页面流数据, 如果下载失败返回 NULL</returns>
        /// <exception cref="ArgumentNullException">url is null</exception>
        public static Stream DownLoadStream(string url, string headerReferer, bool isPost, byte[] postData, int timeout,
                                            IWebProxy webProxy)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url", "[url] null...");
            }

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                {
                    request.Accept = "*/*";

                    if (webProxy != null)
                    {
                        request.Proxy = webProxy;
                    }

                    if (!string.IsNullOrEmpty(headerReferer))
                    {
                        request.Referer = headerReferer;
                    }

                    if (timeout > 0)
                    {
                        request.Timeout = timeout;
                    }

                    // request.Headers["Cookie"] = "ASPSESSIONIDSATSACRA=FDAANHLDOGLMEDOMKGOEBHFK";

                    #region 拼接 POST 数据

                    if (isPost)
                    {
                        request.Method      = "POST";
                        request.ContentType = "application/x-www-form-urlencoded";

                        if (postData != null && postData.Length != 0)
                        {
                            request.ContentLength = postData.Length;

                            using (var requestStream = request.GetRequestStream())
                            {
                                requestStream.Write(postData, 0, postData.Length);
                            }
                        }
                        else
                        {
                            request.ContentLength = 0L;
                        }
                    }

                    #endregion 拼接 POST 数据

                    request.Headers["Accept-Language"] = "zh-cn";
                    request.UserAgent =
                        "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; InfoPath.2; .NET CLR 2.0.50727; CIBA; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)";

                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        var stream    = new MemoryStream();
                        var resStream = response.ContentEncoding != "gzip" //解压某些WEB服务器强行响应 GZIP 数据
                            ? response.GetResponseStream()
                            : new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);

                        var buffer = new byte[1024];
                        var len    = 0;
                        while ((len = resStream.Read(buffer, 0, 1024)) > 0)
                        {
                            stream.Write(buffer, 0, len);
                        }

                        stream.Seek(0, SeekOrigin.Begin); //INFO 下载的流数据把起始位置设到开始, 否则对流数据的接下来的操作会有莫名 BUG
                        return(stream);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("url:{0}, headerReferer:{1}".Fmt(url, headerReferer), ex);
                ex = null;
            }
            return(null);
        }