private void gvItems_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e) { if (IsGroupItem) { int ItemGroupDetailID = new OfferRepository().SaveItemGroupDetail(ItemGroupID, cmbItemCode.EditValue, Utility.UserID); gvItems.SetRowCellValue(e.RowHandle, "ITEMGROUPDETAILID", ItemGroupDetailID); } else { int OfferItemID = new OfferRepository().SaveOfferItem(OfferID, cmbItemCode.EditValue, Utility.UserID); gvItems.SetRowCellValue(e.RowHandle, "OFFERITEMMAPID", OfferItemID); } int rowhandle = cmbItemCodeView.LocateByValue("ITEMCODEID", cmbItemCode.EditValue); gvItems.SetRowCellValue(e.RowHandle, "ITEMCODEID", cmbItemCode.EditValue); gvItems.SetRowCellValue(e.RowHandle, "ITEMCODE", cmbItemCode.Text); gvItems.SetRowCellValue(e.RowHandle, "ITEMNAME", cmbItemCodeView.GetRowCellValue(rowhandle, "ITEMNAME")); gvItems.SetRowCellValue(e.RowHandle, "HSNCODE", cmbItemCodeView.GetRowCellValue(rowhandle, "HSNCODE")); gvItems.SetRowCellValue(e.RowHandle, "CATEGORYID", cmbItemCodeView.GetRowCellValue(rowhandle, "CATEGORYID")); gvItems.SetRowCellValue(e.RowHandle, "SUBCATEGORYID", cmbItemCodeView.GetRowCellValue(rowhandle, "SUBCATEGORYID")); gvItems.SetRowCellValue(e.RowHandle, "CATEGORYNAME", cmbItemCodeView.GetRowCellValue(rowhandle, "CATEGORYNAME")); gvItems.SetRowCellValue(e.RowHandle, "SUBCATEGORYNAME", cmbItemCodeView.GetRowCellValue(rowhandle, "SUBCATEGORYNAME")); }
public IActionResult Get() { if (Request.Query.ContainsKey("count")) { int count; if (Int32.TryParse(Request.Query["count"], out count)) { if (Request.Query.ContainsKey("isFoundation")) { var isFound = Convert.ToBoolean(Request.Query["isFoundation"]); return(Ok(OfferRepository.GetN(count, isFound))); } else { return(BadRequest()); } } } if (Request.Query.ContainsKey("isFoundation")) { var isFound = Convert.ToBoolean(Request.Query["isFoundation"]); return(Ok(OfferRepository.GetAll(isFound))); } else { return(Ok(OfferRepository.GetAll(true))); } }
public DetailsModel(IMapper mapper, StoreRepository stores, OfferRepository offers, ProductRepository products) { _mapper = mapper; _stores = stores; _offers = offers; _products = products; }
public UnitOfWork(PolicyDbContext policyDbContext) { _policyDbContext = policyDbContext; tx = _policyDbContext.Database.BeginTransaction(); _offerRepository = new OfferRepository(policyDbContext); _policyRepository = new PolicyRepository(policyDbContext); _messageRepository = new MessageRepository(policyDbContext); }
public DetailsModel(IMapper mapper, StoreRepository stores, OfferRepository offers, ProductRepository products, AuthService authService) { _mapper = mapper; _stores = stores; _offers = offers; _products = products; _authService = authService; }
public OfferService(OfferRepository offerRepository, ICitiesService citiesService, IAlternativeService alternativeService, IMapper mapper) : base(mapper) { _offerRepository = offerRepository; _citiesService = citiesService; _alternativeService = alternativeService; _mapper = mapper; }
public List <Offer> GetListPaged(int pagenumber, int itemsperpage, string conditions, string order, int statusproject) { OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); List <Offer> lista = Offerrepo.GetListPaged <Entities.Offer, Entities.Category>(pagenumber, itemsperpage, conditions, order, statusproject).ToList().Select(e => new Offer().InjectFrom(e)).Cast <Offer>().OrderByDescending(e => e.DateOffer).ToList(); return(lista); }
public void InsertPhases(List <OfferPhases> listOfferPhases) { OfferRepository <OfferPhases> Offerrepo = new OfferRepository <OfferPhases>(); listOfferPhases.ForEach(e => e.StatusPhase = StatusPhase.EnCurso); Offerrepo.InsertPhases(listOfferPhases); }
public void AddOffer(string debtor, System.Guid offerid) { ICollection <Offers> offers; ICollection <EstimateConnects> Connect; using (var context = new DataBaseContext()) { offers = context.Offer .Include(offermodel => offermodel.Estimate) .Include(user => user.CreatedBy) .Include(user => user.UpdatedBy) .ToList(); Connect = context.EstimateConnects .Include(line => line.EstimateLines) .ToList(); } var offer = offers.FirstOrDefault(x => x.Id.Equals(offerid)); var guid = offer.Estimate.Id; var estimateid = Guid.Parse(guid.ToString()); var estimate = EstimateRepository.Find(estimateid); var lines = Connect.Where(x => x.Estimate.Id == estimate.Id).ToList(); var debtornumber = Regex.Replace(debtor, "[^0-9.]", ""); var client = new RestClient(ApiUrl); var request = new RestRequest("/apiv2/api.php", Method.POST); var InvoiceLines = new List <Dictionary <string, string> >(); foreach (var item in lines) { var line = new Dictionary <string, string> { { "Description", item.EstimateLines.Specification }, { "PriceExcl", item.EstimateLines.TotalCost.ToString() } }; InvoiceLines.Add(line); } var invoice = new Invoice { api_key = ApiKey, controller = "invoice", action = "add", Debtor = debtornumber.ToString(), Concept = 0, InvoiceLines = InvoiceLines }; request.RequestFormat = DataFormat.Json; request.AddJsonBody(invoice); var response = client.Execute <WeFactResponseModel>(request); var offerte = OfferRepository.Find(offerid); OfferRepository.SaveChanges(); EditWefactLines(response.Data.Invoice.InvoiceLines, offerid); }
public IActionResult Create([FromBody] Offer offer) { if (OfferRepository.Create(offer)) { return(Ok(offer.OfferId)); } // todo ADD XD return(BadRequest()); }
public Offer Get(int id) { OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); OfferPhasesRepository <OfferPhases> OfferPrepo = new OfferPhasesRepository <OfferPhases>(); var offer = Offerrepo.Get(id); offer.OfferPhases = new List <OfferPhases>(); offer.OfferPhases = OfferPrepo.GetPhasesByIdOffer(id).ToList(); return(offer); }
static void Main(string[] args) { IOfferRepository offerRepositiry = new OfferRepository(); ISearchRepository searchRepository = new SearchRepository(); List <string> topWordsList = GetTopWordsList(); //CountForSingleWord(topWordsList, searchRepository); //CountForPairWords(topWordsList, searchRepository); CompareOffer(topWordsList, offerRepositiry); }
public void TestTotal() { IOfferRepository r1 = new OfferRepository(); IProductRepository r2 = new ProductRepository(); IPurchaseRepository r3 = new PurchaseRepository(); IFruitShopService f = new FruitShopService(r1, r2, r3); IFruitShopAppService fApp = new FruitShopAppService(f); Receipt r = fApp.RunFruitShop(); Assert.Equal(26.15M, Convert.ToDecimal(r.Total)); }
public void EditInvoice(Guid offerid) { var client = new RestClient(ApiUrl); var request = new RestRequest("/apiv2/api.php", Method.POST); var offer = OfferRepository.Find(offerid); request.AddParameter("api_key", ApiKey); request.AddParameter("action", "edit"); request.AddParameter("controller", "invoice"); request.AddParameter("Identifier", offer.DocumentCode); }
private void gvBranch_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e) { int OfferBranchID = new OfferRepository().SaveOfferBranch(OfferID, cmBranch.EditValue, Utility.UserID); gvBranch.SetRowCellValue(e.RowHandle, "OFFERBRANCHID", OfferBranchID); int rowhandle = cmbBranchView.LocateByValue("BRANCHID", cmBranch.EditValue); gvBranch.SetRowCellValue(e.RowHandle, "BRANCHID", cmBranch.EditValue); gvBranch.SetRowCellValue(e.RowHandle, "BRANCHNAME", cmBranch.Text); gvBranch.SetRowCellValue(e.RowHandle, "BRANCHCODE", cmbBranchView.GetRowCellValue(rowhandle, "BRANCHCODE")); gvBranch.SetRowCellValue(e.RowHandle, "PHONENO", cmbBranchView.GetRowCellValue(rowhandle, "PHONENO")); }
public UoW(IWinstonEntities entity) { _entity = entity as WinstonEntities; Users = new UserRepository(entity); Offers = new OfferRepository(entity); Vouchers = new VoucherRepository(entity); UserVouchers = new UserVoucherRepository(entity); KeyAccounts = new KeyAccountRepository(entity); VoucherTransactions = new VoucherTransactionRepository(entity); UserSegments = new UserSegmentRepository(entity); }
public UnitOfWork(HotelContext context) { this.context = context ?? throw new System.ArgumentNullException(nameof(context)); Users = new UserRepository(context); BookingOffers = new BookingOfferRepository(context); Offers = new OfferRepository(context); BookingRoomServices = new BookingRoomServiceRepository(context); BookingRooms = new BookingRoomRepository(context); Services = new ServiceRepository(context); RoomFeatures = new RoomFeatureRepository(context); Features = new FeatureRepository(context); RoomImages = new RoomImageRepository(context); Rooms = new RoomRepository(context); }
public IActionResult Create() { var query = Request.Query["query"]; var isFound = Convert.ToBoolean(Request.Query["isFoundation"]); if (String.IsNullOrWhiteSpace(query)) { return(Ok(OfferRepository.GetAll(isFound))); } else { return(Ok(OfferRepository.GetByQueryInProds(query, isFound))); } }
public void UpdatePhases(List <OfferPhases> listOfferPhases, int IdOffer) { OfferRepository <OfferPhases> Offerrepo = new OfferRepository <OfferPhases>(); Offerrepo.UpdatePhases(listOfferPhases, IdOffer); Log4NetLogger logger2 = new Log4NetLogger(); SUser suser = new SUser(); foreach (var oferfases in listOfferPhases) { var user = suser.GetUserById(new Guid(oferfases.Offer.IdUser)); logger2.Info("Actualización Fases Oferta:" + IdOffer + "," + "UsuarioOrigen:" + user.UserName + ",Fase:" + oferfases.Name); } }
public int?Delete(int id) { OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); OfferRepository <OfferPhases> OfferrepoP = new OfferRepository <OfferPhases>(); int rta2 = OfferrepoP.DeletePhases(id); int?rta = Offerrepo.Delete(id); if (rta == null) { return(null); } else { return(rta); } }
public bool InitializeQuotaCells(Guid offerId) { bool result = false; LoggingUtility log = LoggerFactory.GetLogger(); try { OfferObject offerObject = new OfferRepository().SelectByID(offerId); var parameters = new Dictionary<string, string>(); var studyId = offerObject.StudyId.Value; var sampleId = offerObject.SampleId.Value; parameters.Add("StudyId", studyId.ToString()); parameters.Add("SampleId", sampleId.ToString()); if (offerObject != null) { SteamStudyObject steamStudyObject = new QuotaExpressionRepository().SelectByID(offerObject.SampleId.Value); QuotasLiveObject quotasLiveObject = new QuotaLiveMatch().GetQuotaRemainingValues(offerObject.StudyId.Value); if (quotasLiveObject == null || (quotasLiveObject.QuotasLiveList[0].InternalQuotaId == 0 && quotasLiveObject.QuotasLiveList[0].InternalSampleId == 0)) { log.Info(new ErrorObject(ErrorKey.ERR_INTERNAL_BACKEND_FETCH_MULTI_UNAVAILABLE, parameters).Message); result = false; } else if (steamStudyObject == null || steamStudyObject.ExpressionsXML == null) { // The offer is not initialized, we need to call services to store quota level attribute, mappings, and quota remaining log.Debug("Calling SteamService to store the quota level attribute, mappings, and quota remaining for sample: " + offerObject.SampleId.Value); result = CreateQuotaCell(offerObject, quotasLiveObject); } else { // The offer is initialized, we need to update the quota remaining if it has changed log.Debug("Check for quota remaining updates for sample: " + offerObject.SampleId.Value); result = UpdateQuotaCell(offerObject, steamStudyObject, quotasLiveObject); } } } catch { log.Error("An error occurred while trying to initialize the QuotaCells for offerId: " + offerId.ToString()); throw; } return result; }
public OfferController(IRepository <Offers> offerrepository, IRepository <Users> userrepository, IRepository <Offers> offerrepoitory, IRepository <Estimates> estimaterepository, IRepository <EstimateLines> estimatlinesrepository, IRepository <EstimateConnects> estimateconnectsrepository, IRepository <Settings> settingsrepository, IConnector wefactConnector, IHostingEnvironment env, ITemplateService templateservice, IConverter converterService) { OfferRepository = (OfferRepository)offerrepository; UserRepository = (UsersRepository)userrepository; EstimateRepository = (EstimateRepository)estimaterepository; EstimateLinesRepository = (EstimateLinesRepository)estimatlinesrepository; EstimateConnectsRepository = (EstimateConnectsRepository)estimateconnectsrepository; SettingsRepository = (SettingsRepository)settingsrepository; Wefactconnector = (WeFactConnector)wefactConnector; TemplateService = templateservice; Environment = env; ConverterService = converterService; }
public Offer Update(Offer Offer) { OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); Offer.DateOffer = DateTime.Now; int? rta = Offerrepo.Update(Offer); Log4NetLogger logger2 = new Log4NetLogger(); SUser suser = new SUser(); var user = suser.GetUserById(new Guid(Offer.IdUser)); SCategory scate = new SCategory(); var cate = scate.FindCategoryById(Offer.CategoryId); logger2.Info("Actualización Oferta:" + Offer.TitleOffer + "," + "UsuarioOrigen:" + user.UserName + ",Categoria:" + cate.Name); if (rta == null) { return(null); } else { return(Offer); } }
public OfferDataStore() { items = new List <Item>(); var current = Connectivity.NetworkAccess; if (current == NetworkAccess.Internet) { _offerRepository = new OfferRepository(); var offers = _offerRepository.GetOffers(1); foreach (var offer in offers) { items.Add(new Item { Id = offer.Id.ToString(), Text = offer.Name, Description = offer.Description, Color = offer.ColorCode, IsActive = false }); } } }
public Offer Insert(Offer Offer) { OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); SCategory scate = new SCategory(); var cate = scate.FindCategoryById(Offer.CategoryId); Offer.DateOffer = DateTime.Now; int?rta = Offerrepo.Insert(Offer); if (rta == null) { return(null); } else { Offer.Id = (int)rta; Log4NetLogger logger2 = new Log4NetLogger(); SUser suser = new SUser(); var user = suser.GetUserById(new Guid(Offer.IdUser)); logger2.Info("Creación Oferta:" + Offer.TitleOffer + "," + "Por:" + user.UserName + ",Categoria:" + cate.Name); return(Offer); } }
private static bool SendMailToRequestor(Order order) { Offer offer = OfferRepository.Get(order.OfferId); MailMessage mail = new MailMessage(AppAddress, new MailAddress(order.RequestorEmail)); mail.Subject = "Your order was submitted!"; StringBuilder body = new StringBuilder(); body.Append(string.Format("Hi {0}!\r\n", order.RequestorName)); body.Append("\r\n"); body.Append("You order was submitted.\r\n"); body.Append(string.Format("You can contact {0} by {1}. \r\n", offer.OwnerName, offer.OwnerEmail)); body.Append(string.Format("You declared to meet him {0}.\r\n", order.ReceiveTime)); body.Append("Please be on time to pick up:\r\n"); foreach (var p in offer.Products) { if (order.ProductIds.Contains(p.ProductId)) { body.Append(string.Format("* {0},\r\n", p.Name)); } } body.Append("\r\n"); body.Append("Have a great day!\r\n FoodSharingNetwork"); mail.Body = body.ToString(); try { smtpClient.Send(mail); return(true); } catch (Exception) { return(false); } }
private static bool SendMailToCreator(Order order) { Offer offer = OfferRepository.Get(order.OfferId); MailMessage mail = new MailMessage(AppAddress, new MailAddress(offer.OwnerEmail)); mail.Subject = "Your offer was accepted!"; StringBuilder body = new StringBuilder(); body.Append(string.Format("Hi {0}!\r\n", offer.OwnerName)); body.Append("\r\n"); body.Append(string.Format("Your offer \"{0}\" was accepted by {1}.\r\n", offer.OfferDescription, order.RequestorName)); body.Append(string.Format("You can contact him by {0}. \r\n", order.RequestorEmail)); body.Append(string.Format("He will meet with you {0}.\r\n", order.ReceiveTime)); body.Append("Please prepare following products for him to pick up:\r\n"); foreach (var p in offer.Products) { if (order.ProductIds.Contains(p.ProductId)) { body.Append(string.Format("* {0},\r\n", p.Name)); } } body.Append("\r\n"); body.Append("Have a great day!\r\n FoodSharingNetwork"); mail.Body = body.ToString(); try { smtpClient.Send(mail); return(true); } catch (Exception) { return(false); } }
public int?ChangeStatusPhases(ICollection <OfferPhases> offerPhases, Persistence.Entities.StatusPhase status, Persistence.Entities.Offer offer) { int?rta = null; OfferUserRepository <OfferUser> OfferUrepo = new OfferUserRepository <OfferUser>(); OfferRepository <Offer> Offerrepo = new OfferRepository <Offer>(); //if (status == StatusPhase.Aplicada) //if (!OfferUrepo.HaveOfferUsers(offerPhases.FirstOrDefault().IdOffer) && status==StatusPhase.Aplicada ) //{ OfferPhasesRepository <OfferPhases> OfferPrepo = new OfferPhasesRepository <OfferPhases>(); offer.Status = Offer.StatusOffer.Eliminada; Offerrepo.Update(offer); foreach (var offerphase in offerPhases) { offerphase.StatusPhase = status; rta = OfferPrepo.Update(offerphase); if (status == StatusPhase.Finalizada) { Business.Log4NetLogger logger2 = new Business.Log4NetLogger(); logger2.Info("Proyecto finalizado:" + offerphase.IdOffer); } else if (status == StatusPhase.Eliminada) { Business.Log4NetLogger logger2 = new Business.Log4NetLogger(); logger2.Info("Proyecto eliminado:" + offerphase.IdOffer); } if (rta == null) { break; } } //} return(rta); }
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); }
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); }
static void Main(string[] args) { IOfferRepository offerRepositiry = new OfferRepository(); ISearchRepository searchRepository = new SearchRepository(); List<string> topWordsList = GetTopWordsList(); //CountForSingleWord(topWordsList, searchRepository); //CountForPairWords(topWordsList, searchRepository); CompareOffer(topWordsList, offerRepositiry); }
public int Activate(int sampleId, Guid offerId, out int suspendedCode) { LoggingUtility log = LoggerFactory.GetLogger(); OfferRepository offerRep = new OfferRepository(); var newStatus = (int)OfferStatus.Active; suspendedCode = 0; try { OpenSampleObject sample = GetOpenSampleObject(sampleId); //If the sample was mainstream enabled if (sample != null) { // update offer attributes in local database based on attributes from SAM new RespondentAttributeRepository().UpdateOrRemove(offerId, sample.Attributes); // update sample quota remaining in local database from SAM offerRep.UpdateQuotaRemaining(sampleId, sample.MainstreamQuotaRemaining); // collect quota cell attributes, and quota cell quota remaining and store in database var QuotaCellRequestSuccess = new QuotaCellManager().InitializeQuotaCells(offerId); // Set the offer as pending if it failed in getting the quota cells if (!QuotaCellRequestSuccess) { //newStatus = (int)OfferStatus.Suspended; suspendedCode = 22; newStatus = (int)OfferStatus.Suspended; log.Info("Suspending the sample " + sample.SampleId + " as the QuotaCell could not be initialized."); } } //If the sample was not mainstream enabled else { var ErrorList = this.openSampleAttribute.ServiceErrorList.ToList(); //If SAM returned error message in it's response if (ErrorList.Count > 0) { // If error code is for a TimeOut or an unexpected sql error (SAM side) // => Make the offer as pending if (ErrorList.Exists(i => Convert.ToInt32(i.code) == TimeoutErrorCode) || ErrorList.Exists(i => Convert.ToInt32(i.code) == UnexpectedSqlErrorCode)) { newStatus = (int)OfferStatus.Pending; log.Info("Making the sample " + sampleId + " as pending as SAM returned an error."); } // If error code is for Sample not mainstream enabled // => Make the offer as suspended else if (ErrorList.Exists(i => Convert.ToInt32(i.code) == SampleNotMainstreamEnabledErrorCode)) { //newStatus = (int)OfferStatus.Suspended; suspendedCode = 21; newStatus = (int)OfferStatus.Suspended; log.Info("Suspending the sample " + sampleId + " as it was not found as mainstream enabled."); } } // SAM response doesn't contain an error message, SampleId not found in response // => Suspend the offer else { //newStatus = (int)OfferStatus.Suspended; suspendedCode = 21; newStatus = (int)OfferStatus.Suspended; log.Info("Suspending the sample " + sampleId + " as it was not found as mainstream enabled."); } } } catch (Exception e) { if (e is ThreadAbortException) newStatus = (int)OfferStatus.Inactive; else newStatus = (int)OfferStatus.Pending; log.Error(@"A problem occurred while trying to activate the offer: " + offerId.ToString() + " Sample Id: " + sampleId + ".", e); } finally { offerRep.UpdateOfferStatus(sampleId, newStatus); } return newStatus; }
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); }
public HomeController(IRepository <Users> userrepository, IRepository <Offers> offerrepository) { UsersRepository = (UsersRepository)userrepository; OfferRepository = (OfferRepository)offerrepository; }
// GET RpcService ///<summary> ///Returns the term status given offerID and termId ///</summary> ///<param name="OfferId">Unique ID for the Offer</param> ///<param name="TermsId">Unique ID for the term</param> ///<returns> ///Status: Term status| ///Error: In case of invalid Offer ID or Term ID or Term ID expiration date latest then 30 minutes| ///LivematchAttributeUsage: List of the attributes names for the passed OfferId | ///Offer data: OfferId, OfferType, StudyId, SampleId| ///</returns> public IHttpActionResult GetOfferAttributeUsage(string OfferId, string TermsId) { LoggingUtility log = LoggerFactory.GetLogger(); RpcOfferResponse _responseEnvelope = new RpcOfferResponse(Request.Properties["requestId"].ToString(), true); var oid = new Guid(); var tid = new Guid(); parameters.Add("OfferId", OfferId); parameters.Add("TermId", TermsId); log.ProcessingDebug(_responseEnvelope.Meta.Id, "Received GET OfferAttributeUsage request."); try { //Test if one of the required parameters is not supplied in the URL if (OfferId == null || TermsId == null) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_MISSING_DATA_ARGUMENTS, parameters)); } //Test if given offer id is of type GUID else if (Guid.TryParse(OfferId, out oid) == false) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_INVALID_OFFER_ARGUMENT, parameters)); } //Test if given term id is of type GUID else if (Guid.TryParse(TermsId, out tid) == false) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_INVALID_TERM_ARGUMENT, parameters)); } else { log.ProcessingDebug(_responseEnvelope.Meta.Id, "Getting requested offer and term from the database."); var ms = new OfferRepository().SelectByID(oid); //There is no offer with this id, add an error if (ms == null) _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_INVALID_OFFER_ARGUMENT, parameters)); //Offer is inactive or suspended else if (ms.Status != (int)OfferStatus.Active) _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_OFFER_SUSPENDED_INACTIVE, parameters)); //Check if the provided term exists for the given offer else if (new TermRepository().CheckTermForOffer(tid, oid) == false) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_INVALID_TERM_ARGUMENT, parameters)); } else { //Check term if still valid log.ProcessingDebug(_responseEnvelope.Meta.Id, "Checking if requested term has expired."); if (new TermRepository().CheckTermValidity(tid) == null) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_HUB_TERM_EXPIRED, parameters)); } //Add offer data to response else { log.ProcessingDebug(_responseEnvelope.Meta.Id, "Getting requested offer attributes from the database."); //_responseEnvelope.Data.Add(new RpcApiObject(new OfferAttributeRepository().GetRpcOfferAttributes(oid).ToList(), new RpcOfferApiDetails(ms.Id, ms.SampleId, ms.StudyId))); _responseEnvelope.Data.LivematchAttributeUsage = new OfferAttributeRepository().GetRpcOfferAttributes(oid).ToList(); _responseEnvelope.Data.Offer = new RpcOfferDetailsApiObject(ms.Id, ms.StudyId, ms.SampleId); } } } } catch (Exception e) { _responseEnvelope.Data.Errors.Add(new ErrorObject(ErrorKey.ERR_INTERNAL_FATAL)); log.InfoJson(new Methods().Exception_ToLogObject(_responseEnvelope.Meta.Id, RequestContext.Principal.Identity.Name, operationType.WS.ToString(), operationName.GetAllLiveOffers.ToString(), e)); } finally { //If the response has errors, insert an error message into the logs if (_responseEnvelope.Data.Errors.Count != 0) { log.InfoJson(new Methods().Error_ToLogObject(_responseEnvelope.Meta.Id, RequestContext.Principal.Identity.Name, OperationType, OperationName, parameters, _responseEnvelope.Data.Errors)); log.ProcessingDebug(_responseEnvelope.Meta.Id, "GET OfferAttributeUsage request was unsuccessful."); _responseEnvelope.Status = false; } //The response has no errors, we insert a request successful message into the logs else { _responseEnvelope.Data.Errors = null; log.InfoJson(new Methods().Response_ToLogObject(_responseEnvelope.Meta.Id, RequestContext.Principal.Identity.Name, OperationType, OperationName, parameters, _responseEnvelope.Data)); log.ProcessingDebug(_responseEnvelope.Meta.Id, "GET OfferAttributeUsage request was successful."); } } return Ok(_responseEnvelope); }
public ActionResult GetStudySamples(int studyId) { var mainstreamStudySampleResponse = new MainstreamStudySampleResponseModel(); MainstreamStudySampleResponseObject samples = null; Thread searchStudyThread = new Thread(() => { try { samples = new Sam().ProcessGetMainstreamStudySample(studyId); } catch (Exception e) { LoggerFactory.GetLogger().Error(string.Format(msgUtil.GetMessage(MessageKey.LOG_SEARCHSTUDY_EXCEPTION), studyId), e); } }); try { searchStudyThread.Start(); if (searchStudyThread.Join(10000)) { OfferRepository offerRep = new OfferRepository(); List<SampleModel> sampleList = new List<SampleModel>(); foreach (var sample in samples.MainstreamStudySamples) { SampleModel newSample = new SampleModel(); newSample.StudySample = sample; if (offerRep.SelectOfferBySampleId(sample.SampleId) != null) { newSample.Exists = true; } sampleList.Add(newSample); } mainstreamStudySampleResponse.SampleList = sampleList; mainstreamStudySampleResponse.Errors = samples.Errors; } else { List<ServiceErrorObject> errorList = new List<ServiceErrorObject>(); ServiceErrorObject error = new ServiceErrorObject(); error.message = string.Format(msgUtil.GetMessage(MessageKey.ERR_SEARCHSTUDY_TIMEOUT), studyId); errorList.Add(error); mainstreamStudySampleResponse.Errors = errorList; } } catch { List<ServiceErrorObject> errorList = new List<ServiceErrorObject>(); ServiceErrorObject error = new ServiceErrorObject(); error.message = msgUtil.GetMessage(MessageKey.ERR_SEARCHSTUDY_EXCEPTION); errorList.Add(error); mainstreamStudySampleResponse.Errors = errorList; } return PartialView("_StudyResult", mainstreamStudySampleResponse); }
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); }
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); }