public bool RegisterListListener(LoginSession session, String server, int list) { try { IListServiceClient callback = _callbackCreator(); lock (_subscribersLock) { if (!_subscribers.Exists(client => client.IsCurrentCallback(callback))) { _subscribers.Add(new AsyncListServiceClient(callback)); } _subscribers.Find(client => client.IsCurrentCallback(callback)).AddChannel(new Channel(server, list)); } CheckClients(null, null); return(true); } catch (CommunicationException ex) { ServiceLogger.Error("Error while registering ListListener", ex); return(false); } }
public void GetToken(Credentials inCredentials, string inFilename) { try { _configurationCloud = new ApiConfiguration(inCredentials.ConsumerKey, inCredentials.ConsumerSecret, "http://desktop"); _oAuthKeyService = new MYOBOAuthKeyService(); var dateTimeNow = DateTime.UtcNow; var lastTokenTime = _oAuthKeyService.OAuthResponse.ReceivedTime; double days = (dateTimeNow - lastTokenTime).TotalDays; string days1 = days.ToString(); ServiceLogger.Log(string.Format(@"days: {0}", days1)); if (days < 365) { if (_oAuthKeyService.OAuthResponse.HasExpired) { var oauthService = new OAuthService(_configurationCloud); _oAuthKeyService.OAuthResponse = oauthService.RenewTokens(_oAuthKeyService.OAuthResponse); ServiceLogger.Log("Token Renewed"); } else { ServiceLogger.Log("Token not Expired"); } MYOBCompanyFiles companyFiles = new MYOBCompanyFiles(inCredentials); companyFiles.FetchFile(_configurationCloud, null, _oAuthKeyService, inFilename); } } catch (Exception exception) { ServiceLogger.LogException("Exception in GetTokens", exception); } }
static void Main(string[] args) { string addr = string.Empty; try { addr = getIpAddress(); if (addr != string.Empty) { // The same service that located on the service of the client // This service is to send the client window service command( service that located on the field) m_wcfc.StartService(addr, 8030); ServiceLogger.WriteLine(LOGGER_NAMES.GOJI_WCF_STREAMING_CLIENT, "Service started to list to " + addr); } } catch (Exception err) { ServiceLogger.WriteLine(LOGGER_NAMES.GOJI_WCF_STREAMING_CLIENT, "Service error on start: " + addr); return; } Console.WriteLine("Write any key to stop client"); Console.ReadLine(); try { //m_wcfc.Close(); ServiceLogger.WriteLine(LOGGER_NAMES.GOJI_WCF_STREAMING_CLIENT, "Service stopped"); } catch (Exception err) { ServiceLogger.WriteLine(LOGGER_NAMES.GOJI_WCF_STREAMING_CLIENT, "Service stopped error" + err.Message); } }
/// <summary> /// /// </summary> /// <param name="inFolder"></param> public object AddWatchedFolder(string inFolder) { object supplier = 0; try { FileSupplier fileSupplier = createNewFileSupplier(inFolder, FileSupplier.FileType.XML); file_suppliers.Add(inFolder, fileSupplier); supplier = fileSupplier; } catch (ArgumentNullException nexc) { // The key is null ServiceLogger.Log(string.Format(@"Failed to monitor folder {0}: The key is null: {1}", inFolder, nexc.Message)); } catch (ArgumentException aexc) { // The key already exists in the dictionary // Prevent from folder duplication ServiceLogger.Log(string.Format(@"Failed to monitor folder {0}: The key already exists in the dictionary: {1}", inFolder, aexc.Message)); } return(supplier); }
private void StartHTTPCompanionService(string URL) { //URL = Zeus.Lib.Extensions.ExtensionHelpers.GetAddress(URL); WebServiceHTTP.WebServiceBaseAddress = URL; string WebServiceHTTPBaseAddress = URL + "Admin/"; try { Uri uri = new Uri(WebServiceHTTPBaseAddress); oWebServiceHost = new WebServiceHost(oServiceHTTPType, uri); var endpoint = CreateEndpoint(oServiceHTTPInterfaceType, WebServiceHTTPBaseAddress); oWebServiceHost.AddServiceEndpoint(endpoint); //oWebServiceHost.Authorization.ServiceAuthorizationManager = new RestAuthorizationManager(); oWebServiceHost.Open(); } catch (Exception ex) { ServiceLogger.Error("Companion service cannot be started, reason: " + ex.Message); return; } ServiceLogger.Info("SERVICE HTML ADMIN STARTED"); ServiceLogger.Info("Listening on: " + WebServiceHTTPBaseAddress); }
/// <summary> /// /// </summary> public void CallThorInitMethod(DTO.Thorlink.DTO_ThorAuth thorAuth) { if (thorAuth == null) { throw new Exception("CallThorInitMethod received a null argument!"); } try { if (thorAuth != null) { ThorConfig.AppKey = thorAuth.appKey; ThorConfig.SiteNo = thorAuth.siteNo; ThorConfig.MerchantCode = thorAuth.merchantCode; ThorConfig.DeviceCode = thorAuth.deviceCode; ThorConfig.OnSetToken = HandlerForToken; ThorConfig.LocalDirectory = @"C:\Thorlink Logs"; string credentials = @"appId:- " + thorAuth.appKey; credentials += @"siteNo:- " + thorAuth.siteNo; credentials += @"siteNo:- " + thorAuth.siteNo; credentials += @"siteNo:- " + thorAuth.siteNo; credentials += @"path for directory:- " + ThorConfig.LocalDirectory; ServiceLogger.Log(@"Values set for ThorConfiguration as "); ThorConfig.Init(); ServiceLogger.Log(@"Thor Config Init() method called with " + credentials); } } catch (Exception exception) { ServiceLogger.LogException("Exception in Calling Init Method ", exception); } }
public bool UpdateSalesForceModulesStatus(SalesForceModuleStatus salesForceModuleStatus) { try { //We need to login to sales force to initiate the process.. //Get the credentials for logging into sales force.. var credentials = _salesForceCredentialFactory.Create(); if (_salesForceInterface.Login(credentials)) { //Update the sales fields with new values.. var isSuccess = _salesForceInterface.UpdateSalesForceModulesStatus(salesForceModuleStatus); //Since we have completed all the processing we will log out.. _salesForceInterface.Logout(); return(isSuccess); } } catch (Exception exception) { ServiceLogger.LogException("Exception in UpdateSalesForceModulesStatus", exception); } return(false); }
public bool DisableMobiToGo(string accountName) { try { //We need to login to sales force to initiate the process.. //Get the credentials for logging into sales force.. var credentials = _salesForceCredentialFactory.Create(); if (_salesForceInterface.Login(credentials)) { //Update the Mobi to Go Status.. var isEnabled = _salesForceInterface.UpdateMobiToGoStatus(accountName, false); //Since we have completed all the processing we will log out.. _salesForceInterface.Logout(); return(isEnabled); } } catch (Exception exception) { ServiceLogger.LogException("Exception in DisableMobiToGo", exception); } return(false); }
public bool DisablePocketVouchers(string accountName) { try { //We need to login to sales force to initiate the process.. //Get the credentials for logging into sales force.. var credentials = _salesForceCredentialFactory.Create(); if (_salesForceInterface.Login(credentials)) { //Update the pocket voucher fields to sales force.. var isEnabled = _salesForceInterface.DisablePocketVouchers(accountName); var isDateChanged = _salesForceInterface.UpdatePocketVouchersDateUpdated(accountName); //Since we have completed all the processing we will log out.. _salesForceInterface.Logout(); return(isEnabled && isDateChanged); } } catch (Exception exception) { ServiceLogger.LogException("Exception in DisablePocketVouchers", exception); } return(false); }
private IEnumerable <MediaInfo> Execute(Expression <Func <MediaInfo, Boolean> > expression) { var adcUri = new Uri( Config.Instance.ConfigObject.DataServiceConnectionOptions.DataServiceAddress); var adcDB = new AdcModelContainer(adcUri); var query = adcDB.MediaInfos.Expand(@"ContentTable").Expand(@"SegmentInfos").Where(expression) as DataServiceQuery <MediaInfo>; var result = new List <MediaInfo>(); if (query != null) { try { var response = (QueryOperationResponse <MediaInfo>)query.Execute(); while (response != null) { var part = new List <MediaInfo>(); part.AddRange(response); result.AddRange(part); var continuation = response.GetContinuation(); response = continuation != null?adcDB.Execute(continuation) : null; } } catch (Exception ex) { ServiceLogger.Error(ex.Message, ex); return(result); } } return(result); }
public void Initialize(DTO_ThorAuth dto_thorAuth) { try { if (dto_thorAuth != null) { if (ThorAuthCheck.Instance.ThorlinkAccessToken == null) { ThorAuthCheck.Instance.CallThorInitMethod(dto_thorAuth); Thread.Sleep(500); } else { ServiceLogger.Log("Token already exists :-" + ThorAuthCheck.Instance.ThorlinkAccessToken); } } else { throw new ArgumentNullException("Initialize received a null argument!"); } } catch (Exception ex) { ServiceLogger.Log(" exception is ---" + ex.Message); } }
public PocketVoucherDetail GetPocketVoucherDetail(string accountName) { try { //We need to login to sales force to initiate the process.. //Get the credentials for logging into sales force.. var credentials = _salesForceCredentialFactory.Create(); if (_salesForceInterface.Login(credentials)) { //Get the pocket voucher fields from sales force to return to POS.. var pocketVoucherDetail = _salesForceInterface.GetPocketVoucherDetail(accountName); //Since we have completed all the processing we will log out.. _salesForceInterface.Logout(); return(pocketVoucherDetail); } } catch (Exception exception) { ServiceLogger.LogException("Exception in GetPocketVoucherDetail", exception); } return(null); }
/// <summary> /// 上下文初始化 /// </summary> /// <returns></returns> public DependencyResult Init() { ServiceLogger.Info("---------------------服务的依赖项检测--开始---------------------"); DependencyResult result = new DependencyResult() { UnitName = GetUnitName() }; //配置文件依赖检测 result.DependencyDetails.Add(CheckAvailabilityOfConfigForService(ProtocolConfig)); result.DependencyDetails.Add(CheckAvailabilityOfConfigForService(DatabaseConfig)); //数据库依赖检测 foreach (var dbConfigItem in DatabaseConfig.DbConfigItems) { result.DependencyDetails.Add(CheckAvailabilityOfDbSessionForService(dbConfigItem)); } //其他依赖项检测 foreach (var dependencyResult in InitOthers()) { result.DependencyResults.Add(dependencyResult); } //更新并记录自身错误 result.UpdateInfoFromDependencies(); ServiceLogger.Info(result.Message); ServiceLogger.Info("---------------------服务的依赖项检测--结束---------------------"); return(result); }
protected override void OnStart(string[] args) { // start the service ILogger svcLogger = new ServiceLogger(EventLog); try { // - set current directory to the install location // - get executable name for file logger Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; ProcessModule pm = Process.GetCurrentProcess().MainModule; string moduleName = pm.ModuleName.Split('.')[0]; Reference <ILogger> loggerRef = Reference <ILogger> .Create(new MultiLogger( svcLogger, new FileLogger(@"C:\_qds\logs\" + moduleName + ".{dddd}.log"))); _clientRef = Reference <ICoreClient> .Create(new CoreClientFactory(loggerRef).SetEnv(BuildConst.BuildEnv).Create()); _server = new AlertServer { LoggerRef = loggerRef, Client = _clientRef, HostInstance = null, OtherSettings = _clientRef.Target.LoadAppSettings("AlertServer") }; _server.Start(); } catch (Exception ex) { svcLogger.Log(ex); } }
public List <ClippMessage> GetPreviousMessages() { try { using (var client = new HttpClient(_httpClientHandler)) { client.BaseAddress = new Uri(string.Format("http://{0}:{1}/", _baseAddress, _port)); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.GetAsync(string.Format("{0}/Messages/1", ClippAddress)); response.Wait(); var result = response.Result; if (result.IsSuccessStatusCode) { var clippMessageTask = result.Content.ReadAsStringAsync(); clippMessageTask.Wait(); var clippMessages = JsonConvert.DeserializeObject <ClippMessage[]>(clippMessageTask.Result); return(new List <ClippMessage>(clippMessages)); } } } catch (Exception exception) { ServiceLogger.LogException("Exception in GetPreviousMessages", exception); } return(new List <ClippMessage>(0)); }
/// <summary> /// /// </summary> /// <param name="fileURI"></param> protected void processOrderFile(string inFileURI) { bool added = false; WebOrderDBAccessProcess process = web_order_db_manager.AddProcess(out added); //.................................................... WebOrder webOrder; string orderHandle = readOrderFromFile(inFileURI, out webOrder); process.OrderURI = inFileURI; process.WebOrder = webOrder; process.HasCompleted += dbAccessProcessComplete; process.HasFailed += dbAccessProcessFailed; process.DeadLock += dbAccessDeadLock; //.................................................... removeCompleteOrder(process.WebOrder); System.Reflection.MethodBase currentMethod = System.Reflection.MethodBase.GetCurrentMethod(); ServiceLogger.LogWithMethod(currentMethod, @": Complete order file has been removed from folder"); //.................................................... if (added) { web_order_db_manager.StartProcess(process); } else { web_order_db_manager.AddProcessToPoll(process); } }
/// <summary> /// /// </summary> /// <param name="webOrderXML"></param> void dbSaveOrder(WebOrder inOrder) { WebOrderDB webOrderDB = new WebOrderDB(); try { webOrderDB.BeginTransaction(); //check webmate enabled here or not.. bool checkWebmateIsEnabled = checkWebmateEnabledOrNot(webOrderDB); if (checkWebmateIsEnabled) { int weborderKey = dbSaveOrderInfo(inOrder, webOrderDB); int menu_key = getMenuKeyFormChit(webOrderDB); dbSaveOrderItems(weborderKey, inOrder, webOrderDB, menu_key); } else { SetWebmateForMessage(webOrderDB); } webOrderDB.EndTransaction(); } catch (Exception) { webOrderDB.RollbackTransaction(); ServiceLogger.Log(@"WebOrderDBAccessProcess.dbSaveOrder(WebOrder inOrder) ROLLBACK"); throw; } }
private static void ConsoleThreadException(object sender, UnhandledExceptionEventArgs e) { try { Exception ex = e.ExceptionObject as Exception; string errorMSG = "An application error occured. Please contact the administrator " + "with the following information:\n\n"; errorMSG += "Error Message: " + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace; //result = XtraMessageBox.Show(errorMSG, "Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); //result = MadaaMessageBox.ShowError(ex.Message, errorMSG, "Windows Forms Error", MessageBoxButtons.AbortRetryIgnore); ServiceLogger.LogError("ConsoleThreadException, " + errorMSG); } catch { try { //MadaaMessageBox.ShowError("Fata windows forms error", "Fata windows forms error"); ServiceLogger.LogError("UIThreadException(), SmartWatcher application encountered a Fatal Error."); } finally { Environment.Exit(-1); } } //Exit the program when the user slicks Abort. // if (result == DialogResult.Abort) { Environment.Exit(-1); } }
protected override bool StartRunner() { bool result = false; ServiceLogger.Log(@"Starting Thorlink Server endpoint ..."); result = OpenServiceHost(); if (result) { ServiceLogger.Log(@"Thorlink Server endpoint is running ..."); //TODO: Initialize the Thorlink Integration Server.... ServiceInfo serviceInfo = ServiceInfo.Instance; ServiceLogger.Log(string.Format(@"Thor Server: Database server URL: {0}", serviceInfo.WebmateDatabaseServerPath())); ServiceLogger.Log(string.Format(@"Thor Server: Database location: {0}", serviceInfo.WebmateDatabaseLocation())); ServiceLogger.Log(@"Thor Server runner: Thorlink Integration Service has started"); } else { ServiceLogger.Log(@"Thor Server endpoint failed to run ..."); } return(result); }
private IEnumerable <ASDB> Execute(Expression <Func <ASDB, Boolean> > expression) { var asdbUri = ConfigurationManager.AppSettings.Get("AsdbUri"); var asdbDB = new ASDBModelContainer(new Uri(asdbUri)); var query = asdbDB.ASDBs.Where(expression) as DataServiceQuery <ASDB>; var result = new List <ASDB>(); if (query != null) { try { var response = (QueryOperationResponse <ASDB>)query.Execute(); while (response != null) { var part = new List <ASDB>(); part.AddRange(response); result.AddRange(part); var continuation = response.GetContinuation(); response = continuation != null?asdbDB.Execute(continuation) : null; } } catch (Exception ex) { ServiceLogger.Error(ex.Message, ex); return(result); } } return(result); }
private void ProcessXmlFile(string inFilename) { try { var invoice = XeroHelper.DeSerializeFromFilePath <XeroInvoice>(inFilename); if (invoice.Type == "ACCPAYCREDIT" || invoice.Type == "ACCRECCREDIT") { CreateCreditNode(inFilename, invoice); } else { CreateInvoice(inFilename, invoice); } } catch (XeroIntegrationException xiExc) { MoveFileToFailedFolder(inFilename); // Failed. XML Invoice with an invalid structure or NOT Found is moved to the Failed folder for further human action ServiceLogger.Log(string.Format(@"Xero Server Validation Error: {0} [Invoice filename: {1}]", xiExc.Message, inFilename)); } catch (Exception exc) { ServiceLogger.Log(string.Format(@"Xero Server Error: {0} [Invoice filename: {1}]", exc.Message, inFilename)); MoveFileToRetryFolder(inFilename); } }
public bool UpdateSalesForceVersion(string versionNumber, string accountName) { try { //We need to login to sales force to initiate the process.. //Get the credentials for logging into sales force.. var credentials = _salesForceCredentialFactory.Create(); if (_salesForceInterface.Login(credentials)) { //Update the sales force version of POS.. var isEnabled = _salesForceInterface.UpdateSalesForceVersion(accountName, versionNumber); //Since we have completed all the processing we will log out.. _salesForceInterface.Logout(); return(isEnabled); } } catch (Exception exception) { ServiceLogger.LogException("Exception in UpdateSalesForceVersion", exception); } return(false); }
private void CreateInvoice(string inFilename, XeroInvoice invoice) { var xeroInvoice = XeroInvoiceController.Instance.CreateInvoice(invoice); var createdInvoice = _repository.Create(xeroInvoice); if (createdInvoice.ValidationStatus == ValidationStatus.Error) { MoveFileToFailedFolder(inFilename); foreach (var message in createdInvoice.Warnings) { ServiceLogger.Log(string.Format(@"Xero Server Validation Error: {0} [Invoice Reference: {1}]", message.Message, xeroInvoice.Reference)); } } else { if (invoice.Payments != null && invoice.Payments.Item != null && invoice.Payments.Item.Count > 0) { var invoicePayments = XeroInvoiceController.Instance.GetInvoicePayments(invoice.Payments, createdInvoice); _repository.Create(invoicePayments); } MoveFileToSuccesfulFolder(inFilename); ServiceLogger.Log(string.Format(@"Invoice: {0} has been sent with reference number: {1}", xeroInvoice.Number, xeroInvoice.Reference)); } }
protected virtual int Execute() { if (!Paused && FailedToStart) { int timeDiff = TickCount.CompareTo(DateTime.Now); if (timeDiff <= 0) { try { FailedToStart = !StartServiceTask(); if (FailedToStart) { SetTickCountInMinutes(15); // This make startService() to be called every minute if it fails } } catch (Exception e) { ServiceLogger.LogException(String.Format(@"Error starting {0} service", ServiceName), e); } } } return(-1); }
protected bool runXero() { bool result; _appID = InitXeroIntegration(); if (_appID.Trim() != @"") { XeroIntegrationError error = XeroIntegrationManager.Instance.RunAppWithID(_appID); if (error == XeroIntegrationError.NoError) { result = true; } else { ServiceLogger.Log(XeroIntegrationManager.Instance.ErrorMessage); result = false; } } else { ServiceLogger.Log(string.Format(@"Invalid app ID: {0}", _appID)); result = false; } return(result); }
/// <summary> /// /// </summary> protected override bool StartRunner() { bool result = false; //........................................... ServiceLogger.Log(@"Starting SmartLink endpoint ..."); result = OpenServiceHost(); if (result) { ServiceLogger.Log(@"SmartLink endpoint is running ..."); ServiceInfo serviceInfo = ServiceInfo.Instance; ServiceLogger.Log(string.Format(@"SmartLink: Server IpAddress: {0}", "127.0.0.1")); ServiceLogger.Log(string.Format(@"SmartLink: Server Port: {0}", "11234")); // Any Chefmate initialization goes here!!!!! ServiceLogger.Log(@"SmartLink runner: Chefmate has started"); } else { ServiceLogger.Log(@"SmartLink endpoint failed to run ..."); } //........................................... return(result); }
public bool stopXero() { bool result; //........................................... if (_appID.Trim() != @"") { XeroIntegrationError error = XeroIntegrationManager.Instance.StopAppWithID(_appID); if (error == XeroIntegrationError.NoError) { result = true; } else { ServiceLogger.Log(XeroIntegrationManager.Instance.ErrorMessage); result = false; } } else { ServiceLogger.Log(string.Format(@"Invalid app ID: {0}", _appID)); result = false; } //........................................... return(result); }
/// <summary> /// /// </summary> /// <returns></returns> public bool Pause() { bool result = false; try { serviceHost_.Close(); result = true; } catch (SystemException e) { ServiceLogger.LogException(String.Format("{0} Service Host failed to pause.", serviceHost_.Description.Name), e); } catch (Exception e) { ServiceLogger.LogException(String.Format("{0} Service Host failed to pause: {1}", serviceHost_.Description.Name, e.Message), e); } finally { //inServiceHost.Close(); } return(result); }
protected override void OnStart(string[] args) { // start the service ILogger svcLogger = new ServiceLogger(base.EventLog); try { // - set current directory to the install location // - get executable name for file logger Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory; ProcessModule pm = Process.GetCurrentProcess().MainModule; string moduleName = pm.ModuleName.Split('.')[0]; ILogger logger = new MultiLogger(svcLogger, new FileLogger(@"C:\_qrsc\ServiceLogs\" + moduleName + ".{dddd}.log")); _ClientRef = Reference <ICoreClient> .Create(new CoreClientFactory(logger).Create()); _Server = new GridManagerServer(); _Server.Logger = logger; _Server.Client = _ClientRef; _Server.HostInstance = null; _Server.Start(); } catch (Exception ex) { svcLogger.Log(ex); } }
private static void UIThreadException(object sender, ThreadExceptionEventArgs e) { try { string errorMSG = "An application error occured. Please contact the administrator " + "with the following information:\n\n"; errorMSG += "Error Message: " + e.Exception.Message + "\n\nStack Trace:\n" + e.Exception.StackTrace; //result = MadaaMessageBox.ShowError(e.Exception.Message, errorMSG, "Windows Forms Error", MessageBoxButtons.AbortRetryIgnore); ServiceLogger.LogError("UIThreadException(), " + errorMSG); } catch { try { //XtraMessageBox.Show("Fata windows forms error", "Fatal Windows Forms Error", // MessageBoxButtons.OK, MessageBoxIcon.Stop); // MadaaMessageBox.ShowError("Fata windows forms error", "Fata windows forms error"); ServiceLogger.LogError("UIThreadException(), SmartWatcher application encountered a Fatal Error."); } finally { Application.Exit(); } } //Exit the program when the user slicks Abort. //if (result == DialogResult.Abort) //{ // Application.Exit(); //} }
public MultiThreadLoggerTests() { ConstHelper.AppPath = "C://"; logger = new ServiceLogger("test-service"); }
public ILogger CreateLogger(string categoryName) { var logger = new ServiceLogger(categoryName); _loggers.Add(logger); return logger; }
public void Dispose() { logger.Close(); logger = null; }