public string AddSample(string sampleList)
        {
            //AddResultsModel is used to return to the UI each SampleId if it was successfully added
            List<AddResultModel> results = new List<AddResultModel>();
            //Convert the json sample list to list of SampleSearchObject
            List<SampleSearchObject> samples = new SampleSearchObject().ConvertFromJson(sampleList);
            var errors = new List<ErrorObject>();
            var parameters = new Dictionary<string, string>();

            //Build the string comma separated to send it to the service
            var sampleComma = string.Empty;
            foreach (var sample in samples)
            {
                sampleComma += sample.SampleId + ",";
            }
            //Remove the trailing comma
            sampleComma = sampleComma.Remove(sampleComma.Length - 1);

            SampleManager sampleManager = null;
            parameters.Add("SampleIds", sampleComma);
            Thread sampleManagerThread = new Thread(() =>
            {
                //Send the request to the service and check if the connection to sam failed
                try
                {
                    sampleManager = new SampleManager(sampleComma);
                }
                catch
                {
                    errors.Add(new ErrorObject(ErrorKey.ERR_INTERNAL_SAM_CONNECTION, parameters));
                    LoggerFactory.GetLogger().InfoJson(Methods.Error_ToLogObject(Guid.NewGuid().ToString(), "OfferService", operationType.SAMCall.ToString(), "AdminUI".ToString(), parameters, errors));
                }
            });

            sampleManagerThread.Start();
            if (!sampleManagerThread.Join(10000))
            {
                errors.Add(new ErrorObject(ErrorKey.ERR_INTERNAL_SAM_CONNECTION, parameters));
                foreach (var sample in samples)
                {
                    var thisResult = new AddResultModel();
                    thisResult.SampleId = sample.SampleId;
                    thisResult.Added = false;
                    thisResult.Message = msgUtil.GetMessage(MessageKey.ERR_ADDSAMPLES_TIMEOUT);
                    results.Add(thisResult);
                }
            }

            //If the connection to sam was successful
            if (errors.Count() == 0)
            {
                //Loop through all the samples to be added
                foreach (var sample in samples)
                {
                    //By default it wasn t added
                    var Added = false;
                    string Message = string.Empty;

                    try
                    {
                        //Setting the fields of the new offer
                        OfferObject newOffer = new OfferObject();
                        newOffer.SampleId = sample.SampleId;
                        newOffer.LOI = sample.LOI;
                        newOffer.StudyStartDate = sample.StartDate;
                        newOffer.StudyEndDate = sample.EndDate;
                        //Default title Survey - {SampleId}
                        newOffer.Title = "Survey - " + sample.SampleId;

                        //If the sample does exist
                        if (sampleManager.CheckIfSampleExist(sample.SampleId))
                        {
                            //Get the specific sample from the service response
                            var newSample = sampleManager.GetOpenSampleObject(sample.SampleId);
                            newOffer.StudyId = newSample.StudyId;
                            newOffer.QuotaRemaining = newSample.MainstreamQuotaRemaining;
                            newOffer.IR = newSample.IR;
                            newOffer.OfferLink = System.Configuration.ConfigurationManager.AppSettings["OfferLink"] + "?{2}&oid={0}&tid={1}";
                            new OfferRepository().Insert(newOffer);

                            newOffer.Id = new OfferRepository().SelectOfferBySampleId(sample.SampleId).Id;
                            new RespondentAttributeRepository().UpdateOrRemove(newOffer.Id, newSample.Attributes);

                            Added = true;
                            Message = msgUtil.GetMessage(MessageKey.MSG_ADDSAMPLES_SUCCESSFULL);
                        }
                        else
                        {
                            Message = msgUtil.GetMessage(MessageKey.ERR_ADDSAMPLES_MISSINGDATA);
                        }
                    }
                    catch (Exception e)
                    {
                        LoggerFactory.GetLogger().Error(string.Format(msgUtil.GetMessage(MessageKey.LOG_ADDSAMPLES_EXCEPTION), sample.SampleId, sample.StartDate, sample.EndDate, sample.LOI), e);
                        Added = false;
                    }

                    //Add the result to the list
                    var thisResult = new AddResultModel();
                    thisResult.SampleId = sample.SampleId;
                    thisResult.Added = Added;
                    thisResult.Message = Message;
                    results.Add(thisResult);
                }
            }
            //Return JSON object to the javascript
            return JsonConvert.SerializeObject(results);
        }
Esempio n. 2
0
        public void Execute(IJobExecutionContext context)
        {
            LoggerFactory.SetThreadLogger("SuspendedOffersJob");
            LoggingUtility log = LoggerFactory.GetLogger();
            log.Info("SuspendedOffersJob started processing at " + DateTime.Now);
            IOfferRepository offerRep = new OfferRepository();

            //Getting all the suspended samples in order to check if they are still mainstream enabled
            var suspendedSamples = offerRep.GetSuspendedSampleIdsAndDates();

            //The maximum number of sent sample per request
            var MaxSamplePerRequest = 150;

            //This loop was made to send limited number of samples per request because the service returns HTTP response 414 for large numbers of samples
            for (var i = 0; i < suspendedSamples.Count(); i += MaxSamplePerRequest)
            {
                //Takes maximum number of samples starting index "i"
                var currentSamples = suspendedSamples.Skip(i).Take(MaxSamplePerRequest).ToList();
                var errors = new List<ErrorObject>();
                SampleManager sampleManager = null;

                //Check if the service threw an error
                try
                {
                    sampleManager = new SampleManager(new JobUtil().SampleListAsString(currentSamples));
                }
                catch
                {
                    //If the service threw an error it must be a connection error
                    errors.Add(new ErrorObject(ErrorKey.ERR_INTERNAL_SAM_CONNECTION, parameters));
                    log.ErrorJson(new Methods().Error_ToLogObject(Guid.NewGuid().ToString(), "OfferService", operationType.SAMCall.ToString(), "SuspendedOffersJob".ToString(), parameters, errors));
                }

                //If the service didn't throw any error continue
                if (errors.Count() == 0 && !sampleManager.ResponseHasUnwantedErrors())
                {
                    //Loop through all the samples
                    foreach (var sample in currentSamples)
                    {
                        //Adding the sample to the parameters
                        parameters.Add("SampleId", sample.SampleId.ToString());

                        //Inactivate the offer if the conditions are met (End date reached or no end date on the offer but 30 days has passed since the start date)
                        var expiration = sample.StudyEndDate;
                        if (expiration == null && sample.StudyStartDate != null)
                        {
                            expiration = sample.StudyStartDate.AddDays(30);
                        }

                        //Check if the sample exist in the service response
                        bool isMainstreamEnabled = sampleManager.CheckIfSampleExist(sample.SampleId);

                        if (isMainstreamEnabled)
                        {
                            //If sample is still enabled, try to activate the offer and update the respondent attributes and quota remaining
                            try
                            {
                                var newStatus = sampleManager.Activate(sample.SampleId, sample.Id);
                            }
                            // If offer activation throws an exception (E.G. connection was lost while trying to get quota cells), keep offer status as suspended
                            catch
                            {
                                offerRep.UpdateOfferStatus(sample.SampleId, (int)OfferStatus.Suspended);
                            }
                        }
                        else
                        {
                            if (expiration == null || expiration <= DateTime.Now)
                            {
                                offerRep.UpdateOfferStatus(sample.SampleId, (int)OfferStatus.Inactive);
                                log.Info("Sample " + sample.SampleId + " is not mainstream enabled and it expired (Expiration date: " + expiration + "). Setting sample to Inactive.");
                            }
                            else
                            {
                                log.Info("Sample " + sample.SampleId + " is not mainstream enabled and not expired yet. Sample will remain suspended.");
                            }
                        }
                        //Clear the dictionaries so we don t have duplicate keys
                        errors.Clear();
                        parameters.Clear();
                    }
                }
            }
            log.Info("SuspendedOffersJob ended processing at " + DateTime.Now);
        }
Esempio n. 3
0
        public void Execute(IJobExecutionContext context)
        {
            LoggerFactory.SetThreadLogger("ActiveOffersJob");
            LoggingUtility log = LoggerFactory.GetLogger();
            log.Info("ActiveOffersJob started processing at " + DateTime.Now);
            IOfferRepository offerRep = new OfferRepository();

            //Getting all the active samples in order to check if they are still mainstream enabled
            var activeSamples = offerRep.GetActiveSampleIds();

            //The maximum number of sent sample per request
            var MaxSamplePerRequest = 150;

            //This loop was made to send limited number of samples per request because the service returns HTTP response 414 for large numbers of samples
            for (var i = 0; i < activeSamples.Count(); i += MaxSamplePerRequest)
            {
                //Takes maximum number of samples starting index "i"
                var currentSamples = activeSamples.Skip(i).Take(MaxSamplePerRequest).ToList();
                var errors = new List<ErrorObject>();
                SampleManager sampleManager = null;

                //Check if the service threw an error
                try
                {
                    sampleManager = new SampleManager(new JobUtil().SampleListAsString(currentSamples));
                }
                catch
                {
                    //If the service threw an error it must be a connection error
                    log.Error("Offer service could not connect to SAM for unknown reasons.");
                }

                //If the service didn't throw any error and SAM didn't reply with errors continue
                if (errors.Count() == 0 && !sampleManager.ResponseHasUnwantedErrors())
                {
                    //Loop through all the active samples
                    foreach (var sample in currentSamples)
                    {
                        //Adding the sample to the parameters
                        parameters.Add("SampleId", sample.SampleId.ToString());
                        //Check if the sample exist in the service response
                        bool isMainstreamEnabled = sampleManager.CheckIfSampleExist(sample.SampleId);
                        //If the sample is not mainstream enabled we update the active status to 2(Suspended)
                        if (!isMainstreamEnabled)
                        {
                            offerRep.UpdateOfferStatus(sample.SampleId, (int)OfferStatus.Suspended);
                            //Log that the sample id will be suspended
                            log.Info("Suspending sample " + sample.SampleId + " as it is not mainstream enabled.");
                        }
                        //If the sample is mainstream enabled we should Update and Insert the correspondent attributes in the Respondent attributes table
                        else
                        {
                            //If sample is still enabled update the respondent attributes and quota remaining, try to activate the offer
                            try
                            {
                                var newStatus = sampleManager.Activate(sample.SampleId, sample.Id);
                                if (newStatus == (int)OfferStatus.Pending)
                                {
                                    new OfferRepository().UpdateRetryCount(sample.SampleId, 0);
                                }
                            }
                            // If offer activation throws an exception (E.G. connection was lost while trying to get quota cells), keep offer status as active
                            catch
                            {
                                offerRep.UpdateOfferStatus(sample.SampleId, (int)OfferStatus.Active);
                            }
                        }

                        //Clear the dictionaries so we don't have duplicate keys
                        errors.Clear();
                        parameters.Clear();
                    }
                }
            }
            log.Info("ActiveOffersJob ended processing at " + DateTime.Now);
        }
Esempio n. 4
0
        public void Execute(IJobExecutionContext context)
        {
            LoggerFactory.SetThreadLogger("PendingOffersJob");
            LoggingUtility log = LoggerFactory.GetLogger();
            log.Info("PendingOffersJob started processing at " + DateTime.Now);
            SampleManager sampleManager = null;
            var responseSuccessfull = false;
            var maxRetries = Convert.ToInt32(ConfigurationManager.AppSettings["PendingOffersJobMaxRetries"]);
            IOfferRepository offerRep = new OfferRepository();
            Stopwatch sw = new Stopwatch();

            var maxSamplePerRequest = 150;

            //Getting all the pending samples
            var pendingSamples = offerRep.GetPendingSampleIdsAndRetryCount();

            //If there are at least 1 pending sample
            if (pendingSamples.Count() > 0)
            {
                for (var i = 0; i < pendingSamples.Count(); i += maxSamplePerRequest)
                {
                    bool responseHasUnwantedError = true;
                    //takes the maximum number of samples allowed in the URL
                    var currentSamples = pendingSamples.Skip(i).Take(maxSamplePerRequest).ToList();
                    var errors = new List<ErrorObject>();

                    foreach (var sample in currentSamples)
                    {
                        offerRep.UpdateRetryCount(sample.SampleId, ++sample.RetryCount);
                        log.Info("Attempt #" + sample.RetryCount + " to update the status of Offer having sampleId: " + sample.SampleId);
                    }

                    try
                    {
                        sw.Start();
                        sampleManager = new SampleManager(new JobUtil().SampleListAsString(currentSamples));
                        sw.Stop();
                        if (sw.ElapsedMilliseconds > 30000)
                        {
                            log.Warn("SAM connection returned response after " + sw.ElapsedMilliseconds + " milliseconds.");
                        }
                        responseSuccessfull = true;
                        responseHasUnwantedError = sampleManager.ResponseHasUnwantedErrors();
                    }
                    catch
                    {
                        //If the service threw an error it must be a connection error
                        responseSuccessfull = false;
                        log.Error("Offer service could not connect to SAM for unknown reasons.");
                    }

                    //Loop through the pending samples

                    foreach (var sample in currentSamples)
                    {
                        var suspend = false;
                        parameters.Add("SampleId", sample.SampleId.ToString());
                        //If SAM response was successful update the sample accordingly
                        if (responseSuccessfull && !responseHasUnwantedError)
                        {
                            var isMainstreamEnabled = sampleManager.CheckIfSampleExist((int)sample.SampleId);
                            if (isMainstreamEnabled)
                            {
                                //If sample is still enabled update the respondent attributes and quota remaining
                                var newStatus = (int)OfferStatus.Pending;
                                // Try to activate the offer
                                try
                                {
                                    newStatus = sampleManager.Activate(sample.SampleId, sample.Id);
                                }
                                // If offer activation throws an exception (E.G. connection was lost while trying to get quota cells), keep offer status as pending
                                catch
                                {
                                    newStatus = (int)OfferStatus.Pending;
                                }
                                // If the new offer status isn't active and the retry count exceeded the max retries ==> Suspend the offer
                                finally
                                {
                                    if (newStatus != (int)OfferStatus.Active && sample.RetryCount >= maxRetries)
                                    {
                                        suspend = true;
                                        //Log that the sample id will be suspended because the current status is not active and the maximum retries is reached
                                        log.Info("Suspending sample " + sample.SampleId + " as the maximum retry count is reached.");
                                    }
                                }
                            }
                            else
                            {
                                suspend = true;
                                //Log that the sample id will be suspended because the sample was not mainstream enabled
                                log.Info("Suspending sample " + sample.SampleId + " as it is not mainstream enabled.");
                            }
                        }
                        // If SAM response failed update the retry count
                        // Or response has unwanted errors like timeout or unexpected sql error
                        // wen check if the sample has hit the max retries count
                        // and suspend it if it did
                        else
                        {
                            //If the max retries is reached suspend the offer
                            if (sample.RetryCount >= maxRetries)
                            {
                                suspend = true;
                                //Log that the sample id will be suspended because the max retries is reached
                                log.Info("Suspending sample " + sample.SampleId + " as the maximum retry count is reached.");
                            }
                        }

                        //If suspend flag is true update the row in the database
                        if (suspend)
                        {
                            offerRep.UpdateOfferStatus(sample.SampleId, (int)OfferStatus.Suspended);
                        }
                        errors.Clear();
                        parameters.Clear();
                    }
                }
            }
            log.Info("PendingOffersJob ended processing at " + DateTime.Now);
        }