Handle() публичный статический Метод

public static Handle ( string message, Exception, exception ) : void
message string
exception Exception,
Результат void
Пример #1
0
 public void Add(TEntity contact)
 {
     try
     {
         _storage.Add(contact);
     }
     catch (Exception e)
     {
         _exceptionHandler.Handle(e);
     }
 }
        public void HandlingException_LogsExceptionOnce()
        {
            // Arrange
            var exception = new Exception("Hello Test");

            // Act
            _sut.Handle(exception);

            // Assert
            _loggingServiceMock.Verify(f => f.LogException(exception), Times.Once);
        }
Пример #3
0
        /// <summary>
        ///     Creates a sub key to local intranet and sets its value
        /// </summary>
        /// <param name="rootPath">Root path like 'server' for example</param>
        public void CreateLocalIntranet(string rootPath)
        {
            try
            {
                var sysEnv = new SysEnvironment();
                sysEnv.Values = Values;

                // Creates a sub key in the CurrentUser and then set a new value
                var registryPath = Path.Combine(new Constants().LocalIntranetRegPath, rootPath);
                var key          = Registry.CurrentUser.CreateSubKey(registryPath, RegistryKeyPermissionCheck.ReadWriteSubTree);
                if (key == null)
                {
                    throw new Exception("Registry does not exist");
                }
                key.SetValue(new Constants().LocalIntranetKeyName, 00000001);

                // Creates a sub key in the Users and then set a new value
                var regPath = Path.Combine(sysEnv.GetUserSid(Environment.UserName), new Constants().LocalIntranetRegPath);

                var key2 = Registry.Users.CreateSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree);
                if (key2 == null)
                {
                    throw new Exception("Registry does not exist");
                }
                key2.SetValue(new Constants().LocalIntranetKeyName, 00000001);
            }
            catch (Exception exception)
            {
                var initEx = new ExceptionHandler();
                initEx.Values = Values;
                initEx.Handle(exception, MethodBase.GetCurrentMethod(), true);
            }
        }
Пример #4
0
 /// <summary>
 /// di tu ceng = eyemap
 /// </summary>
 private void InitializeEyeMap()
 {
     MapObjects2.DataConnection mapCon   = new MapObjects2.DataConnectionClass();
     MapObjects2.MapLayer       EyeLayer = null;
     try
     {
         mapCon.Database = Path.GetDirectoryName(Application.ExecutablePath) + "\\shaps\\";
         for (int i = 0; i < mapLayer.m_layers.Length; i++)
         {
             if (mapLayer.m_layers[i].typeName == "地图层")
             {
                 EyeLayer              = new MapObjects2.MapLayerClass();
                 EyeLayer.GeoDataset   = mapCon.FindGeoDataset(mapLayer.m_layers[i].dtFile);
                 EyeLayer.Symbol.Color = System.Convert.ToUInt32(mapLayer.m_layers[i].dtColor);
                 EyeLayer.Symbol.Size  = 1;
                 if (EyeLayer.shapeType == MapObjects2.ShapeTypeConstants.moShapeTypePolygon)
                 {
                     EyeLayer.Symbol.OutlineColor = System.Convert.ToUInt32(mapLayer.m_layers[i].dtColor);
                 }
                 mapEye.Layers.Add(EyeLayer);
                 mapEye.Refresh();
             }
         }
     }
     catch (Exception ex)
     {
         //MessageBox.Show("加载图层失败,请重新起动软件!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
         ExceptionHandler.Handle("加载图层失败,请重新起动软件!", ex);
     }
 }
Пример #5
0
        //		public delegate void ContextMenuEventHandler(object sender,string name,int type);
        //		public event ContextMenuEventHandler Menu_XDClick;

        #region InitializeGis
        /// <summary>
        /// load layer info from .\mapLayers.mdb to Info::m_layers
        /// </summary>
        private void LoadMapInfo()
        {
            try
            {
                OleDbDataAdapter acs = new OleDbDataAdapter("SELECT * FROM mapInfo", mapLayer.GetAccessCon());
                ds = new DataSet();
                acs.Fill(ds, "layersInfo");
                int i = ds.Tables["layersInfo"].Rows.Count;
                mapLayer.m_layers = null;
                mapLayer.m_layers = new LayerInfo[i];

                for (int j = 0; j < i; j++)
                {
                    mapLayer.m_layers[j].dtName   = ds.Tables["layersInfo"].Rows[j]["Layer"].ToString();
                    mapLayer.m_layers[j].dtFile   = ds.Tables["layersInfo"].Rows[j]["LayerName"].ToString();
                    mapLayer.m_layers[j].dtScale  = System.Convert.ToDouble(ds.Tables["layersInfo"].Rows[j]["LayerScale"]);
                    mapLayer.m_layers[j].dtSize   = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LayerSize"]);
                    mapLayer.m_layers[j].dtColor  = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LayerColor"]);
                    mapLayer.m_layers[j].dtSymbol = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LayerSymbol"]);

                    mapLayer.m_layers[j].bzScale = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LabelScale"]);
                    mapLayer.m_layers[j].bzSize  = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LabelSize"]);
                    mapLayer.m_layers[j].bzColor = System.Convert.ToInt64(ds.Tables["layersInfo"].Rows[j]["LabelColor"]);

                    mapLayer.m_layers[j].typeName = ds.Tables["layersInfo"].Rows[j]["TypeName"].ToString();
                }
                //				STAT.X=47699;
                //				STAT.Y=31331;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("加载图层信息失败,请重新起动软件!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                ExceptionHandler.Handle("加载图层信息失败,请重新起动软件!", ex);
            }
        }
Пример #6
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            if (!TestNet)
            {
                return;
            }
            string loginName     = txtUserName.Text.Trim().ToUpper();
            string loginPassWord = txtPwd.Text.Trim().ToUpper();
            bool   isLogin       = false;

            try
            {
                isLogin = Login(loginName, loginPassWord);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
            if (isLogin)
            {
                //成功返回
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                DialogResult dialogResult = XtraMessageBox.Show("您输入的密码或用户名有误,请重新输入。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtPwd.Focus();
                this.DialogResult = DialogResult.None;
            }

            this.Cursor = Cursors.Default;
        }
Пример #7
0
        private static void runBootstrapper()
        {
            AppDomain.CurrentDomain.UnhandledException += appDomainUnhandledException;
            try
            {
                var bootstrapper = new Bootstrapper();
                bootstrapper.Run();

                var app = Application.Current as App;
                if (app != null)
                {
                    var shell = app.MainWindow as Shell;
                    if (shell != null)
                    {
                        shell.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                     (Action)(() =>
                                                              shell.TryOpenFile(app.ParameterOpenFilePath)
                                                              ));
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex, true, null);
            }
        }
Пример #8
0
        /// <summary>
        ///     Gets a generic List<string> from an xml.
        /// </summary>
        /// <param name="xml">Xml</param>
        /// <param name="node">The descendants value that we're going to get</param>
        /// <returns></returns>
        public List <string> GetListFromXml(string xml, string node)
        {
            try
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(xml))
                {
                    /* Loads the xml file */
                    var doc = XDocument.Parse(xml);

                    /* For each value that we're getting,
                     * it's been added to the generic List<string>
                     */
                    foreach (var myNode in doc.Descendants(node))
                    {
                        list.Add(myNode.Value);
                    }

                    return(list);
                }
            }
            catch (Exception exception)
            {
                var initEx = new ExceptionHandler();
                initEx.Values = Values;
                initEx.Handle(exception, MethodBase.GetCurrentMethod(), true);
            }
            return(null);
        }
Пример #9
0
        public async Task DownloadPosts()
        {
            try
            {
                using (var service = Config.GetMobileService())
                {
                    var posts = await service.GetPosts();

                    foreach (var post in posts)
                    {
                        var foundGroup = SpottedCache.Groups.FirstOrDefault(x => x.Id == post.Group?.Id);
                        if (foundGroup == null)
                        {
                            post.Group = new BasicGroup()
                            {
                                Name = "Spotted"
                            };
                        }
                        else
                        {
                            post.Group = foundGroup;
                        }
                    }

                    posts = posts.OrderByDescending(x => x.Created).ToList();
                    Posts = new ObservableCollection <Post>(posts);
                }
            }
            catch (Exception e)
            {
                await ExceptionHandler.Handle(e);
            }
        }
Пример #10
0
 private void operRoomContent_DoubleClick(object sender, EventArgs e)
 {
     try
     {
         if (!_canSelect)
         {
             return;
         }
         OperationRoomContent operationRoomContent = sender as OperationRoomContent;
         if (ExtendApplicationContext.Current.AppType == ApplicationType.PACU)
         {
             if (operationRoomContent != null)
             {
                 if (string.IsNullOrEmpty(operationRoomContent.PatientID))
                 {
                     _selectedOperationRoomContent = operationRoomContent;
                     if (ParentForm != null)
                     {
                         ParentForm.DialogResult = DialogResult.OK;
                     }
                     RefreshRoom(operationRoomContent.RoomNo, ExtendApplicationContext.Current.PatientContextExtend.PatientID, ExtendApplicationContext.Current.PatientContextExtend.VisitID,
                                 ExtendApplicationContext.Current.PatientContextExtend.OperID);
                 }
             }
         }
     }
     catch (Exception err)
     {
         ExceptionHandler.Handle(err);
     }
 }
Пример #11
0
        public void OperationRoomPandectLoad(string bedType)
        {
            try
            {
                pRoomPandect.Controls.Clear();
                OperationRoomContentList.Clear();
                _bedType     = bedType;
                pacuRoomList = comnDictRepository.GetOperatingRoomList(bedType).Data;
                if (pacuRoomList != null && pacuRoomList.Count > 0)
                {
                    pacuRoomList = pacuRoomList.Where(x => x.DEPT_CODE == ExtendApplicationContext.Current.OperRoom).ToList();
                }

                if (pacuRoomList.Count <= 12)
                {
                    panelBotton.Visible = false;
                }
                else
                {
                    btnUp.Enabled = false;
                }
                InitOperationRoomContentList();
                GetPacuInfo();
            }
            catch (Exception ex)
            {
                Logger.Error("OperationRoomPandectLoad", ex);
                ExceptionHandler.Handle(ex);
            }
        }
Пример #12
0
        public void DeleteCamera(Camera camera, EventHandler <AsyncWorkerCallbackEventArgs <bool> > callback)
        {
            if (camera == null)
            {
                throw new ArgumentNullException("camera");
            }

            try
            {
                AsyncWorkerHandle <bool> handle = AsyncWorkerHelper.DoWork <bool>(
                    delegate(object sender, DoWorkEventArgs e)
                {
                    DeleteCameraRequest request = new DeleteCameraRequest();
                    request.CameraId            = camera.Id;

                    DeleteCameraResponse response =
                        ServiceProvider.GetService <IDeviceConnectorService, IDeviceConnectorCallbackService>(
                            ViewModelLocator.ServiceClient,
                            ViewModelLocator.SelectedService.HostName,
                            ViewModelLocator.SelectedService.Uri.ToString()
                            ).DeleteCamera(request);

                    e.Result = true;
                },
                    null, callback);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
        }
Пример #13
0
        private Dictionary <string, string> GetMsgNoticInfo()
        {
            Dictionary <string, string> msg_dict = new Dictionary <string, string>();

            try
            {
                QueryParams queryParams = new QueryParams();
                queryParams.AddQueryDefines("OperDept", ExtendAppContext.Current.OperDeptCode);
                queryParams.AddQueryDefines("Type", 2);
                DataTable NoticMsgTable = DataOperator.HttpWebApi <DataResult>(ApiUrlEnum.GetNoticeMsgData, queryParams).ToDataTable();

                if (NoticMsgTable.Rows.Count > 0)
                {
                    foreach (DataRow dr in NoticMsgTable.Rows)
                    {
                        if (!msg_dict.ContainsKey(dr["ID"].ToString()))
                        {
                            msg_dict.Add(dr["ID"].ToString(), dr["MSG"].ToString() + "," + dr["COUNTS"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
            return(msg_dict);
        }
Пример #14
0
        private void HandleLastError(Action nextStep)
        {
            using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                bool fileExist = isoFile.FileExists(ErrorFile);

                if (fileExist)
                {
                    using (IsolatedStorageFileStream fileStream = isoFile.OpenFile(ErrorFile, FileMode.Open))
                    {
                        object report;
                        var    serializer = new XmlSerializer(typeof(Log));
                        try
                        {
                            report = serializer.Deserialize(fileStream);
                        }
                        catch (XmlException)
                        {
                            fileStream.Position = 0;
                            using (var reader = new StreamReader(fileStream))
                            {
                                report = reader.ReadToEnd();
                            }
                        }

                        ExceptionHandler.Handle(report, nextStep);
                    }
                }
                else
                {
                    nextStep();
                }
            }
        }
Пример #15
0
        public void SearchCameras(string searchText, EventHandler <AsyncWorkerCallbackEventArgs <IList <Camera> > > callback)
        {
            try
            {
                AsyncWorkerHandle <IList <Camera> > handle = AsyncWorkerHelper.DoWork <IList <Camera> >(
                    delegate(object sender, DoWorkEventArgs e)
                {
                    List <Camera> matches = new List <Camera>();

                    foreach (var item in GetCamerasSync())
                    {
                        if (string.IsNullOrEmpty(searchText) || item.Name.Contains(searchText))
                        {
                            matches.Add(item as Camera);
                        }
                    }

                    e.Result = matches;
                },
                    null, callback);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
        }
Пример #16
0
        /// <summary>
        /// 发送报文至指定的客户端
        /// </summary>
        /// <param name="tcpClient">客户端</param>
        /// <param name="datagram">报文</param>
        public void SyncSend(TcpClient tcpClient, byte[] datagram)
        {
            GuardRunning();

            if (tcpClient == null)
            {
                throw new ArgumentNullException("tcpClient");
            }

            if (datagram == null)
            {
                throw new ArgumentNullException("datagram");
            }

            try
            {
                NetworkStream stream = tcpClient.GetStream();
                if (stream.CanWrite)
                {
                    stream.Write(datagram, 0, datagram.Length);
                }
            }
            catch (ObjectDisposedException ex)
            {
                ExceptionHandler.Handle(ex);
            }
        }
Пример #17
0
 /// <summary>
 ///     Modify UAC Level based on the parameters given
 /// </summary>
 /// <param name="enableLua">("1" TO DECAY) ("1" FOR RAISE)</param>
 /// <param name="consentPromptBehaviorAdmin">("0" TO DECAY) ("5" FOR RAISE)</param>
 /// <param name="consentPromptBehaviorUser">("0" TO DECAY) ("3" FOR RAISE)</param>
 /// <param name="promptOnSecureDesktop">("0" TO DECAY) ("1" FOR RAISE)</param>
 public void Modify(int enableLua, int consentPromptBehaviorAdmin, int consentPromptBehaviorUser,
                    int promptOnSecureDesktop)
 {
     try
     {
         var process   = new System.Diagnostics.Process();
         var startInfo = new ProcessStartInfo
         {
             WindowStyle = ProcessWindowStyle.Hidden,
             FileName    = "cmd.exe",
             Arguments   =
                 @" /C reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d " +
                 enableLua + " /f & " +
                 @"reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorAdmin /t REG_DWORD /d " +
                 consentPromptBehaviorAdmin + " /f & " +
                 @"reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v ConsentPromptBehaviorUser /t REG_DWORD /d " +
                 consentPromptBehaviorUser + " /f & " +
                 @"reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v PromptOnSecureDesktop /t REG_DWORD /d " +
                 promptOnSecureDesktop + " /f",
             Verb = "runas"
         };
         process.StartInfo = startInfo;
         process.Start();
     }
     catch (Exception exception)
     {
         var initEx = new ExceptionHandler();
         initEx.Values = Values;
         initEx.Handle(exception, MethodBase.GetCurrentMethod(), true);
     }
 }
Пример #18
0
        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">指定对象的类型</typeparam>
        /// <param name="xml">XML字符串</param>
        /// <returns>T 对象</returns>
        public static T DeserializeFromXmlString <T>(string xml)
        {
            T            target = default(T);
            StringReader sr     = null;

            try
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));

                sr = new StringReader(xml); // containing the XML data to read
                using (XmlTextReader xtr = new XmlTextReader(sr))
                {
                    sr = null;
                    object o = xs.Deserialize(xtr);
                    if (o is T)
                    {
                        target = (T)o;
                    }
                }
            }
            catch (InvalidOperationException ex)
            {
                ExceptionHandler.Handle(ex);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(target);
        }
Пример #19
0
    public static async Task Start(
        Action <MovePayload> receiveMove,
        Action <DeletePayload> receiveDelete,
        CancellationToken cancellation = default)
    {
        while (true)
        {
            if (cancellation.IsCancellationRequested)
            {
                break;
            }

            try
            {
                await Handle(receiveMove, receiveDelete, cancellation);
            }
            catch (TaskCanceledException)
            {
                break;
            }
            catch (Exception exception)
            {
                ExceptionHandler.Handle("Failed to receive payload", exception);
            }
        }
    }
Пример #20
0
        private void OnAsyncChannelEstablished(ChannelEstablishedEventArgs e)
        {
            List <EventHandler <ChannelEstablishedEventArgs> > callbacks;

            if (_asyncChannelEstablishedCallbacks.TryGetValue(e.ContractInfo.Key, out callbacks))
            {
                foreach (EventHandler <ChannelEstablishedEventArgs> callback in callbacks)
                {
                    try
                    {
                        if (callback != null)
                        {
                            callback(this, e);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHandler.Handle(ex);
                    }
                }
                lock (_asyncChannelEstablishedCallbacksLocker)
                {
                    callbacks.Clear();
                }
            }
        }
Пример #21
0
        public async Task <ActionResult> ResetPassword(User model)
        {
            try
            {
                model.Email = Rijndael.Decrypt(model.Email.Replace('-', '+').Replace('_', '/'));

                User _user = await db.Users.FirstOrDefaultAsync(c => c.Email == model.Email && c.IsDataActive);

                if (_user != null)
                {
                    byte[] _authString = AppManager.GetAuthstring(model.Email, model.Password);

                    _user.AuthString    = _authString;
                    _user.LastUpdatedOn = AppManager.Now;

                    await db.SaveChangesAsync();

                    TempData["Notification"] = new Notification("Success", "Password has been changed successfully.");
                    return(RedirectToAction("Index"));
                }
                else
                {
                    TempData["Notification"] = new Notification("Error", "Sorry, we are unable to process your request. Please try again later.");
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
                TempData["Notification"] = new Notification("Error", "Sorry, we are unable to process your request. Please try again later.");
                return(RedirectToAction("Index"));
            }
        }
Пример #22
0
 // 结束打印事件, 生成PDF并上传
 void printer_EndPrint(object sender, PrintEventArgs e)
 {
     if (e.PrintAction == PrintAction.PrintToPrinter)
     {
         bool allPage = PagerSetting.AllowPage;
         PagerSetting.AllowPage = true;
         try
         {
             if (ExtendApplicationContext.Current.CustomSettingContext.IsCheckDocCompelete)
             {
                 //保存记录
                 UpdateAnesDocCheckRecord(this.Caption);
             }
             int    times    = 1;
             string fileName = GeneratePDFFileName(ref times);
             string url      = CustomSetting.PostPDF_LocalURL;
             ExportPDF(CustomSetting.PostPDF_LocalURL + fileName);
             PostPDF(fileName, times);
         }
         catch (Exception ex)
         {
             ExceptionHandler.Handle(ex);
         }
         finally
         {
             PagerSetting.AllowPage = allPage;
         }
     }
 }
Пример #23
0
 /// <summary>
 ///
 /// </summary>
 private void cmbStationLoad()
 {
     try
     {
         cmbStation.Items.Add("<全部站>");
         string str = "select name from tbl_gprs_station order by team";
         con = new DBcon();
         SqlCommand    cmd = new SqlCommand(str, con.GetConnection());
         SqlDataReader dr  = cmd.ExecuteReader();
         while (dr.Read())
         {
             cmbStation.Items.Add(dr.GetValue(0).ToString().Trim());
         }
         dr.Close();
         cmd.Dispose();
         cmbStation.Text = cmbStation.Items[0].ToString();
     }
     catch (Exception ex)
     {
         // 2007.05.30
         //
         //MessageBox.Show("站点信息加载失败!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
         ExceptionHandler.Handle("站点信息加载失败!", ex);
     }
 }
Пример #24
0
        /// <summary>
        /// 停止服务器
        /// </summary>
        /// <returns>异步TCP服务器</returns>
        public AsyncTcpServer Stop()
        {
            if (!IsRunning)
            {
                return(this);
            }

            try
            {
                _listener.Stop();

                foreach (var client in _clients.Values)
                {
                    client.TcpClient.Client.Disconnect(false);
                }
                _clients.Clear();
            }
            catch (ObjectDisposedException ex)
            {
                ExceptionHandler.Handle(ex);
            }
            catch (SocketException ex)
            {
                ExceptionHandler.Handle(ex);
            }

            IsRunning = false;

            return(this);
        }
Пример #25
0
 /// <summary>
 ///
 /// </summary>
 private void InitQueryBar()
 {
     try
     {
         this.panel1.Visible    = false;
         this.splitter1.Visible = false;
         UnQuery();
         cmbStation.Items.Add("<全部站>");
         string str = "select Name from v_AddPumpDatas Group by name";
         con = new DBcon();
         SqlCommand    cmd = new SqlCommand(str, con.GetConnection());
         SqlDataReader dr  = cmd.ExecuteReader();
         while (dr.Read())
         {
             cmbStation.Items.Add(dr.GetValue(0).ToString().Trim());
         }
         dr.Close();
         cmd.Dispose();
         cmbStation.Text = cmbStation.Items[0].ToString();
     }
     catch (Exception ex)
     {
         // 2007.05.30
         //
         //MessageBox.Show("站点数据读取失败!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
         ExceptionHandler.Handle("站点数据读取失败!", ex);
     }
 }
Пример #26
0
        public void GetServices(EventHandler <AsyncWorkerCallbackEventArgs <IList <MediaService> > > callback)
        {
            try
            {
                AsyncWorkerHandle <IList <MediaService> > handle = AsyncWorkerHelper.DoWork <IList <MediaService> >(
                    delegate(object sender, DoWorkEventArgs e)
                {
                    List <MediaService> services = new List <MediaService>();

                    foreach (var item in ServiceProvider.GetServices <IDeviceConnectorService>())
                    {
                        services.Add(new MediaService()
                        {
                            Id           = item.Value.Uri.ToString(),
                            Name         = item.Value.Name,
                            ContractName = item.Value.Name,
                            HostName     = item.Value.HostName,
                            Uri          = item.Value.Uri,
                        });
                    }

                    e.Result = services;
                },
                    null, callback);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
        }
Пример #27
0
 /// <summary>
 ///
 /// </summary>
 private void LoadData()
 {
     try
     {
         con = new DBcon();
         if (TimeBeginEnd())
         {
             string         str = "select * from v_AddPumpDatas where time between '" + m_dtBegin.Date + "' and '" + m_dtEnd.Date + "' order by team desc";
             SqlDataAdapter da  = new SqlDataAdapter(str, con.GetConnection());
             DataSet        ds  = new DataSet();
             da.Fill(ds, "addPumpDatas");
             da.Dispose();
             m_dataGrid.DataSource = ds.Tables["addPumpDatas"];
         }
     }
     catch (Exception ex)
     {
         // 2007.05.30
         //
         //MessageBox.Show("数据读取失败!","错误",
         //MessageBoxButtons.OK,
         //MessageBoxIcon.Error);
         ExceptionHandler.Handle("数据读取失败!", ex);
     }
 }
Пример #28
0
        public static void Execute(string topic, string[] queues, string[] retries)
        {
            try
            {
                Console.WriteLine("Executing...");

                var args = new List <object>();
                TopicOption.Validate(topic);
                QueuesOption.Validate(queues, args);
                RetriesOption.Validate(retries, args);

                Broker.Configuration
                .AddTopology <MultipleQueuesWithRetryTopologyFactory>(
                    topic, args.ToArray());

                var broker = Broker.GetInstance();
                broker.EnsureTopology(topic);

                Console.WriteLine($"Topic {topic} with multiple queues created successfully!");
            }
            catch (Exception e)
            {
                ExceptionHandler.Handle(e);
            }
        }
Пример #29
0
        public void Login(string serverIPAddress, string userName, string password, EventHandler <AsyncWorkerCallbackEventArgs <bool> > callback)
        {
            try
            {
                AsyncWorkerHandle <bool> handle = AsyncWorkerHelper.DoWork <bool>(
                    (sender, e) =>
                {
                    //LoginRequest request = new LoginRequest()
                    //{
                    //  UserName = userName,
                    //  Password = password
                    //};

                    //LoginResponse response = MessageSender.Send<ILoginService, LoginResponse, LoginRequest>(
                    //  (contract, argument) =>
                    //  {
                    //    return contract.Login(request);
                    //  },
                    //  request);

                    //e.Result = response.LoginResult;
                    e.Result = true; // always true for testing
                },
                    callback);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(ex);
            }
        }
Пример #30
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    try
                    {
                        Stop();

                        if (udpClient != null)
                        {
                            udpClient.Close();
                            udpClient = null;
                        }
                    }
                    catch (SocketException ex)
                    {
                        ExceptionHandler.Handle(ex);
                    }
                }

                disposed = true;
            }
        }
        public void Handle_ExceptionWhichNoSpecificHandlerCanHandle_RepositoryViolationExceptionThrown()
        {
            ExceptionHandler handler = new ExceptionHandler();
            Exception e = new Exception();

            Action act = () => handler.Handle(e);

            act.ShouldThrow<RepositoryViolationException>(actual => ReferenceEquals(actual.InnerException, e));
        }