public OfferObject OfferObject(int status, bool test)
 {
     OfferObject offer = new OfferObject();
     offer.Status = status;
     offer.TestOffer = test;
     offer.Id = new Guid();
     offer.SampleId = 1;
     return offer;
 }
        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);
        }
        private bool UpdateQuotaCell(OfferObject offerObject, SteamStudyObject steamStudyObject, QuotasLiveObject quotasLiveObject)
        {
            var sampleId = offerObject.SampleId.Value;
            LoggingUtility log = LoggerFactory.GetLogger();

            try
            {
                QuotaMappingRepository quotaMappingRepository = new QuotaMappingRepository();
                GMISampleObject sampleObject = new SampleMappingRepository().SelectByID(steamStudyObject.SampleId);

                List<GMISampleObject> GMISampleObjectList = new List<GMISampleObject>();
                GMISampleObjectList.Add((sampleObject != null) ? sampleObject : new GMISampleObject());
                List<GMIQuotaObject> GMIQuotasList = quotaMappingRepository.SelectBySampleID(steamStudyObject.SampleId).ToList();

                bool needUpdate = false;
                foreach (GMIQuotaObject gmiQuotaObject in GMIQuotasList)
                {
                    var quota = quotasLiveObject.QuotasLiveList.Where(p => p.InternalQuotaId == gmiQuotaObject.InternalQuotaId).Where(p => p.InternalSampleId == sampleObject.InternalSampleId).ToList();
                    if (quota.Count() > 0 && gmiQuotaObject.QuotaRemaining != quota[0].QuotaRemaining)
                    {
                        gmiQuotaObject.QuotaRemaining = quota[0].QuotaRemaining;
                        quotaMappingRepository.Update(gmiQuotaObject);
                        needUpdate = true;
                    }
                }

                if (needUpdate)
                {
                    // There was a change in quota remaining, update the quota expressions XML to reflect the new values
                    log.Debug("Update the quota remaining for sample: " + sampleId);
                    GMISampleQuotasObject gmiSampleQuotasObject = new GMISampleQuotasObject();
                    gmiSampleQuotasObject.GMIQuotasList = GMIQuotasList;
                    gmiSampleQuotasObject.GMISampleQuotasList = GMISampleObjectList;

                    new SteamStudy().UpdateQuotaExpression(steamStudyObject, gmiSampleQuotasObject);
                    new QuotaExpressionRepository().updateQuotaExpressionsXML(steamStudyObject);
                }
            }
            catch (Exception e)
            {
                log.Error("An error occurred while trying to update the quota cells for offerId " + offerObject.Id.ToString(), e);
                throw;
            }

            return true;
        }
        private bool CreateQuotaCell(OfferObject offerObject, QuotasLiveObject quotasLiveObject)
        {
            LoggingUtility log = LoggerFactory.GetLogger();
            IQuotaExpressionRepository quotaExpressionRepository = new QuotaExpressionRepository();
            IQuotaMappingRepository quotaMappingRepository = new QuotaMappingRepository();
            ISampleMappingRepository sampleMappingRepository = new SampleMappingRepository();

            try
            {
                var parameters = new Dictionary<string, string>();
                var sampleId = offerObject.SampleId.Value;
                parameters.Add("SampleId", sampleId.ToString());
                // ensure quota related data in the database is purged for this sample
                quotaExpressionRepository.Delete(sampleId);
                sampleMappingRepository.Delete(sampleId);
                quotaMappingRepository.DeletebySampleId(sampleId);

                int studyId = Convert.ToInt32(offerObject.StudyId);
                log.Debug("Calling SteamService to get the attributes at the quota cell level for studyId: " + studyId + ", sample: " + sampleId);
                SteamStudyObject steamStudyObject = new SteamStudy().GetQuotasAttributes(studyId, sampleId);

                if (steamStudyObject.ExpressionsXML == null || steamStudyObject.ExpressionsXML.Contains(DocumentNotFound) || !steamStudyObject.ExpressionsXML.Contains("<data>"))
                {
                    log.Info(new ErrorObject(ErrorKey.ERR_INTERNAL_BACKEND_STEAM_UNAVAILABLE, parameters).Message);
                    return false;
                }
                // In order for the attributes names to be consistent with what is returned to suppliers on other services
                // like CodeBook and LiveOffers need to remove the prefix panelist_ from all attribute names (added by steam service)
                steamStudyObject.ExpressionsXML = steamStudyObject.ExpressionsXML.Replace("panelist_", null);

                log.Debug("Calling GMI GetSample service to get the mapping from internal to external ids for studyId: " + studyId + ", sample: " + sampleId);
                GMISampleQuotasObject gmiSampleQuotasObject = new GMIStudy().GetGMISamples(studyId, sampleId);
                if (gmiSampleQuotasObject == null || (gmiSampleQuotasObject.GMIQuotasList == null && gmiSampleQuotasObject.GMISampleQuotasList == null))
                {
                    log.Info(new ErrorObject(ErrorKey.ERR_INTERNAL_BACKEND_GET_SAMPLE_UNAVAILABLE, parameters).Message);
                    return false;
                }

                log.Debug("Calling fetchMulti service to get the Quota Remaining for studyId: " + studyId + ", sample: " + sampleId);
                new QuotaLiveMatch().UpdateQuotaRemaingValues(gmiSampleQuotasObject, quotasLiveObject);
                new SteamStudy().UpdateQuotaExpression(steamStudyObject, gmiSampleQuotasObject);

                steamStudyObject.OfferId = offerObject.Id;
                quotaExpressionRepository.Insert(steamStudyObject);

                foreach (GMIQuotaObject gmiQuotaObject in gmiSampleQuotasObject.GMIQuotasList)
                {
                    gmiQuotaObject.OfferId = offerObject.Id;
                    quotaMappingRepository.Insert(gmiQuotaObject);
                }

                foreach (GMISampleObject gmiSampleObject in gmiSampleQuotasObject.GMISampleQuotasList)
                {
                    gmiSampleObject.OfferId = offerObject.Id;
                    sampleMappingRepository.Insert(gmiSampleObject);
                }
            }
            catch (Exception e)
            {
                log.Error("An error occurred while trying to create the quota cells for offerId " + offerObject.Id.ToString(), e);
                throw;
            }
            return true;
        }
 public static bool InsertOffer(WebServiceResponse offer)
 {
     bool success = false;
     if (offer != null && offer.Data != null)
     {
         OfferObject convertedOffer = JsonConvert.DeserializeObject<OfferObject>(offer.Data);
         if (convertedOffer.Id != new Guid())
         {
             OfferObject offerToAdd = new OfferObject();
             offerToAdd.Id = convertedOffer.Id;
             offerToAdd.Description = (convertedOffer.Description != null) ? convertedOffer.Description : "Default Description";
             offerToAdd.Status = convertedOffer.Status;
             offerToAdd.IR = (convertedOffer.IR != null) ? convertedOffer.IR : 0;
             offerToAdd.LOI = (convertedOffer.LOI != null) ? convertedOffer.LOI : 0;
             offerToAdd.OfferLink = (convertedOffer.OfferLink != null) ? convertedOffer.OfferLink : "https://devhub.globaltestmarket.com/hub/tplm/welcome";
             offerToAdd.QuotaRemaining = (convertedOffer.QuotaRemaining != null) ? convertedOffer.QuotaRemaining : 0;
             offerToAdd.RespondentAttributes = new List<RespondentAttributeObject>();
             offerToAdd.SampleId = (convertedOffer.SampleId != null) ? convertedOffer.SampleId : 0;
             offerToAdd.StudyId = (convertedOffer.StudyId != null) ? convertedOffer.StudyId : 0;
             offerToAdd.StudyStartDate = (convertedOffer.StudyStartDate != null) ? convertedOffer.StudyStartDate : null;
             offerToAdd.StudyEndDate = (convertedOffer.StudyEndDate != null) ? convertedOffer.StudyEndDate : null;
             offerToAdd.Terms = new List<TermObject>();
             offerToAdd.TestOffer = (convertedOffer.TestOffer != null) ? convertedOffer.TestOffer : false;
             offerToAdd.Title = (convertedOffer.Title != null) ? convertedOffer.Title : "Default Title";
             offerToAdd.Topic = (convertedOffer.Topic != null) ? convertedOffer.Topic : "Default Topic";
             offerToAdd.RetryCount = (convertedOffer.RetryCount != null) ? convertedOffer.RetryCount : 0;
             offers.Add(offerToAdd);
             success = true;
         }
     }
     return success;
 }