/// <summary> /// Retorna objeto do certificado para autenticação no serviço /// Obtendo o certificado em um caminho físico na maquina/rede /// </summary> /// <param name="rootPath">Caminho do diretório raiz do projeto</param> /// <param name="filename">Nome do certificado a ser lido</param> /// <param name="password">Senha do certificado para extração</param> /// <returns>Objeto X509Certificate2 contento o certificado</returns> public static X509Certificate2 ObterCertificado(string rootPath, string filename, string password) { try { if (string.IsNullOrEmpty(rootPath)) { BusinessException bEx = new BusinessException("Caminho do certificado não informado."); GlobalException.ReturnException(bEx); } string filePath = Path.Combine(rootPath, filename); if (!File.Exists(filePath)) { BusinessException aEx = new BusinessException(string.Format("Arquivo do certificado inexistente: \'{0}\'.", filename)); GlobalException.ReturnException(aEx); } X509Certificate2 certificate = new X509Certificate2(filePath, password, X509KeyStorageFlags.MachineKeySet); return(certificate); } catch (Exception ex) { ApplicationException bEx = new ApplicationException("Erro ao extrair certificado: " + ex.Message); GlobalException.ReturnException(bEx); return(null); } }
/// <summary> /// Cria novo objeto HttpClient através do baseAddress e do handler padrão para conexão /// </summary> /// <param name="baseAddress">URL do enedereço base para conexão com o serviço REST</param> /// <param name="token">Toke da sessão - DEVE SER OBTIDO DO Web services de Autenticação</param> /// <returns>Objeto HttpClient</returns> public HttpClient CreateHttpClient() { try { HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(20), BaseAddress = new Uri(this.BaseAddress), }; /// Toke da sessão - DEVE SER OBTIDO DO Web services de Autenticação client.DefaultRequestHeaders.Add("Authorization", this.Token.Set_Token); client.DefaultRequestHeaders.Add("X-CSRF-Token", this.Token.X_CSRF_Token); client.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue(this.EdiaType)); return(client); } catch (Exception ex) { ApplicationException aEx = new ApplicationException(string.Format("Erro ao estabelecer comunicação com o serviço: \'{0}\'.", ex.Message)); GlobalException.ReturnException(aEx); return(null); } }
public async Task Invoke(HttpContext httpContext) { var ex = httpContext.Features.Get <IExceptionHandlerFeature>()?.Error; if (ex == null) { return; } httpContext.Response.Clear(); httpContext.Response.ContentType = @"application/json"; GlobalException exception; if (ex is GlobalException) { exception = (GlobalException)ex; } else { exception = new GlobalException(ex.Message); } httpContext.Response.StatusCode = (int)exception.Status; using (var writer = new StreamWriter(httpContext.Response.Body)) { var resp = new ErrorResp(exception.Message); new JsonSerializer().Serialize(writer, resp); await writer.FlushAsync().ConfigureAwait(false); } }
static void Main() { if (PreventApplication.Register(GUID)) { GlobalException.Init(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Windows.MainWindow()); } }
// <summary> /// Alterar Jogo /// </summary> /// <param name="Jogo">Jogo</param> /// <returns></returns> public void Alterar(Jogo model) { try { _jogoRepository.Update(model); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
// <summary> /// Excluir Jogo /// </summary> /// <param name="Jogo">Jogo</param> /// <returns></returns> public void Excluir(Jogo model) { try { _jogoRepository.Remove(model); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
/// <summary> /// Listar Jogos /// </summary> /// <returns></returns> public List <Jogo> Listar() { try { return(_jogoRepository.Listar()); } catch (Exception ex) { GlobalException.ReturnException(ex); return(new List <Jogo>()); } }
/// <summary> /// Logar /// </summary> /// <param name="UsuarioVM">UsuarioVM</param> /// <returns></returns> public Usuario Login(UsuarioVM model) { try { return(_Db.Usuario.FirstOrDefault(x => x.Nome.ToUpper().Trim() == model.Nome.ToUpper().Trim() && x.Senha.ToUpper().Trim() == model.Senha.ToUpper().Trim())); } catch (Exception ex) { GlobalException.ReturnException(ex); return(new Usuario()); } }
// <summary> /// Cadastrar Amigo /// </summary> /// <param name="AmigoVM">AmigoVM</param> /// <returns></returns> public void Cadastrar(AmigoVM model) { try { Amigo amigo = new Amigo() { Nome = model.Nome }; _amigoRepository.Add(amigo); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
// <summary> /// Cadastrar Jogo /// </summary> /// <param name="JogoVM">JogoVM</param> /// <returns></returns> public void Cadastrar(JogoVM model) { try { Jogo jogo = new Jogo() { Nome = model.Nome, AmigoID = model.AmigoId }; _jogoRepository.Add(jogo); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
// <summary> /// Cadastrar Usuario /// </summary> /// <param name="UsuarioVM">UsuarioVM</param> /// <returns></returns> public void Cadastrar(UsuarioVM model) { try { Usuario usuario = new Usuario() { Nome = model.Nome, Senha = model.Senha }; _usuarioRepository.Add(usuario); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
public static void begin() { YDColorizer.GlobalException.Initialize(); Timer timer = new Timer(); #region 配置文件不存在,创建默认配置文件 if (Config.IsConfigExists() == false) { Config.CreateDefault(); } #endregion List <string> dialogBoxTitles = AboutConfig.LoadSearchTitles(); EditDialogBox edb = new EditDialogBox(); int thisProcessId = System.Diagnostics.Process.GetCurrentProcess().Id; timer.Interval = 100;// 设置搜索间隔为100毫秒 timer.Tick += new EventHandler((object object_sender, EventArgs EventArgs_e) => { try { if (edb.hWnd == IntPtr.Zero) { foreach (var title in dialogBoxTitles) // 遍历标题数组寻找对话框 { WinApi.Window dialogBox = new WinApi.Window(DialogBoxClassName, title); // 搜索we物体编辑器的文本编辑框 if (dialogBox.Handle != IntPtr.Zero && thisProcessId == AboutProcess.GetProcessId(dialogBox.Handle)) // 搜索的对话框与该ydwe插件同进程 { edb.AttachDialog(dialogBox.Handle); // 重建模拟窗口 break; } } } } catch (Exception e) { timer.Stop(); GlobalException.CatchException(e, e.ToString()); } }); timer.Start();// 启动搜索计时器 }
/// <summary> /// Retorna objeto do certificado para autenticação no serviço /// Obtendo o certificado registrado no repositório local do usuário do SO /// </summary> /// <returns>Objeto X509Certificate2 contento o certificado</returns> public static X509Certificate2 ObterCertificado(string CertificadoDigitalECPF) { X509Store store = new X509Store("MY", StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); foreach (X509Certificate2 x509 in fcollection) { try { if (x509.FriendlyName.IndexOf(CertificadoDigitalECPF) != -1) { //Console.WriteLine(x509.FriendlyName); return(x509); } //Console.WriteLine(x509.FriendlyName); } catch (CryptographicException) { CryptographicException cEx = new CryptographicException("As informações não puderam ser obtidas deste certificado."); GlobalException.ReturnException(cEx); } } BusinessException bEx = new BusinessException("Certificado não localizado."); GlobalException.ReturnException(bEx); return(null); } catch (Exception ex) { ApplicationException aEx = new ApplicationException(string.Format("Erro ao extrair certificado: \'{0}\'.", ex.Message)); GlobalException.ReturnException(aEx); return(null); } finally { store.Close(); } }
// <summary> /// Excluir Amigo /// </summary> /// <param name="Amigo">Amigo</param> /// <returns></returns> public void Excluir(Amigo model) { try { List <Jogo> listaJogos = _jogoRepository.PesquisarPorAmigo(model.Id); if (listaJogos.Any()) { throw new BusinessException("Existem jogos empretados para esse amigo"); } _amigoRepository.Remove(model); } catch (Exception ex) { GlobalException.ReturnException(ex); } }
/// <summary> /// Envia uma requisição POST para o endpoint formado por baseAddress e url /// </summary> /// <param name="url">Action usada para criar resource no serviço</param> /// <returns>Resultado da requisição</returns> public async Task <JRetornoAutenticacao> Post(string url) { JRetornoAutenticacao retorno = null; try { HttpResponseMessage response = null; if (this.HoraExpiracaoToken <= DateTime.Now || string.IsNullOrWhiteSpace(this.Token)) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); response = this.HttpClient.SendAsync(request).Result; if ((int)response.StatusCode != 200) { ApplicationException aEx = new ApplicationException(response.ReasonPhrase); GlobalException.ReturnException(aEx); } this.HoraExpiracaoToken = DateTime.Now.AddMinutes(this.ValidadeTokenMinutos); string operationLocation = response.Headers.GetValues("Set-Token").FirstOrDefault(); retorno = new JRetornoAutenticacao { Set_Token = response.Headers.GetValues("Set-Token").FirstOrDefault(), X_CSRF_Expiration = response.Headers.GetValues("X-CSRF-Expiration").FirstOrDefault(), X_CSRF_Token = response.Headers.GetValues("X-CSRF-Token").FirstOrDefault() }; } return(retorno); } catch (Exception ex) { ApplicationException aEx = new ApplicationException(string.Format("Erro ao enviar requisição para serviço: \'{0}\'.", ex.Message)); GlobalException.ReturnException(aEx); return(null); } }
public static bool Start() { bool ret = true; Log.Instance().Init("./MapServer"); GlobalException.InitException(); //载入配置文件 try { ConfigManager.Instance().LoadConfig(); MemIniFile ini = new MemIniFile(); if (!ini.LoadFromFile(TextDefine.GoldConfig)) { Log.Instance().WriteLog("load golbalconfig error!"); return(false); } String sIP = ini.ReadValue(TextDefine.GameServerSetion, TextDefine.NormalIPKey, TextDefine.NormalIP); int nPort = ini.ReadValue(TextDefine.GameServerSetion, TextDefine.NormalPortKey, TextDefine.GameServerPort); mTcpServer = new TcpServer(); mTcpServer.onConnect += new TcpServerEvent.OnConnectEventHandler(OnConnect); mTcpServer.onClose += new TcpServerEvent.OnCloseEventHandler(OnClose); mTcpServer.onReceive += new TcpServerEvent.OnReceiveEventHandler(OnReceive); if (!mTcpServer.Start(sIP, nPort)) { return(false); } } catch (System.Exception ex) { Log.Instance().WriteLog("启动服务器失败"); Log.Instance().WriteLog(ex.Message); Log.Instance().WriteLog(ex.StackTrace); return(false); } return(ret); }
/// <summary> /// Envia uma requisição POST para o endpoint formado por baseAddress e url, usando /// como request body o parâmetro jsonData /// </summary> /// <param name="url">Action usada para criar resource no serviço</param> /// <param name="jsonData">Objeto usado para requisição</param> /// <returns>Resultado da requisição</returns> public async Task <HttpResponseMessage> Post(string url, string jsonData, string ediaType = "application/json") { try { HttpResponseMessage response = null; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new StringContent(jsonData, Encoding.UTF8, ediaType), }; response = this.HttpClient.SendAsync(request).Result; return(response); } catch (Exception ex) { ApplicationException aEx = new ApplicationException(string.Format("Erro ao enviar requisição para serviço: \'{0}\'.", ex.Message)); GlobalException.ReturnException(aEx); return(null); } }
/// <summary> /// Logar /// </summary> /// <param name="UsuarioVM">UsuarioVM</param> /// <returns></returns> public UsuarioVM Login(UsuarioVM model) { try { Usuario usu = _usuarioRepository.Login(model); if (usu == null) { throw new BusinessException("Credenciais inválidas."); } TokenService ts = new TokenService(); var token = ts.GenerateToken(usu); model.Token = token; return(model); } catch (Exception ex) { GlobalException.ReturnException(ex); return(new UsuarioVM()); } }
public string ComunicarEntregaDocumentoCarga(EntregasDocumentoCarga entregasDocumentoCarga) { /// EndPoint string lEndPoint = URLBase + Util.ObterParametro <string>("PUCOMEX.EndPointComunicarEntregaDocumentoCarga"); RestClient client = new RestClient(lEndPoint, Autenticar(), "application/xml"); string text = Util.Serializar <EntregasDocumentoCarga>(entregasDocumentoCarga, "http://www.pucomex.serpro.gov.br/cct"); //##// Buscar de parametro NameSpace do XML da integração PUCOMEX using (client) { HttpResponseMessage response = client.Post(lEndPoint, text, "application/xml").Result; int StatusCode = (int)response.StatusCode; if (!StatusCode.Equals(200)) { BusinessException ex = new BusinessException(response.Content.ReadAsStringAsync().Result); GlobalException.ReturnException(ex); } return(response.Content.ReadAsStringAsync().Result); } }
/// <summary> /// Configura o handler para o HttpClient, usando certificado e protocolos SSL /// </summary> /// <returns>Objeto HttpClientHandler para configurar conexão http</returns> private HttpClientHandler GetHttpClientHandler() { try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; HttpClientHandler handler = new HttpClientHandler { MaxConnectionsPerServer = 9999, //SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 }; /// Obtendo o certificado em um caminho físico na maquina/rede X509Certificate2 certificate = Certificate.ObterCertificado(ROOTPATH, CERTFILE, PASSWORD); /// Obtendo o certificado registrado no repositório local do usuário no SO //X509Certificate2 certificate = Certificate.ObterCertificado(Certificado_Digital); _ = handler.ClientCertificates.Add(certificate); handler.ServerCertificateCustomValidationCallback += (sender, cert, chain, errors) => { //if (Config.LerConfiguracao("AmbDEV").Equals("1")) return(true); // No ambiente de Desenvolvimento, trust all certificates //return errors == SslPolicyErrors.None; // Compliant: trust only some certificates }; return(handler); } catch (Exception ex) { ApplicationException aEx = new ApplicationException(ex.Message); GlobalException.ReturnException(aEx); return(null); } }
/// <summary> /// Cria novo objeto HttpClient através do baseAddress e do handler padrão para conexão /// </summary> /// <param name="baseAddress">URL do enedereço base para conexão com o serviço REST</param> /// <returns>Objeto HttpClient</returns> public void CreateHttpClient(string baseAddress) { try { HttpClientHandler handler = this.GetHttpClientHandler(); HttpClient client = new HttpClient(handler) { Timeout = TimeSpan.FromMinutes(1), BaseAddress = new Uri(baseAddress), }; client.DefaultRequestHeaders.Add("Role-Type", "DEPOSIT"); client.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); this.HttpClient = client; } catch (Exception ex) { ApplicationException aEx = new ApplicationException(string.Format("Erro ao estabelecer comunicação com o serviço: \'{0}\'.", ex.Message)); GlobalException.ReturnException(aEx); } }
public static void begin() { YDColorizer.GlobalException.Initialize(); Timer timer = new Timer(); #region 配置文件不存在,创建默认配置文件 if (Config.IsConfigExists() == false) { Config.CreateDefault(); } #endregion Program.language = Config.GetLanguage(); List <string> dialogBoxTitles = AboutConfig.LoadSearchTitles(); #region 托盘图标 if (Config.IsNotifyIconVisible() == true) { NotifyIcon notifyIcon = new NotifyIcon(); notifyIcon.Icon = YDColorizer.Properties.Resources.icoYDColorizerRuning; switch (Program.language) { case 0: notifyIcon.Text = "YDWE颜色插件正在执行" + Environment.NewLine + "点击图标可以暂时停止执行"; break; case 1: notifyIcon.Text = "YDWE顏色插件正在執行" + Environment.NewLine + "點擊圖標可以暫時停止執行"; break; default: break; } notifyIcon.Visible = true; notifyIcon.Click += new EventHandler((object object_sender, EventArgs EventArgs_e) => { if (timer.Enabled == true) { timer.Enabled = false; notifyIcon.Icon = YDColorizer.Properties.Resources.icoYDColorizerStop; switch (Program.language) { case 0: notifyIcon.Text = "YDWE颜色插件已暂停" + Environment.NewLine + "点击图标可以恢复执行"; break; case 1: notifyIcon.Text = "YDWE顏色插件已暫停" + Environment.NewLine + "點擊圖標可以恢復執行"; break; default: break; } } else { timer.Enabled = true; notifyIcon.Icon = YDColorizer.Properties.Resources.icoYDColorizerRuning; switch (Program.language) { case 0: notifyIcon.Text = "YDWE颜色插件正在执行" + Environment.NewLine + "点击图标可以暂时停止执行"; break; case 1: notifyIcon.Text = "YDWE顏色插件正在執行" + Environment.NewLine + "點擊圖標可以暫時停止執行"; break; default: break; } } }); } #endregion timer.Interval = 100;// 设置搜索间隔为100毫秒 EditDialogBox edb = new EditDialogBox(); timer.Tick += new EventHandler((object object_sender, EventArgs EventArgs_e) => { try { if (edb.hWnd == IntPtr.Zero) { foreach (var title in dialogBoxTitles) // 遍历标题数组寻找对话框 { WinApi.Window dialogBox = new WinApi.Window(DialogBoxClassName, title); // 搜索we物体编辑器的文本编辑框 if (dialogBox.Handle != IntPtr.Zero) // 找到 { int thisProcessId = System.Diagnostics.Process.GetCurrentProcess().Id; int targetProcessId = AboutProcess.GetProcessId(dialogBox.Handle); if (thisProcessId == targetProcessId) // 搜索的对话框与该ydwe插件同进程 { edb.AttachDialog(dialogBox.Handle); // 重建模拟窗口 break; } } } } } catch (Exception e) { timer.Stop(); GlobalException.CatchException(e, e.ToString()); } }); timer.Start();// 启动搜索计时器 }
public override int SaveChanges() { try { var added = new List <KeyValuePair <object, LogMeusJogos> >(); var entries = ChangeTracker.Entries().Where(x => x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted).ToList(); foreach (var dbEntityEntry in entries) { var entityName = dbEntityEntry.Entity.GetType().Name; var primaryKey = GetPrimaryKeyValue(dbEntityEntry); switch (dbEntityEntry.State) { case EntityState.Added: case EntityState.Deleted: var log = new LogMeusJogos { Tabela = entityName, Acao = dbEntityEntry.State.ToString(), MatriculaUsuario = (_accessor?.HttpContext?.User?.Identity?.Name != null) ? int.Parse(_accessor.HttpContext.User.Identity.Name) : 0, Chaves = primaryKey, NomeColuna = "*", Propriedade = "*", ValorOriginal = String.Empty, ValorAtual = String.Empty, DtcOcorrencia = DateTime.Now }; if (dbEntityEntry.State == EntityState.Deleted) { log.ValorOriginal = JsonConvert.SerializeObject(dbEntityEntry.Entity); } Set <LogMeusJogos>().Add(log); if (dbEntityEntry.State != EntityState.Added) { continue; } var kv = new KeyValuePair <object, LogMeusJogos>(dbEntityEntry.Entity, log); added.Add(kv); break; case EntityState.Modified: GeraLogUpdate(dbEntityEntry, entityName, primaryKey); break; } } var result = base.SaveChanges(); UpdateInsertedKey(added); return(result); } catch (Exception ex) { GlobalException.ReturnException(ex); return(0); } }
private static void OnDeleted(object source, FileSystemEventArgs e) { string _Size; string _Type = null; string _FileName; string _Permissions; string Parent = Directory.GetParent(e.FullPath).ToString(); string _Author = null; if (Path.HasExtension(e.FullPath)) { try { _Author = File.GetAccessControl(e.FullPath).GetOwner(typeof(NTAccount)).ToString(); } catch (Exception) { } } else { try { _Author = Directory.GetAccessControl(e.FullPath).GetOwner(typeof(NTAccount)).ToString(); } catch (Exception) { } _Type = "Folder"; } if (_Author != null) { _Author = _Author.Remove(0, 12); } try { _Size = new FileInfo(e.FullPath).Length.ToString(); } catch (Exception) { _Size = "Unknown"; } try { _Type = new FileInfo(e.FullPath).Extension; } catch (Exception) { if (_Type == null) { _Type = "Unknown Type"; } else { _Type = "Unknown Type"; } } try { _FileName = Path.GetFileName(e.Name); } catch (Exception) { _FileName = "Unknown"; } try { _Permissions = new FileInfo(e.FullPath).IsReadOnly.ToString(); } catch (Exception ex) { _Permissions = "Unknown"; GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = ex.Message }); GlobalException.LogTheException(); } if (GlobalResources.IsRestrictionsMonitoringSet & GlobalResources.IsFileSytemRestrictionSet) { Agent_FileSystem.Analyse(e.FullPath, _Author); } try { System.Windows.Application.Current.Dispatcher.Invoke(delegate { FSMListHolder.Add(new FileSystemReportsModel() { Time = DateTime.Now.ToString(), ChangeType = e.ChangeType.ToString() + "...", FileType = _Type, Name = _FileName, Size = _Size.ToString() + " bytes", FullPath = e.FullPath, Permissions = _Permissions, Author = _Author }); }); } catch (Exception) { } }
private static void Worker_DoWork(object sender, DoWorkEventArgs e) { ObservableCollection <ApplicationsModel> ProgramHolderListOfWorker = new ObservableCollection <ApplicationsModel>(); ProgramHolderListOfWorker = e.Argument as ObservableCollection <ApplicationsModel>; string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; RegistryKey rk; using (rk = Registry.CurrentUser.OpenSubKey(uninstallKey)) { foreach (string skName in rk.GetSubKeyNames()) { using (RegistryKey sk = rk.OpenSubKey(skName)) { try { var displayName = sk.GetValue("DisplayName"); var Size = sk.GetValue("EstimatedSize"); string publisher; string path; try { publisher = sk.GetValue("Publisher").ToString(); path = sk.GetValue("InstallLocation").ToString(); } catch (Exception m) { publisher = "Exception"; path = "Exception"; GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } if (publisher == null) { publisher = "no data"; } if (path == null) { path = "no data"; } ProgramHolderListOfWorker.Add(new ApplicationsModel { Name = displayName.ToString(), Size = Convert.ToInt32(Size), Path = path.ToString(), Publisher = publisher.ToString() }); } catch (Exception m) { GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } } } } using (rk = Registry.LocalMachine.OpenSubKey(uninstallKey)) { foreach (string skName in rk.GetSubKeyNames()) { using (RegistryKey sk = rk.OpenSubKey(skName)) { try { var displayName = sk.GetValue("DisplayName"); var Size = sk.GetValue("EstimatedSize"); string publisher; string path; try { publisher = sk.GetValue("Publisher").ToString(); path = sk.GetValue("InstallLocation").ToString(); } catch (Exception m) { publisher = "Exception"; path = "Exception"; GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } if (publisher == null) { publisher = "no data"; } if (path == null) { path = "no data"; } ProgramHolderListOfWorker.Add(new ApplicationsModel { Name = displayName.ToString(), Size = Convert.ToInt32(Size), Path = path.ToString(), Publisher = publisher.ToString() }); } catch (Exception m) { GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } } } } using (rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall")) { foreach (string skName in rk.GetSubKeyNames()) { using (RegistryKey sk = rk.OpenSubKey(skName)) { try { var displayName = sk.GetValue("DisplayName"); var Size = sk.GetValue("EstimatedSize"); string publisher; string path; try { publisher = sk.GetValue("Publisher").ToString(); path = sk.GetValue("InstallLocation").ToString(); } catch (Exception m) { publisher = "Exception"; path = "Exception"; GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } if (publisher == null) { publisher = "no data"; } if (path == null) { path = "no data"; } ProgramHolderListOfWorker.Add(new ApplicationsModel { Name = displayName.ToString(), Size = Convert.ToInt32(Size), Path = path.ToString(), Publisher = publisher.ToString() }); } catch (Exception m) { GlobalException.No++; GlobalException.AllExceptions.Add(new Model.ExceptionModel { No = GlobalException.No, Date = DateTime.Now.ToShortDateString(), Time = DateTime.Now.ToShortTimeString(), Message = m.Message }); GlobalException.LogTheException(); } } } } e.Result = ProgramHolderListOfWorker; }