protected virtual void ErrorEventHandler(ErrorEvent handler, ErrorEventArgs args)
 {
     if (handler != null)
     {
         handler(this, args);
     }
 }
        public void Test()
        {
            var tc = new TestClass();

            Assert.IsTrue(string.IsNullOrEmpty(tc.InstanceName));

            tc.ErrorEvent += Tc_ErrorEvent;
            ErrorEvent     = null;
            var ex = new Exception("test");

            Assert.IsNull(ErrorEvent);
            tc.SendErrorEvent(ex);
            Assert.IsNotNull(ErrorEvent);
            // ReSharper disable once PossibleNullReferenceException
            Assert.AreSame(ex, ErrorEvent.GetException());

            tc.PropertyChanged  += Tc_PropertyChanged;
            PropertyChangedEvent = null;
            var propName = nameof(ErrorEvent);

            Assert.IsNull(PropertyChangedEvent);
            tc.SendPropertyChanged(propName);
            Assert.IsNotNull(PropertyChangedEvent);
            // ReSharper disable once PossibleNullReferenceException
            Assert.AreEqual(propName, PropertyChangedEvent.PropertyName);

            tc.DisposeCalled = false;
            Assert.IsFalse(tc.IsDisposed);
            Assert.IsFalse(tc.DisposeCalled);
            tc.Dispose();
            Assert.IsTrue(tc.IsDisposed);
            Assert.IsTrue(tc.DisposeCalled);

            tc.DisposeCalled = false;
            Assert.IsFalse(tc.DisposeCalled);
            tc.Dispose();
            Assert.IsFalse(tc.DisposeCalled);

            var className = "ClassName";

            tc = new TestClass(className);
            Assert.AreEqual(className, tc.InstanceName);
        }
Exemplo n.º 3
0
 private void RunPostor()
 {
     postorFlag = true;
     Task.Run(async() => {
         ProtocolError error;
         Message msg;
         while (postorFlag)
         {
             try
             {
                 if (ErrorList.TryDequeue(out error))
                 {
                     ErrorEvent?.Invoke(this, error);
                 }
                 else if (MessageList.TryDequeue(out msg))
                 {
                     if (msg.MessageID == MessageID.MI_BIG_BOX)
                     {
                         this.UnpackBigBox(msg as MessageBigBox);
                     }
                     else
                     {
                         MessageEvent?.Invoke(this, msg);
                     }
                 }
                 else
                 {
                     await Task.Delay(1);
                 }
             }
             catch (Exception ex) { ex.GetType(); }
         }
         //退出,清理所有消息
         while (ErrorList.TryDequeue(out error))
         {
             ErrorEvent?.Invoke(this, error);
         }
         while (MessageList.TryDequeue(out msg))
         {
             //MessageEvent?.Invoke(this, msg);
         }
     });
 }
Exemplo n.º 4
0
        // Carga un cliente desde un XML
        public static Customer LoadFrom(string filename)
        {
            Customer tCustomer = null;

            try
            {
                var          serializer = new XmlSerializer(typeof(Customer));
                FileStream   fs         = new FileStream(filename, FileMode.Open);
                StreamReader stream     = new StreamReader(fs, Encoding.Unicode);
                tCustomer = (Customer)serializer.Deserialize(stream);
                fs.Close();
            }catch (Exception ex)
            {
                IEvent e = new ErrorEvent("", "", "Customer::" + ex.Message);
                e.Publish();
            }

            return(tCustomer);
        }
        /// <summary>
        /// Checks that an <see cref="ErrorEvent"/> contains valid data.
        /// </summary>
        /// <param name="errorEvent">The event to check.</param>
        /// <param name="testId">The id of the test.</param>
        /// <param name="functionName">The name of the function the error occurred in.</param>
        private void VerifyErrorEvent(ErrorEvent errorEvent, string testId, string functionName)
        {
            Assert.Equal(BaseErrorReportingTestApplication.Service, errorEvent.ServiceContext.Service);
            Assert.Equal(BaseErrorReportingTestApplication.Version, errorEvent.ServiceContext.Version);

            Assert.Contains(functionName, errorEvent.Message);
            Assert.Contains(testId, errorEvent.Message);

            Assert.Equal(HttpMethod.Get.Method, errorEvent.Context.HttpRequest.Method);
            Assert.False(string.IsNullOrWhiteSpace(errorEvent.Context.HttpRequest.Url));
            Assert.True(errorEvent.Context.HttpRequest.ResponseStatusCode >= 200);

            if (_isWindows)
            {
                Assert.False(string.IsNullOrWhiteSpace(errorEvent.Context.ReportLocation.FilePath));
                Assert.True(errorEvent.Context.ReportLocation.LineNumber > 0);
            }
            Assert.Equal(functionName, errorEvent.Context.ReportLocation.FunctionName);
        }
Exemplo n.º 6
0
        private void downloadThread()
        {
            try
            {
                Uri            URL            = new Uri(httpUrl);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
                httpWebRequest.Timeout = 120 * 1000;
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();


                long totalBytes = httpWebResponse.ContentLength;
                //更新文件大小
                StartEvent?.Invoke(this, totalBytes);
                Stream st = httpWebResponse.GetResponseStream();
                Stream so = new FileStream(savePath, FileMode.Create);

                long   totalDownloadedByte = 0;
                byte[] by    = new byte[1024];
                int    osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);

                    osize = st.Read(by, 0, (int)by.Length);

                    //进度计算
                    double process = double.Parse(String.Format("{0:F}",
                                                                ((double)totalDownloadedByte / (double)totalBytes * 100)));
                    ProcessUpdateEvent?.Invoke(this, process);
                }
                //关闭资源
                httpWebResponse.Close();
                so.Close();
                st.Close();
                CompleteEvent?.Invoke(this, null);
            }
            catch (Exception ec)
            {
                //下载发生异常
                ErrorEvent?.Invoke(this, ec.Message);
            }
        }
Exemplo n.º 7
0
 public void Delete(string url, TaskEvent finished = null, ErrorEvent error = null)
 {
     try
     {
         FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(accessUrlBase + url);
         ftpReq.Credentials = icr;
         ftpReq.Method      = WebRequestMethods.Ftp.DeleteFile;
         FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse();
         ftpRes.Close();
     }
     catch (WebException e)
     {
         error?.Invoke(((FtpWebResponse)e.Response).StatusDescription);
     }
     catch (Exception e)
     {
         error?.Invoke(e.Message);
     }
 }
Exemplo n.º 8
0
        private ErrorEvent ReadErrorEvent()
        {
            ErrorEvent errorEvent = new ErrorEvent();
            string     headerLine;
            int        length = 0;

            do
            {
                headerLine = ReadLine();
                Match headerMatch = Regex.Match(headerLine, HEADER_PATTERN);
                if (headerMatch.Success)
                {
                    string headerName  = headerMatch.Groups[1].Value;
                    string headerValue = headerMatch.Groups[2].Value;
                    switch (headerName)
                    {
                    case "name":
                        errorEvent.Name = headerValue;
                        break;

                    case "content-length":
                        length = Int32.Parse(headerValue);
                        break;

                    case "summary":
                        errorEvent.Summary = headerValue;
                        break;

                    default:
                        throw new InvalidOperationException(String.Format("Invalid header - '{0}:{1}' while parsing ERROR event", headerName, headerValue));
                    }
                }
            } while (headerLine != String.Empty);

            if (length >= 0)
            {
                char[] description = ReadBlock(length);
                errorEvent.Description = new String(description);
            }

            return(errorEvent);
        }
Exemplo n.º 9
0
    //Note:当下载的文件数据大于2G时,该int类型的参数将会数据溢出,所以先自己通过响应头来获取长度,获取不到再使用参数的方式
    protected override void ReceiveContentLength(int contentLength)
    {
        string contentLengthStr = _unityWebRequest.GetResponseHeader("Content-Length");

        if (contentLengthStr != null && !"".Equals(contentLengthStr))
        {
            try
            {
                _totalFileSize = long.Parse(contentLengthStr);
            }
            catch (System.FormatException e)
            {
                UnityEngine.Debug.LogWarning("获取文件长度失败,contentLengthStr:" + contentLengthStr + "," + e.Message);
                _totalFileSize = contentLength;
            }
            catch (System.Exception e)
            {
                UnityEngine.Debug.LogWarning("获取文件长度失败,contentLengthStr:" + contentLengthStr + "," + e.Message);
                _totalFileSize = contentLength;
            }
        }
        else
        {
            _totalFileSize = contentLength;
        }
        //这里拿到的下载大小是待下载的文件大小,需要加上本地已下载文件的大小才等于总大小
        if (_useRange)
        {
            _totalFileSize += _localFileSize;
        }

        if (_useRange && _fileSize != -1 && _totalFileSize != _fileSize)
        {
            ErrorEvent?.Invoke();
        }
        else
        {
            _lastTime     = UnityEngine.Time.time;
            _lastDataSize = _curFileSize;
            StartDownloadEvent?.Invoke();
        }
    }
Exemplo n.º 10
0
        /// <summary>
        /// 异步执行C#函数,完成后回调
        /// </summary>
        /// <param name="ass">程序集</param>
        /// <param name="type">类.方法</param>
        /// <param name="data">传入数据</param>
        /// <returns>回调的编号</returns>
        public int AsyncRun(string ass, string type, params object[] data)
        {
            int id = asyncId++;

            if (asyncId > int.MaxValue - 100)
            {
                asyncId = 0;
            }
            try
            {
                System.Reflection.Assembly asm = System.Reflection.Assembly.Load(ass);
                string className = type.Substring(0, type.LastIndexOf("."));
                Type   t         = asm.GetType(className);
                (new Thread(() =>
                {
                    try
                    {
                        string method = type.Substring(type.LastIndexOf(".") + 1,
                                                       type.Length - type.LastIndexOf(".") - 1);
                        List <Type> ft = new List <Type>();
                        for (int i = 0; i < data.Length; i++)
                        {
                            ft.Add(data[i].GetType());
                        }
                        object r = t.GetMethod(method, ft.ToArray()).Invoke(null, data);
                        addTask(id, "async", r);
                    }
                    catch (Exception e)
                    {
                        ErrorEvent?.Invoke(this, e.Message);
                        addTask(id, "asyncFail", e.Message);
                    }
                })).Start();
            }
            catch (Exception e)
            {
                ErrorEvent?.Invoke(this, e.Message);
                return(-1);
            }

            return(id);
        }
Exemplo n.º 11
0
        public async Task SendMany <T>(List <Message <T> > messages)
        {
            var request = new AwsModel.SendMessageBatchRequest
            {
                Entries  = messages.Select(m => { return(new AwsModel.SendMessageBatchRequestEntry(m.Id.ToString(), JsonConvert.SerializeObject(m.Body))); }).ToList(),
                QueueUrl = Url
            };

            var response = await Client.AwsClient.SendMessageBatchAsync(request);

            foreach (var success in response.Successful)
            {
                SuccessEvent?.Invoke(true, $"Message Sent Success => Message id : {success.MessageId} - Message MD5 Body: {success.MD5OfMessageBody}");
            }

            foreach (var failed in response.Failed)
            {
                ErrorEvent?.Invoke(false, $"Message Sent Error => Message id : {failed.Id} - Message Body: {failed.Message}");
            }
        }
Exemplo n.º 12
0
 public void Initialize(
     string staminaNamespaceName,
     EzStaminaModel staminaModel,
     Func <IEnumerator, Coroutine> startCoroutine,
     Action <Coroutine> stopCoroutine,
     GetStaminaEvent onGetStamina,
     RecoverStaminaEvent onRecoverStamina,
     ConsumeStaminaEvent onConsumeStamina,
     ErrorEvent onError
     )
 {
     _staminaNamespaceName = staminaNamespaceName;
     _staminaModel         = staminaModel;
     _startCoroutine       = startCoroutine;
     _stopCoroutine        = stopCoroutine;
     _onGetStamina         = onGetStamina;
     _onRecoverStamina     = onRecoverStamina;
     _onConsumeStamina     = onConsumeStamina;
     _onError = onError;
 }
Exemplo n.º 13
0
 public Entities.Product GetProductByID(int ID)
 {
     Entities.Product Result;
     if (ID > 0)
     {
         var D = Factory.GetDALProduct();
         Result = D.GetProductByID(ID);
         if (Result == null && ErrorEvent != null)
         {
             ErrorEvent(this, new ErrorEventArgs("Producto no encontrado"));
         }
         ErrorEvent?.Invoke(this, new ErrorEventArgs(Factory.GetIdentity(D)));
     }
     else
     {
         ErrorEvent?.Invoke(this, new ErrorEventArgs("El ID debe ser mayor que cero"));
         Result = null;
     }
     return(Result);
 }
Exemplo n.º 14
0
    private void ReceiveCallback(IAsyncResult ar)
    {
        var state = ar.AsyncState as SocketState;

        try
        {
            if (state != null)
            {
                int receiveLen = state.Self.EndReceiveFrom(ar, ref state.RemotePoint);
                if (receiveLen > 0)
                {
                    byte[] receivedData = new byte[receiveLen];
                    Array.Copy(state.Buffer, 0, receivedData, 0, receiveLen);
                    state.Buffer = receivedData;

                    //string str = System.Text.Encoding.UTF8.GetString(receivedData);
                    //Debug.Log(str);
                    //SqlHelper.Insatance.GetSqlConn();

                    Debug.Log($"接收数据长度:{receivedData.Length}");

                    Debug.Log(BitConverter.ToString(receivedData));
                    GPSInfosManager.Insatance.praseMessage(receivedData);

                    state.ReceivedTime = DateTime.Now;
                    ReceivedDataEvent?.Invoke(state);
                }
            }
        }
        catch (Exception error)
        {
            ErrorEvent?.Invoke(error.Message, state?.RemotePoint);
        }
        finally
        {
            if (state != null)
            {
                BeginReceive();
            }
        }
    }
Exemplo n.º 15
0
        public static IEnumerator SetForm(
            Client client,
            GameSession session,
            string formationNamespaceName,
            EzMoldModel moldModel,
            int index,
            List <EzSlotWithSignature> slots,
            string signatureKeyId,
            GetFormEvent onGetForm,
            UpdateFormEvent onUpdateForm,
            ErrorEvent onError
            )
        {
            AsyncResult <EzSetFormResult> result = null;

            yield return(client.Formation.SetForm(
                             r =>
            {
                result = r;
            },
                             session,
                             formationNamespaceName,
                             moldModel.Name,
                             index,
                             slots,
                             signatureKeyId
                             ));

            if (result.Error != null)
            {
                onError.Invoke(
                    result.Error
                    );
                yield break;
            }

            var form = result.Result.Item;

            onUpdateForm.Invoke(moldModel, index, form);
            onGetForm.Invoke(moldModel, index, form);
        }
Exemplo n.º 16
0
 private IDEEvent Anonymize(IDEEvent e)
 {
     try
     {
         var anonymizedEvent = _anonymizer.Anonymize(e);
         // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
         anonymizedEvent.GetHashCode();
         return(anonymizedEvent);
     }
     catch (Exception ex)
     {
         try
         {
             var errorEvent = new ErrorEvent
             {
                 TriggeredAt    = e.TriggeredAt,
                 TerminatedAt   = e.TerminatedAt,
                 Duration       = e.Duration,
                 IDESessionUUID = e.IDESessionUUID,
                 ActiveDocument = e.ActiveDocument,
                 ActiveWindow   = e.ActiveWindow,
                 Id             = e.Id,
                 KaVEVersion    = e.KaVEVersion,
                 TriggeredBy    = e.TriggeredBy,
                 Content        = string.Format("An error occured during anonymization of {0}.", e.GetType()),
                 StackTrace     = ex.StackTrace.Split('\n')
             };
             var anonymizedEvent = _anonymizer.Anonymize(errorEvent);
             // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
             anonymizedEvent.GetHashCode();
             return(anonymizedEvent);
         }
         catch
         {
             return(new ErrorEvent
             {
                 Content = string.Format("An unrecoverable error occured during anonymization of {0}.", e.GetType()),
             });
         }
     }
 }
Exemplo n.º 17
0
 /// <summary>
 /// 跑一遍任务池子里的任务
 /// </summary>
 private void runTask()
 {
     lock (taskLock)
         while (toRun.Count > 0)
         {
             try
             {
                 LuaTaskData task;
                 toRun.TryTake(out task);                                             //取出来一个任务
                 lua.GetFunction("sys.tiggerCB").Call(task.id, task.type, task.data); //跑
             }
             catch (Exception e)
             {
                 ErrorEvent?.Invoke(lua, e.Message);
             }
             if (stop)//任务停了
             {
                 return;
             }
         }
 }
Exemplo n.º 18
0
 public void MakeDirectory(string url, TaskEvent finished = null, ErrorEvent error = null)
 {
     try
     {
         //Console.WriteLine("uri full path:" + accessUrlBase + url);
         FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(accessUrlBase + url);
         ftpReq.Credentials = icr;
         ftpReq.Method      = WebRequestMethods.Ftp.MakeDirectory;
         FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse();
         ftpRes.Close();
         finished?.Invoke();
     }
     catch (WebException e)
     {
         error?.Invoke(((FtpWebResponse)e.Response).StatusDescription);
     }
     catch (Exception e)
     {
         error?.Invoke(e.Message);
     }
 }
Exemplo n.º 19
0
 public string LoadTextContent(Encoding encoding)
 {
     try
     {
         if (IsExist())
         {
             return(File.ReadAllText(FullName, encoding));
         }
         else
         {
             ReadFileNotFined?.Invoke(this, "Файл, который вы собирались прочитать, не найден по пути: " + FullName);
             return(null);
         }
     }
     catch (System.Exception ex)
     {
         ErrorEvent?.Invoke(this, ex.Message);
         System.Console.WriteLine(ex.Message);
         return(null);
     }
 }
Exemplo n.º 20
0
        public static IEnumerator GetItemSetWithSignature(
            Client client,
            GameSession session,
            string inventoryNamespaceName,
            string inventoryModelName,
            string itemModelName,
            string itemSetName,
            string signatureKeyId,
            GetItemSetWithSignatureEvent onGetItemSetWithSignature,
            ErrorEvent onError
            )
        {
            {
                AsyncResult <EzGetItemWithSignatureResult> result = null;
                yield return(client.Inventory.GetItemWithSignature(
                                 r => { result = r; },
                                 session,
                                 inventoryNamespaceName,
                                 inventoryModelName,
                                 itemModelName,
                                 signatureKeyId,
                                 itemSetName
                                 ));

                if (result.Error != null)
                {
                    onError.Invoke(
                        result.Error
                        );
                    yield break;
                }

                onGetItemSetWithSignature.Invoke(
                    result.Result.Items.First().ItemSetId,
                    signatureKeyId,
                    result.Result.Body,
                    result.Result.Signature
                    );
            }
        }
Exemplo n.º 21
0
        public static IEnumerator Consume(
            Client client,
            GameSession session,
            string inventoryNamespaceName,
            string inventoryModelName,
            string itemModelName,
            int consumeValue,
            ConsumeEvent onConsume,
            ErrorEvent onError,
            string itemSetName = null
            )
        {
            AsyncResult <EzConsumeResult> result = null;

            yield return(client.Inventory.Consume(
                             r =>
            {
                result = r;
            },
                             session,
                             inventoryNamespaceName,
                             inventoryModelName,
                             itemModelName,
                             consumeValue,
                             itemSetName
                             ));

            if (result.Error != null)
            {
                onError.Invoke(
                    result.Error
                    );
                yield break;
            }

            var inventory = result.Result.Inventory;
            var itemSets  = result.Result.Items;

            onConsume.Invoke(inventory, itemSets, consumeValue);
        }
Exemplo n.º 22
0
        private static void EventManagerOnErrorEventReceive(ErrorEvent obj)
        {
            if (Settings.Interactive)
            {
                Console.Write($"Encountered Error Event: {obj.EventKey} Do you want to continue? [Y/n]");

                if (Console.ReadKey().Key == ConsoleKey.Y)
                {
                    throw new EventManagerException($"[{obj.EventKey}] {obj.Message}");
                }

                return;
            }

            if (obj.CanContinue ||
                Settings.IgnoredEvents.Contains(obj.EventKey))
            {
                return;
            }

            throw new EventManagerException($"[{obj.EventKey}] {obj.Message}");
        }
Exemplo n.º 23
0
 /// <summary>
 /// 尝试查询数据库中的数据
 /// </summary>
 /// <typeparam name="T">查询的数据类型</typeparam>
 /// <param name="factory">数据库工厂</param>
 /// <param name="command">数据库操作命令</param>
 /// <param name="results">查询到的数据集合</param>
 /// <returns>查询成功返回true, 否则返回false</returns>
 public static bool TryQuery<T>(this DBFactory factory, DBCommand command, out List<T> results)
 {
     try
     {
         if (command == null)
         {
             results = new List<T>();
             return false;
         }
         using (factory)
         {
             results = factory.Connection.Query<T>(command.CommandText, command.CommandParameter, factory.Transaction).AsList();
             return true;
         }
     }
     catch (Exception ex)
     {
         ErrorEvent?.Invoke(ex);
         results = new List<T>();
         return false;
     }
 }
Exemplo n.º 24
0
        public static IEnumerator Withdraw(
            Client client,
            GameSession session,
            string moneyNamespaceName,
            EzWallet wallet,
            int value,
            bool paidOnly,
            WithdrawEvent onWithdraw,
            GetWalletEvent onGetWallet,
            ErrorEvent onError
            )
        {
            AsyncResult <EzWithdrawResult> result = null;

            yield return(client.Money.Withdraw(
                             r =>
            {
                result = r;
            },
                             session,
                             moneyNamespaceName,
                             wallet.Slot,
                             value,
                             paidOnly
                             ));

            if (result.Error != null)
            {
                onError.Invoke(
                    result.Error
                    );
                yield break;
            }

            wallet = result.Result.Item;

            onWithdraw.Invoke(wallet, value);
            onGetWallet.Invoke(wallet);
        }
Exemplo n.º 25
0
        public override void Handle(ICommand item)
        {
            var createDepositCommand = (CreateDepositCommand)item;
            var accountId            = createDepositCommand.AccountId;

            if (accountId.Equals(Guid.Empty))
            {
                var errorEvent = new ErrorEvent(Guid.NewGuid(), Guid.Empty, createDepositCommand, "Account Guid empty");
                _eventPublisher.Publish(errorEvent);
                return;
            }

            var account = _accountAggregateService.Load(accountId);

            if (account.Guid.Equals(Guid.Empty))
            {
                var errorEvent = new ErrorEvent(Guid.NewGuid(), accountId, account, "Account not found");
                _eventPublisher.Publish(errorEvent);
                return;
            }

            var depositGuid = GetDepositGuid();

            var createDepositEvent = new CreateDepositEvent {
                ItemGuid    = depositGuid,
                AccountGuid = accountId
            };

            _eventPublisher.Publish(createDepositEvent);

            var addDepositToAccountEvent = new AddDepositToAccountEvent
            {
                ItemGuid  = accountId,
                DepositId = depositGuid
            };

            _eventPublisher.Publish(addDepositToAccountEvent);
        }
Exemplo n.º 26
0
 /// <summary>
 /// 添加队列
 /// </summary>
 /// <param name="queueName">队列名称</param>
 /// <param name="action">接收到数据的处理</param>
 /// <returns></returns>
 public bool TryAddQueue(string queueName, Action <byte[]> action)
 {
     try
     {
         if (Queues.ContainsKey(queueName))
         {
             throw new Exception($"已存在队列【{queueName}】");
         }
         if (conn == null)
         {
             conn = factory.CreateConnection();
         }
         if (!conn.IsOpen)
         {
             throw new Exception($"连接未打开【{HostName}】【{Port}】【{UserName}】【{Password}】");
         }
         var queue = new QueueParameter();
         queue.Name       = queueName;
         queue.OnReceived = action;
         queue.Channel    = conn.CreateModel();
         queue.Consumer   = new EventingBasicConsumer(queue.Channel);
         queue.Channel.BasicQos(0, 1, false);//告诉broker,同一时间只处理一个消息
         queue.Consumer           = new EventingBasicConsumer(queue.Channel);
         queue.Consumer.Received += (obj, arg) =>
         {
             queue.OnReceived?.Invoke(arg.Body.ToArray());
             queue.Channel.BasicAck(arg.DeliveryTag, false);
         };
         queue.Channel.BasicConsume(queue.Name, false, queue.Consumer);//告诉broker,发送消息之后,消息暂时不要删除,等消费者处理完成再说
         Queues.Add(queue.Name, queue);
         return(Queues.ContainsKey(queueName) && conn.IsOpen);
     }
     catch (Exception ex)
     {
         ErrorEvent?.Invoke(ex);
         return(false);
     }
 }
Exemplo n.º 27
0
        private void Adapter(List <FileInfo> files)
        {
            files.ForEach(f =>
            {
                string nameWithoutExtension = Path.GetFileNameWithoutExtension(f.Name);
                List <string> sns           = nameWithoutExtension.Split("-".ToCharArray()).ToList();

                if (sns.Count > 2)
                {
                    m_abnormalFile.Add(nameWithoutExtension);
                    return;
                }

                sns.ForEach(s =>
                {
                    if (string.IsNullOrEmpty(s))
                    {
                        sns.Remove(s);
                    }
                    ;
                });

                FileInfomation info = new FileInfomation()
                {
                    FileInfo             = f,
                    SourcePath           = sourcePath,
                    DestinationPath      = desPath,
                    NameWithoutExtension = nameWithoutExtension,
                    FileType             = (FileType)Enum.Parse(typeof(FileType), Path.GetExtension(f.Name).ToLower().Replace(".", "")),
                    Performers           = new string[] { sns[1].Trim() },
                    Title = sns[0].Trim(),
                };

                m_fileInfomation.Add(info);
            });

            ErrorEvent?.Invoke(m_abnormalFile);
        }
Exemplo n.º 28
0
        private void raiseErrorEvent(ErrorEvent evt)
        {
            string evtCode    = evt.getEvtCode();
            string evtMessage = evt.getEvtMsg();

            evtMessage = evtMessage.Replace("\n", "");

            switch (evtCode)
            {
            case EVENT_TYPE.ON_CONNECTION:
                logwrite.write("raiseEvent", ":::::::::::::::::::::::::::::::::::: GetEventOnConnection ::::::::::::::::::::::::::::::::::::");
                logwrite.write("raiseEvent", evtMessage);
                logwrite.write("raiseEvent", "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                GetEventOnConnection(evt.getCurFinesseIP(), evt.getCurAemsIP(), evt.getCurIspsIP(), evtMessage);
                break;

            case EVENT_TYPE.ON_DISCONNECTION:
                logwrite.write("raiseEvent", ":::::::::::::::::::::::::::::::::::: GetEventOnDisConnection ::::::::::::::::::::::::::::::::::::");
                logwrite.write("raiseEvent", evtMessage);
                logwrite.write("raiseEvent", "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                GetEventOnDisConnection(evt.getCurFinesseIP(), evt.getCurAemsIP(), evt.getCurIspsIP(), evtMessage);
                break;

            case EVENT_TYPE.ERROR:
                logwrite.write("raiseEvent", ":::::::::::::::::::::::::::::::::::: GetEventOnError ::::::::::::::::::::::::::::::::::::");
                logwrite.write("raiseEvent", evtMessage);
                logwrite.write("raiseEvent", "ERROR TYPE : " + evt.getErrorType() + " , ERROR MESSAGE : " + evt.getErrorMessage());
                logwrite.write("raiseEvent", "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                GetEventOnCallError(evtMessage);
                break;

            default:
                logwrite.write("raiseEvent", ":::::::::::::::::::::::::::::::::::: UNKWON EVENT ::::::::::::::::::::::::::::::::::::");
                logwrite.write("raiseEvent", evtMessage);
                logwrite.write("raiseEvent", "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                break;
            }
        }
Exemplo n.º 29
0
 public object LoadBinaryFormatter()
 {
     try
     {
         var formatter = new BinaryFormatter();
         using (FileStream fs = new FileStream(FullName, FileMode.OpenOrCreate))
         {
             if (fs.Length > 0)
             {
                 return(formatter.Deserialize(fs));
             }
         }
     }
     catch (SerializationException)
     {
         throw;
     }
     catch (Exception ex)
     {
         ErrorEvent?.Invoke(this, ex.Message);
     }
     return(null);
 }
Exemplo n.º 30
0
 public FixedLengthLogFile(string aFileName,
                           ushort aLineLength       = 80,
                           ushort aMaxSize          = 0,
                           bool aDate               = false,
                           bool aTime               = false,
                           bool aFileRollOver       = false,
                           ErrorEvent aOnErrorEvent = null,
                           ReadWritePosition aOnReadWritePosition = null)
     : base(aFileName)
 {
     if (aLineLength < 20)
     {
         throw new InvalidDataException("LineLength must be greater than 20");
     }
     LineLenght           = aLineLength;
     MaxSize              = aMaxSize;
     IncludeDate          = aDate;
     IncludeTime          = aTime;
     FileRollOver         = aFileRollOver;
     FOnErrorEvent        = aOnErrorEvent;
     FOnReadWritePosition = aOnReadWritePosition;
     this.OnErrorEvent   += new ErrorHandlerDelegate(ErrorHandler);
 }
Exemplo n.º 31
0
        private void ImageProcessorOnCameraErrorEvent(object sender, CameraEventBase cameraErrorInfo)
        {
            switch (cameraErrorInfo.EventType)
            {
            case CameraEventType.Shutdown:
                TakingPicture = false;
                //_dialogService.ShowInfo(cameraErrorInfo.Message);
                Dispose();
                break;

            case CameraEventType.Error:
                TakingPicture = false;

                ErrorEvent ev = cameraErrorInfo as ErrorEvent;
                if (ev != null && ev.ErrorCode == ReturnValue.TakePictureAutoFocusNG)
                {
                    // _dialogService.ShowInfo("Не удалось сфокусироваться. Пожалуйста, повторите попытку.");
                    Dispose();
                    Initialize();
                }
                break;
            }
        }
Exemplo n.º 32
0
 public static void HandleLoggingException(Exception ex, int contactID, string source, String ip, bool sendEmail)
 {
     string message = null;
     string stackTrace = null;
     try
     {
         var loggingEx = new ApplicationException("Unable to log exception to the database", ex);               
         BuildStrings(loggingEx, out message, out stackTrace);
     }
     catch
     {
         message = "Unable to log exception to the database: " + ex.Message;
         stackTrace = ex.Source;
     }
     finally
     {   
         if (sendEmail)
         {
             ErrorEvent errorEvent = new ErrorEvent(0, contactID, null, message, null, null, source, stackTrace, null, ip);
             //ErrorEventEmailer.SendEmail(errorEvent, "V2 Logging Exception");
         }
         SystemApplictionEventLoggingUtil.WriteError(source, message + "\n\nStackTrace:\n" + stackTrace);            
     }
 }
Exemplo n.º 33
0
 void MP_onErrorEvent(object sender, ErrorEvent e)
 {
     Invoke(new MethodInvoker(
                  delegate()
                  {
                      try
                      {
                          Log(e.Message);
                      }
                      catch (Exception err)
                      {
                          MessageBox.Show(err.Message);
                      }
                  }));
 }
Exemplo n.º 34
0
 private void OnError(ErrorEvent e)
 {
     if (onErrorEvent != null)
         onErrorEvent(this, e);
 }