public void Log(string content, int level = LogLevel.Information)
        {
            try
            {
                if (level == LogLevel.Information)
                {
                    _logger.Info(content);
                }
                if (level == LogLevel.Debug)
                {
                    _logger.Debug(content);
                }
                if (level == LogLevel.Error)
                {
                    _logger.Error(content);
                }

                var logEntry = new ExecutionLog();
                logEntry.LogContent  = content;
                logEntry.LogLevel    = level;
                logEntry.DateCreated = DateTime.UtcNow;
                Entities.ExecutionLogs.Add(logEntry);
                Entities.SaveChanges();
            }
            catch (Exception ex)
            {
                // Swallow the exception! - this is a logger
                //
                _logger.Info($"Failed attempt to add Execution Log ({level}) {content}");
                _logger.Error(ex);
            }
        }
        public async Task <ApplicationUser> ProvisionNewAccount(string emailAddress, string domain)
        {
            var user = new ApplicationUser()
            {
                Email    = emailAddress,
                UserName = emailAddress,
            };

            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                var createUserResult = await _userManager.CreateAsync(user);

                if (!createUserResult.Succeeded)
                {
                    _logger.Error(
                        $"Unable to create new User for {user.Email}/{user.UserName} - " +
                        $"{createUserResult.Errors.ToCommaDelimited()}");
                    return(null);
                }

                _logger.Info($"Created new User {user.Email}");

                var addToRoleResult = await _userManager.AddToRoleAsync(user.Id, SecurityConfig.UserRole);

                if (!addToRoleResult.Succeeded)
                {
                    _logger.Error(
                        $"Unable to add User {user.Email}/{user.UserName} to {SecurityConfig.UserRole} - " +
                        $"{createUserResult.Errors.ToCommaDelimited()}");
                    return(null);
                }

                _logger.Info($"Added User {user.Email} to Role {SecurityConfig.UserRole}");

                var login = new UserLoginInfo("Shopify", domain);

                var addLoginResult = await _userManager.AddLoginAsync(user.Id, login);

                if (!addLoginResult.Succeeded)
                {
                    _logger.Error(
                        $"Unable to add Login for User {user.Email}/{user.UserName} - " +
                        $"{addLoginResult.Errors.StringJoin(";")}");
                    return(null);
                }

                _logger.Info($"Added User {user.Email} Login {login.LoginProvider} / {login.ProviderKey}");

                transaction.Commit();
            }

            return(user);
        }
 private void ProcessOrderAux(long shopifyOrderId)
 {
     try
     {
         ProcessOrder(shopifyOrderId);
     }
     catch (Exception ex)
     {
         _systemLogger.Error(ex);
         _logService.Log($"Encounter error syncing Payments for Shopify Order {shopifyOrderId}");
         _syncOrderRepository.IncreaseOrderErrorCount(shopifyOrderId);
     }
 }
示例#4
0
        public void OrderSyncInChildScope(ConcurrentQueue <long> queue)
        {
            // NOTE: it's necessary to catch Exceptions, because this is running in its own thread
            try
            {
                var instanceId = _connectionContext.InstanceId;
                var monitorId  = _monitoringService.CurrentScopeMonitorId;

                using (var childScope = _lifetimeScope.BeginLifetimeScope())
                {
                    var childConnectionContext = childScope.Resolve <InstanceContext>();
                    var childAcumaticaContext  = childScope.Resolve <AcumaticaHttpContext>();
                    var childOrderSync         = childScope.Resolve <AcumaticaOrderPut>();
                    var monitoringService      = childScope.Resolve <JobMonitoringService>();

                    _logger.Debug(
                        $"OrderSyncInChildScope - Acumatica Context: {childAcumaticaContext.ObjectIdentifier}");

                    childConnectionContext.Initialize(instanceId);
                    monitoringService.RegisterCurrentScopeMonitorId(monitorId);

                    childAcumaticaContext.SessionRun(() => childOrderSync.RunQueue(queue));
                }
            }
            catch (Exception ex)
            {
                // NOTE => must do this, as an uncaught exception will bring the entire process down
                //
                _logger.Error(ex);
            }
        }
示例#5
0
        public bool Log(LogLevel logLevel, Func <string> messageFunc, Exception exception = null)
        {
            if (_logger == null)
            {
                return(false);
            }
            if (messageFunc == null && exception == null)
            {
                return(true);
            }


            if (logLevel == LogLevel.Trace && _logger.IsTraceEnabled)
            {
                _logger.Trace(messageFunc());
            }
            if (logLevel == LogLevel.Debug && _logger.IsDebugEnabled)
            {
                _logger.Debug(messageFunc());
            }
            if (logLevel == LogLevel.Info && _logger.IsInfoEnabled)
            {
                _logger.Info(messageFunc());
            }
            if (logLevel == LogLevel.Warn && _logger.IsWarnEnabled)
            {
                _logger.Warn(messageFunc());
            }
            if (logLevel == LogLevel.Error && _logger.IsErrorEnabled)
            {
                var message = messageFunc();
                if (!message.IsNullOrEmpty())
                {
                    _logger.Error(message);
                }
                _logger.Error(exception);
            }
            if (logLevel == LogLevel.Fatal && _logger.IsFatalEnabled)
            {
                _logger.Fatal(messageFunc());
            }
            return(true);
        }
示例#6
0
 public void TestConnection()
 {
     try
     {
         _executionLogService.Log("Connecting to Shopify...");
         _orderApi.RetrieveCount();
         _stateRepository.UpdateSystemState(x => x.ShopifyConnState, StateCode.Ok);
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         _stateRepository.UpdateSystemState(x => x.ShopifyConnState, StateCode.SystemFault);
     }
 }
示例#7
0
 public void Login()
 {
     try
     {
         var path     = $"/entity/auth/login";
         var content  = _credentials.AuthenticationJson;
         var response = Post(path, content, excludeVersion: true);
         IsLoggedIn = true;
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         throw;
     }
 }
示例#8
0
        public void RunOrder(long shopifyOrderId)
        {
            try
            {
                CorrectSalesOrderWithUnknownRef(shopifyOrderId);

                // *** SAVE THIS, JONES! - This little branch of logic increases throughput!!
                //
                var orderPreAction = _pendingActionService.Create(shopifyOrderId).OrderAction;
                if (orderPreAction.ActionCode == ActionCode.UpdateInAcumatica && !orderPreAction.IsValid)
                {
                    _acumaticaOrderPaymentPut.ProcessOrder(shopifyOrderId);
                }

                var orderAction = _pendingActionService.Create(shopifyOrderId).OrderAction;
                if (!orderAction.IsValid)
                {
                    _logService.Log(LogBuilder.SkippingInvalidShopifyOrder(shopifyOrderId));
                    return;
                }

                if (orderAction.ActionCode == ActionCode.CreateInAcumatica)
                {
                    CreateSalesOrder(shopifyOrderId);
                    _acumaticaOrderPaymentPut.ProcessOrder(shopifyOrderId);
                    return;
                }

                if (orderAction.ActionCode == ActionCode.UpdateInAcumatica)
                {
                    _acumaticaOrderPaymentPut.ProcessOrder(shopifyOrderId);
                    UpdateExistingSalesOrder(shopifyOrderId);
                    return;
                }

                if (orderAction.ActionCode == ActionCode.CreateBlankSyncRecord)
                {
                    CreateBlankSalesOrderRecord(shopifyOrderId);
                    return;
                }
            }
            catch (Exception ex)
            {
                _systemLogger.Error(ex);
                _logService.Log($"Encountered error syncing Shopify Order {shopifyOrderId}");
                _syncOrderRepository.IncreaseOrderErrorCount(shopifyOrderId);
            }
        }
示例#9
0
        private void PushFulfillmentToShopifyAux(AcumaticaSoShipment salesOrderShipment)
        {
            try
            {
                CorrectFulfillmentWithUnknownRef(salesOrderShipment.AcumaticaShipmentNbr);

                var syncReadiness = _fulfillmentStatusService.Validate(salesOrderShipment);

                if (syncReadiness.Success)
                {
                    PushFulfillmentToShopify(salesOrderShipment.AcumaticaShipmentNbr);
                }
            }
            catch (Exception ex)
            {
                _pushLogger.Error(ex);
                _logService.Log($"Encounter error syncing {salesOrderShipment.LogDescriptor()}");
                _syncOrderRepository
                .IncreaseOrderErrorCount(salesOrderShipment.AcumaticaSalesOrder.ShopifyOrder.ShopifyOrderId);
                throw;
            }
        }
示例#10
0
        private void ExecuteJob(Guid instanceId, Action action, long jobMonitorId)
        {
            _instanceContext.Initialize(instanceId);
            _jobMonitoringService.RegisterCurrentScopeMonitorId(jobMonitorId);
            var monitor = _jobMonitoringService.RetrieveCurrentScopeMonitor();

            try
            {
                if (!InstanceLock.Acquire(instanceId.ToString()))
                {
                    var msg = $"Failed to acquire lock '{InstanceLock.MethodName}'";
                    _executionLogService.Log(msg, LogLevel.Debug);
                    return;
                }

                if (_jobMonitoringService.IsCorrupted(jobMonitorId))
                {
                    var msg = $"Job is missing or corrupted";
                    _executionLogService.Log(msg);
                    _jobMonitoringService.CleanupPostExecution(jobMonitorId);
                    InstanceLock.Free(instanceId.ToString());
                    return;
                }

                if (_jobMonitoringService.IsInterrupted(jobMonitorId))
                {
                    var msg = $"Job is missing or has received stop signal";
                    _executionLogService.Log(msg);
                    _jobMonitoringService.CleanupPostExecution(jobMonitorId);
                    InstanceLock.Free(instanceId.ToString());
                    return;
                }

                // Phew - we made it! Execute the requested task
                //
                _executionLogService.Log(
                    BackgroundJobType.Name[monitor.BackgroundJobType] + " - starting");

                action();

                _jobMonitoringService.CleanupPostExecution(jobMonitorId);

                // *** IMPORTANT - do not refactor this to use-finally, else it will
                // ... break concurrency locking
                //
                InstanceLock.Free(instanceId.ToString());
            }
            catch (Exception ex)
            {
                InstanceLock.Free(instanceId.ToString());

                // If this is One-Time Job, this will remove the Monitor now that the Job has failed
                //
                _jobMonitoringService.CleanupPostExecution(jobMonitorId);

                _executionLogService.Log(
                    BackgroundJobType.Name[monitor.BackgroundJobType] + " - encountered an error");
                _logger.Error(ex);
            }
            finally
            {
                _executionLogService.Log(
                    BackgroundJobType.Name[monitor.BackgroundJobType] + " - finished");
            }
        }
示例#11
0
        // No [IdentityProcessor] attribute - the Identity will be dictated by "shop" i.e. domain
        //
        public ActionResult Return(string code, string shop, string returnUrl)
        {
            // Attempt to locate the identity, as there maybe a valid Domain + Access Token
            // This needs to happen before try-catch, else failure will make it attempt to
            // update using System State Repository
            //
            var userId = _provisioningService.RetrieveUserIdByShopifyDomain(shop);

            var identity = _identityService.HydrateIdentity(userId);

            if (!identity.IsAuthenticated)
            {
                throw new HttpException(
                          (int)HttpStatusCode.Unauthorized, $"Attempt to login using invalid Shopify store {shop}");
            }

            try
            {
                if (!VerifyShopifyHmac())
                {
                    throw new Exception("Failed HMAC verification from Shopify Return");
                }


                if (BackButtonDetected(code))
                {
                    return(Redirect("Domain"));
                }

                // Get Key and Secret credentials from config file - and there is not Instance-specific.
                //
                var credentials = ShopifyCredentialsConfig.Settings.ToApiKeyAndSecret(shop);
                _shopifyHttpContext.Initialize(credentials);

                // Refresh the Shopify Access Token
                //
                var codeHash    = _hmacCrypto.ToBase64EncodedSha256(code);
                var accessToken = _oAuthApi.RetrieveAccessToken(code, credentials);
                _connectionContext.UpdateShopifyCredentials(shop, accessToken, codeHash);

                // Issue ASP.NET sign-in cookie
                //
                _identityService.SignInAspNetUser(identity.AspNetUserId);
                HttpContext.SetIdentity(identity);

                if (identity.SystemState.IsRandomAccessMode)
                {
                    return(Redirect(GlobalConfig.Url("/Sync/EndToEnd")));
                }
                else
                {
                    return(View(new ReturnModel
                    {
                        IsWizardMode = true,
                        IsConnectionOk = true,
                    }));
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                _stateRepository.UpdateSystemState(x => x.ShopifyConnState, StateCode.SystemFault);
                throw;
            }
        }