예제 #1
0
 public OneStopUtils(IConfiguration Configuration, ILogger logger)
 {
     this.Configuration = Configuration;
     _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);
     _onestopRestClient = OneStopUtils.SetupOneStopClient(Configuration, logger);
     _logger            = logger;
 }
예제 #2
0
        private string HandleSBNErrorNotification(string inputXML)
        {
            string result = "200";
            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNErrorNotification1));
            SBNErrorNotification1 errorNotification;

            using (TextReader reader = new StringReader(inputXML))
            {
                errorNotification = (SBNErrorNotification1)serializer.Deserialize(reader);
            }


            // check to see if it is simply a problem with an old account number.
            if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11845")) // Transaction not allowed - Duplicate Client event exists )
            {
                Log.Logger.Error($"CRA has rejected the message due to an incorrect business number.  The business in question may have had multiple business numbers in the past and the number in the record is no longer valid.  Please correct the business number for record with partnernote of {errorNotification.header.partnerNote}");
            }
            else if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11409")) // Old account number.
            {
                Log.Logger.Information("Error is old account number is already associated with another account.  Retrying.");
                // retry the request with a higher increment.

                string licenceGuid   = OneStopUtils.GetGuidFromPartnerNote(errorNotification.header.partnerNote);
                int    currentSuffix = OneStopUtils.GetSuffixFromPartnerNote(errorNotification.header.partnerNote, Log.Logger);

                string cacheKey    = "_BPAR_" + licenceGuid;
                int    suffixLimit = 10;
                Log.Logger.Information($"Reading cache value for key {cacheKey}");

                _cache.TryGetValue(cacheKey, out suffixLimit);

                // sanity check
                if (currentSuffix < suffixLimit)
                {
                    currentSuffix++;
                    Log.Logger.Information($"Starting resend of licence creation message, with new value of {currentSuffix}");

                    var patchRecord = new MicrosoftDynamicsCRMadoxioLicences()
                    {
                        AdoxioBusinessprogramaccountreferencenumber = currentSuffix.ToString()
                    };
                    _dynamicsClient.Licenceses.Update(licenceGuid, patchRecord);

                    BackgroundJob.Schedule(() => new OneStopUtils(Configuration, _cache).SendLicenceCreationMessageREST(null, licenceGuid, currentSuffix.ToString("D3")) // zero pad 3 digit.
                                           , TimeSpan.FromSeconds(30));                                                                                                  // Try again after 30 seconds
                }
                else
                {
                    Log.Logger.Error($"Skipping resend of licence creation message as there have been too many tries({currentSuffix} - {suffixLimit}) Partner Note is partner note {errorNotification.header.partnerNote}");
                }
            }
            else
            {
                Log.Logger.Error($"Received error notification for record with partner note {errorNotification.header.partnerNote} Error Code is  {errorNotification.body.validationErrors[0].errorMessageNumber}. Error Text is {errorNotification.body.validationErrors[0].errorMessageText} {inputXML}");
            }

            return(result);
        }
예제 #3
0
        public OneStopUtils(IConfiguration Configuration, IMemoryCache cache)
        {
            this.Configuration = Configuration;
            _cache             = cache;
            _dynamics          = DynamicsSetupUtil.SetupDynamics(Configuration);

            _onestopRestClient = OneStopUtils.SetupOneStopClient(Configuration, Log.Logger);
        }
        public OneStopUtils(IConfiguration configuration, IMemoryCache cache)
        {
            this._configuration = configuration;
            _cache = cache;


            _onestopRestClient = OneStopUtils.SetupOneStopClient(configuration, Log.Logger);
        }
예제 #5
0
        private string HandleSBNErrorNotification(string inputXML)
        {
            string result = "200";
            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNErrorNotification1));
            SBNErrorNotification1 errorNotification;

            using (TextReader reader = new StringReader(inputXML))
            {
                errorNotification = (SBNErrorNotification1)serializer.Deserialize(reader);
            }
            _logger.LogError("Received error notification");
            _logger.LogError(inputXML);

            // check to see if it is simply a problem with an old account number.
            if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11845")) // Transaction not allowed - Duplicate Client event exists )
            {
                _logger.LogError("****************************************************");
                _logger.LogError("CRA has rejected the message due to an incorrect business number.  The business in question may have had multiple business numbers in the past and the number in the record is no longer valid.  Please correct the business number.");
                _logger.LogError("****************************************************");
            }
            else if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11409")) // Old account number.
            {
                _logger.LogInformation("Error is old account number is already associated with another account.  Retrying.");
                // retry the request with a higher increment.

                string licenceGuid   = OneStopUtils.GetGuidFromPartnerNote(errorNotification.header.partnerNote);
                int    currentSuffix = OneStopUtils.GetSuffixFromPartnerNote(errorNotification.header.partnerNote, _logger);

                // sanity check
                if (currentSuffix < 10)
                {
                    currentSuffix++;
                    _logger.LogInformation($"Starting resend of licence creation message, with new value of {currentSuffix}");
                    BackgroundJob.Schedule(() => new OneStopUtils(Configuration, _logger).SendLicenceCreationMessageREST(null, licenceGuid, currentSuffix.ToString("D3")) // zero pad 3 digit.
                                           , TimeSpan.FromMinutes(1));                                                                                                    // Try again after 1 minutes.
                }
                else
                {
                    _logger.LogInformation($"Skipping resend of licence creation message as there have been too many tries({currentSuffix})");
                }
            }

            return(result);
        }
        private string HandleSBNErrorNotification(string inputXML)
        {
            string result = "200";
            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNErrorNotification1));
            SBNErrorNotification1 errorNotification;

            using (TextReader reader = new StringReader(inputXML))
            {
                errorNotification = (SBNErrorNotification1)serializer.Deserialize(reader);
            }
            _logger.LogError("Received error notification");
            _logger.LogError(inputXML);

            // check to see if it is simply a problem with an old account number.

            if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11409")) // Old account number.
            {
                _logger.LogInformation("Error is old account number is already associated with another account.");
                // retry the request with a higher increment.

                string licenceGuid   = OneStopUtils.GetGuidFromPartnerNote(errorNotification.header.partnerNote);
                int    currentSuffix = OneStopUtils.GetSuffixFromPartnerNote(errorNotification.header.partnerNote);

                // sanity check
                if (currentSuffix < 10)
                {
                    currentSuffix++;
                    _logger.LogInformation($"Starting resend of licence creation message, attempt {currentSuffix}");
                    BackgroundJob.Enqueue(() => new OneStopUtils(Configuration, _logger).SendLicenceCreationMessageREST(null, licenceGuid, currentSuffix.ToString()));
                }
                else
                {
                    _logger.LogInformation($"Skipping resend of licence creation message as there have been too many tries({currentSuffix})");
                }
            }

            return(result);
        }
        private string HandleSBNCreateProgramAccountResponse(string inputXML)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            Log.Logger.Information("Reached HandleSBNCreateProgramAccountResponse");
            if (!_env.IsProduction())
            {
                Log.Logger.Information($"InputXML is: {inputXML}");
            }

            string httpStatusCode = "200";

            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNCreateProgramAccountResponse1));
            SBNCreateProgramAccountResponse1 licenseData;

            using (TextReader reader = new StringReader(inputXML))
            {
                licenseData = (SBNCreateProgramAccountResponse1)serializer.Deserialize(reader);
            }


            string licenceNumber = OneStopUtils.GetLicenceNumberFromPartnerNote(licenseData.header.partnerNote);

            Log.Logger.Information($"Getting licence with number of {licenceNumber}");

            // Get licence from dynamics

            string businessProgramAccountNumber = "1";
            MicrosoftDynamicsCRMadoxioLicences licence;

            string filter = $"adoxio_licencenumber eq '{licenceNumber}'";

            try
            {
                licence = dynamicsClient.Licenceses.Get(filter: filter).Value.FirstOrDefault();
                businessProgramAccountNumber = licenseData.body.businessProgramAccountNumber.businessProgramAccountReferenceNumber;
            }
            catch (Exception e)
            {
                Log.Logger.Error($"Unable to get licence data for licence number {licenceNumber} {e.Message}");
                licence = null;
            }


            if (licence == null)
            {
                Log.Logger.Information("licence is null - returning 400.");
                httpStatusCode = "400";
            }
            else
            {
                Log.Logger.Information("Licence record retrieved from Dynamics.");
                //save the program account number to dynamics

                int    tempBpan      = int.Parse(businessProgramAccountNumber);
                string sanitizedBpan = tempBpan.ToString();

                MicrosoftDynamicsCRMadoxioLicences pathLicence = new MicrosoftDynamicsCRMadoxioLicences()
                {
                    AdoxioBusinessprogramaccountreferencenumber = sanitizedBpan,
                    AdoxioOnestopsent = true
                };
                Log.Logger.Information("Sending update to Dynamics for BusinessProgramAccountNumber.");
                try
                {
                    dynamicsClient.Licenceses.Update(licence.AdoxioLicencesid, pathLicence);
                    Log.Logger.Information($"ONESTOP Updated Licence {licenceNumber} record {licence.AdoxioLicencesid} to {businessProgramAccountNumber}");
                }
                catch (HttpOperationException odee)
                {
                    Log.Logger.Error(odee, "Error updating Licence {licence.AdoxioLicencesid}");
                    // fail if we can't get results.
                    throw (odee);
                }

                //Trigger the Send ProgramAccountDetailsBroadcast Message
                BackgroundJob.Enqueue(() => new OneStopUtils(_configuration, _cache).SendProgramAccountDetailsBroadcastMessageRest(null, licence.AdoxioLicencesid));

                Log.Logger.Information("send program account details broadcast done.");
            }

            return(httpStatusCode);
        }
        private string HandleSBNCreateProgramAccountResponse(string inputXML)
        {
            _logger.LogInformation("Reached HandleSBNCreateProgramAccountResponse");
            _logger.LogInformation($"inputXML is: {inputXML}");

            string httpStatusCode = "200";

            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNCreateProgramAccountResponse1));
            SBNCreateProgramAccountResponse1 licenseData;

            using (TextReader reader = new StringReader(inputXML))
            {
                licenseData = (SBNCreateProgramAccountResponse1)serializer.Deserialize(reader);
                _logger.LogInformation(inputXML);
            }


            string licenceNumber = OneStopUtils.GetLicenceNumberFromPartnerNote(licenseData.header.partnerNote);

            _logger.LogInformation($"Getting licence with number of {licenceNumber}");

            // Get licence from dynamics
            var filter = $"adoxio_licencenumber eq '{licenceNumber}'";
            MicrosoftDynamicsCRMadoxioLicences licence = _dynamicsClient.Licenceses.Get(filter: filter).Value.FirstOrDefault();

            if (licence == null)
            {
                _logger.LogInformation("licence is null - returning 400.");
                httpStatusCode = "400";
            }
            else
            {
                _logger.LogInformation($"Licence record retrieved from Dynamics.");
                //save the program account number to dynamics
                var businessProgramAccountNumber = licenseData.body.businessProgramAccountNumber.businessProgramAccountReferenceNumber;
                MicrosoftDynamicsCRMadoxioLicences pathLicence = new MicrosoftDynamicsCRMadoxioLicences()
                {
                    AdoxioBusinessprogramaccountreferencenumber = businessProgramAccountNumber
                };
                _logger.LogInformation($"Sending update to Dynamics for BusinessProgramAccountNumber.");
                try
                {
                    _dynamicsClient.Licenceses.Update(licence.AdoxioLicencesid, pathLicence);
                    _logger.LogInformation($"Updated Licence record {licence.AdoxioLicencesid} to {businessProgramAccountNumber}");
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error updating Licence");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                    // fail if we can't get results.
                    throw (odee);
                }

                //Trigger the Send ProgramAccountDetailsBroadcast Message
                BackgroundJob.Enqueue(() => new OneStopUtils(Configuration, _logger).SendProgramAccountDetailsBroadcastMessageREST(null, licence.AdoxioLicencesid));

                _logger.LogInformation("send program account details broadcast done.");
            }

            return(httpStatusCode);
        }
 public LdbExport(IConfiguration Configuration)
 {
     this.Configuration = Configuration;
     this._dynamics     = OneStopUtils.SetupDynamics(Configuration);
 }
예제 #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IDynamicsClient dynamicsClient = OneStopUtils.SetupDynamics(Configuration);

            services.AddSingleton <IReceiveFromHubService>(new ReceiveFromHubService(dynamicsClient, _loggerFactory.CreateLogger("IReceiveFromHubService"), Configuration));

            services.AddSingleton <ILogger>(_loggerFactory.CreateLogger("OneStopController"));

            services.AddMvc(config =>
            {
                if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                }
            });

            // Other ConfigureServices() code...

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "JAG LCRB One Stop Service", Version = "v1"
                });
            });

            services.AddIdentity <IdentityUser, IdentityRole>()
            .AddDefaultTokenProviders();

            if (!string.IsNullOrEmpty(Configuration["JWT_TOKEN_KEY"]))
            {
                // Configure JWT authentication
                services.AddAuthentication(o =>
                {
                    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    o.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(o =>
                {
                    o.SaveToken                 = true;
                    o.RequireHttpsMetadata      = false;
                    o.TokenValidationParameters = new TokenValidationParameters()
                    {
                        RequireExpirationTime = false,
                        ValidIssuer           = Configuration["JWT_VALID_ISSUER"],
                        ValidAudience         = Configuration["JWT_VALID_AUDIENCE"],
                        IssuerSigningKey      = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT_TOKEN_KEY"]))
                    };
                });
            }

            services.AddHangfire(config =>
            {
                // Change this line if you wish to have Hangfire use persistent storage.
                config.UseMemoryStorage();
                // enable console logs for jobs
                config.UseConsole();
            });

            // health checks.
            services.AddHealthChecks(checks =>
            {
                checks.AddValueTaskCheck("HTTP Endpoint", () => new
                                         ValueTask <IHealthCheckResult>(HealthCheckResult.Healthy("Ok")));
            });
        }