/// <summary>
        /// This will set the draw execution job to run on enddate of the event only if manual advance is set to false.
        /// </summary>
        /// <param name="randomEventId"></param>
        public async virtual Task <bool> UpdateDrawExecutionJobByEndDate(int randomEventId)
        {
            var isSuccess = false;

            var randomEvent = await _context.Events.FindAsync(randomEventId);

            var state = new RandomEventState();

            if (randomEvent.EventState != null)
            {
                state = randomEvent.EventState.ToObject <RandomEventState>();
            }

            if (!string.IsNullOrEmpty(state.HangfireJobId)) // remove existing job
            {
                BackgroundJob.Delete(state.HangfireJobId);
            }

            // set a job to run the draw at the enddate.
            var jobId = BackgroundJob.Schedule(() => ExecuteDraw(randomEventId), DateTimeOffset.Parse(randomEvent.EndDate.ToString("yyyy-MM-ddTHH:mm:ss")));

            state.HangfireJobId = jobId;
            state.IsDrawn       = false;

            randomEvent.EventState = JObject.FromObject(state);

            await _context.SaveChangesAsync();

            if (!string.IsNullOrEmpty(jobId))
            {
                isSuccess = true;
            }

            return(isSuccess);
        }
Exemple #2
0
        /// <summary>
        /// Deletes the specified task, by the task GUID, not the Hangfire taskID
        /// </summary>
        /// <param name="id"></param>
        /// <returns>True if task exists and is deleted, False if the task does not exist</returns>
        public async System.Threading.Tasks.Task <bool> Delete(string id)
        {
            var task = await _context.Tasks.Where(t => t.id == id).FirstOrDefaultAsync();

            if (task != null)
            {
                try
                {
                    if (task.taskID != null)
                    {
                        BackgroundJob.Delete(task.taskID);
                    }
                }
                catch (InvalidOperationException)
                {
                    Log.Information("No Hangfire task found for ID: {0}", task.taskID);
                }
                task.status = "CANCELLED";
                await _context.SaveChangesAsync();

                Log.Information("Deleted Task. WorkflowID: {0}, ID: {1}, Hangfire ID: {2}", task.workflowID, task.id, task.taskID);
                return(true);
            }
            return(false);
        }
Exemple #3
0
        ///<summary>
        ///Elimina una tarea
        ///</summary>
        ///<param name="id">identificador de la tarea</param>
        public void DeleteJob(string id)
        {
            BackgroundJob.Delete(id);
            var rel = _context.JobRepository.FirstOrDefault(item => item.IdJob.Equals(id));

            if (rel == null)
            {
                var list = _context.JobRepository.Where(item => item.IdJob.Contains($"{id}_") && item.FechaEjecucion > DateTime.Now).ToList();
                if (list.Count > 1)
                {
                    foreach (var job in list)
                    {
                        if (job.IdJob.Split("_")[0].Equals(id))
                        {
                            rel = job;
                        }
                    }
                }
                else
                {
                    rel = list[0];
                }
            }
            _context.Entry(rel).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            _context.SaveChanges();
        }
Exemple #4
0
        public async Task UpdateAsync(NewsNotificationViewModel model)
        {
            var record = MapUpdate().CreateMapper().Map <NewsNotification>(model);

            if ((model.Status == NewsNotificationStatus.Approved) && (model.HangfireTaskId == null))
            {
                if (DateTime.Compare(model.PushDateUtc, DateTime.UtcNow) < 0)
                {
                    BackgroundJob.Enqueue(() => new PushNotificationWorker().SendPush(model.Id));
                }
                else
                {
                    var job = BackgroundJob.Schedule(() => new PushNotificationWorker().SendPush(model.Id), model.PushDateUtc - DateTime.UtcNow);

                    record.HangfireTaskId = job;
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(record.HangfireTaskId))
                {
                    BackgroundJob.Delete(record.HangfireTaskId);
                    record.HangfireTaskId = null;
                }
            }

            await _repo.NewsNotifications.AddOrUpdateAndSaveAsync(record);
        }
Exemple #5
0
        private void EraseQueue(string queueName)
        {
            var monitoringApi = JobStorage.Current.GetMonitoringApi();
            var queues        = monitoringApi.Queues();

            var checkableQueue = queues.FirstOrDefault(q => q.Name == queueName);

            if (checkableQueue != null)
            {
                Console.WriteLine($"\nErasing Queue {queueName} - Count: {checkableQueue.Length}");
                var originalCount = (int)checkableQueue.Length;
                var count         = originalCount;
                while (count > 0)
                {
                    int progress = (int)(20.0 * ((double)count / originalCount));
                    Console.Write($"\r[{new string('=', 20 - progress)}{new string(' ', progress)}] ");

                    var toDelete       = new List <string>();
                    var iterationCount = Math.Min(200, count);
                    count -= iterationCount;

                    monitoringApi.EnqueuedJobs(queueName, 0, iterationCount)
                    .ForEach(x => toDelete.Add(x.Key));
                    foreach (var jobId in toDelete)
                    {
                        BackgroundJob.Delete(jobId);
                    }
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Play a list of cards from a user's hand
        /// </summary>
        /// <param name="cardIDs">The card IDs the user has selected </param>
        /// <param name="gameID">The game ID in which the user wants to play the card</param>
        /// <param name="userId">The user Id</param>
        /// <param name="autoPlayed">Were these cards auto played</param>
        /// <returns>PlayCard action result containing any errors and the round the card was played.</returns>
        public Entities.ActionResponses.PlayCard Execute(List <Int32> cardIDs, Int32 gameID, Int32 userId, Boolean autoPlayed = false)
        {
            Entities.ActionResponses.PlayCard response = _playCard.Execute(cardIDs, gameID, userId, autoPlayed);

            if (response.ResponseCode == Entities.ActionResponses.Enums.PlayCardResponseCode.Success)
            {
                Entities.Filters.Game.Select filter = new Entities.Filters.Game.Select();
                filter.DataToSelect = Entities.Enums.Game.Select.GamePlayerCards;
                filter.GameID       = gameID;

                Entities.Game game = _selectGame.Execute(filter);

                game.Rounds.Add(response.CurrentRound);

                if (response.CurrentRound.AllPlayersAnswered() && game.SecondsToPlay > 0)
                {
                    var cachedJobId = MemoryCache.Default.Get(game.RoundTimerKey);

                    BackgroundJob.Delete(cachedJobId as String);
                }

                _sendMessage.CardPlayed(game, true);
                _updateGame.Execute(game.GameID, DateTime.UtcNow, null);
            }

            return(response);
        }
Exemple #7
0
        public ActionResult ConfirmOrder(int?id)
        {
            if (id != null)
            {
                bool result = _orderService.ConfirmOrder(id.Value, User.Identity.GetUserId());
                var  order  = _orderService.GetOrder(id.Value, i => i.CurrentStatus, i => i.Seller.ApplicationUser, i => i.Buyer.ApplicationUser);
                if (result && order != null)
                {
                    if (order.JobId != null)
                    {
                        BackgroundJob.Delete(order.JobId);
                        order.JobId = null;
                    }

                    _orderService.SaveOrder();

                    order.JobId = MarketHangfire.SetLeaveFeedbackJob(order.SellerId, order.BuyerId, order.Id, TimeSpan.FromDays(15));


                    MarketHangfire.SetSendEmailChangeStatus(order.Id, order.Seller.ApplicationUser.Email, order.CurrentStatus.DuringName, Url.Action("SellDetails", "Order", new { id = order.Id }, protocol: Request.Url.Scheme));

                    MarketHangfire.SetSendEmailChangeStatus(order.Id, order.Buyer.ApplicationUser.Email, order.CurrentStatus.DuringName, Url.Action("BuyDetails", "Order", new { id = order.Id }, protocol: Request.Url.Scheme));

                    _orderService.SaveOrder();


                    TempData["orderBuyStatus"] = "Спасибо за подтверждение сделки! Сделка успешно закрыта.";
                    return(RedirectToAction("BuyDetails", "Order", new { id }));
                }
            }
            return(HttpNotFound());
        }
 public void Unschedule(string jobId)
 {
     if (jobId != null)
     {
         BackgroundJob.Delete(jobId);
     }
 }
Exemple #9
0
        /// <summary>
        /// Removes the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        public void Remove(long id)
        {
            using (var ctx = new DeepQStockContext())
            {
                string jobId = null;
                ActiveAgents.TryRemove(id, out jobId);

                var agent = ctx.DeepRLAgentParameters.Single(a => a.Id == id);

                // Here we have two posible situations, one is if the agent is running, in this case we cannot remove the agent immediately,
                // we need mark the agent as removed and stop the agent's job. The remove process will be handle in the shutdown process.
                // And the other situation is when the agent is not running, in that case, we can remove immediately.
                if (agent.Status == AgentStatus.Running)
                {
                    agent.Status = AgentStatus.Removed;

                    if (!string.IsNullOrEmpty(jobId))
                    {
                        BackgroundJob.Delete(jobId);
                    }
                }
                else
                {
                    ctx.RemoveAgent(agent);
                }

                ctx.SaveChanges();
            }
        }
Exemple #10
0
        /// <summary>
        /// Forces to stop all analyses that have been started more than 8 days prior to the current date, but haven't ended yet.
        /// </summary>
        /// <param name="numberOfDays">The number of days for which an analysis is allowed to run.</param>
        /// <param name="numberOfDaysLeft">The number of days for which an analysis is allowed to stop.</param>
        /// <returns></returns>
        private async Task ForceStopAnalyses(int numberOfDays = 7, int numberOfDaysLeft = 1)
        {
            // Get the limit date.
            var limitDate = DateTime.Today - TimeSpan.FromDays(numberOfDays + numberOfDaysLeft);
            // Get the analyses.
            var analyses = _context.Analyses
                           .Where(item => item.Status == AnalysisStatus.Initializing || item.Status == AnalysisStatus.Ongoing || item.Status == AnalysisStatus.Stopping)
                           .Where(item => item.DateTimeStarted < limitDate);

            // Mark all of the items for updating.
            _context.Analyses.UpdateRange(analyses);
            // Go over each of the analyses.
            foreach (var analysis in analyses)
            {
                // Update the log.
                analysis.Log = analysis.AppendToLog($"The analysis could not be gracefully stopped within the alotted time of {numberOfDaysLeft} days, so it will now be forcefully stopped.");
                // Update the status.
                analysis.Status = AnalysisStatus.Error;
                // Update the analysis end time.
                analysis.DateTimeEnded = DateTime.Now;
                // Stop and delete the Hangfire background job.
                BackgroundJob.Delete(analysis.JobId);
            }
            // Save the changes to the database.
            await _context.SaveChangesAsync();
        }
        public async Task <DiscountJobDTO> BeginEditDiscountJobAsync(int discountId)
        {
            var job = JobStorage.Current.GetMonitoringApi().ScheduledJobs(0, int.MaxValue)
                      .FirstOrDefault(j => j.Value.Job.Args.Contains(discountId));

            var discountEditTime = await _configRepository.GetDiscountEditTimeAsync((int)ConfigIdentifiers.DiscountEditTimeInMinutes);

            await _discountRepository.UpdateDiscountActivityStatusAsync(discountId, false);

            if (job.Key is null)
            {
                BackgroundJob.Schedule(() => _discountRepository.UpdateDiscountActivityStatusAsync(discountId, true), TimeSpan.FromMinutes(discountEditTime));

                return(new DiscountJobDTO()
                {
                    Message = _stringLocalizer["A session for editing discount has been created."],
                    IsEditedDisount = false,
                    EditTime = discountEditTime,
                });
            }

            BackgroundJob.Delete(job.Key);

            BackgroundJob.Schedule(() => _discountRepository.UpdateDiscountActivityStatusAsync(discountId, true), TimeSpan.FromMinutes(discountEditTime));

            return(new DiscountJobDTO()
            {
                Message = _stringLocalizer["A session for editing discount already exists."],
                IsEditedDisount = true,
                EditTime = discountEditTime,
            });
        }
Exemple #12
0
        public void DeleteJob(string jobId)
        {
            if (!string.IsNullOrEmpty(jobId))
            {
                try
                {
                    RecurringJob.RemoveIfExists(jobId);
                    Console.WriteLine("RecurringJob=>{0} deleted", jobId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }

                try
                {
                    BackgroundJob.Delete(jobId);
                    Console.WriteLine("BackgroundJob=>{0} deleted", jobId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }
            }
        }
Exemple #13
0
        public static async Task Excute(HttpJobItem item, string jobName = null, PerformContext context = null)
        {
            var mon            = JobStorage.Current.GetMonitoringApi();
            var processingJobs = mon.ProcessingJobs(0, int.MaxValue)
                                 .Where(o => o.Value.Job.Args[1].ToString() == jobName).ToList();

            //如果任务没执行完,删除新的任务
            if (processingJobs.Count() >= 2)
            {
                var removeId = processingJobs.Max(s => s.Key);
                RecurringJob.RemoveIfExists(removeId);
                BackgroundJob.Delete(removeId);
                return;
            }

            try
            {
                context.WriteLine(jobName);
                context.WriteLine(JsonConvert.SerializeObject(item));
                var client       = GetHttpClient(item);
                var httpMesage   = PrepareHttpRequestMessage(item);
                var httpResponse = await client.SendAsync(httpMesage);

                HttpContent content = httpResponse.Content;
                string      result  = await content.ReadAsStringAsync();

                context.WriteLine(result);
            }
            catch (Exception ex)
            {
                Logger.ErrorException("HttpJob.Excute", ex);
                context.WriteLine(ex.Message);
            }
        }
Exemple #14
0
        private async Task Edit(long chatId, int userNumberJob, string newSchedule)
        {
            var           api           = JobStorage.Current.GetMonitoringApi();
            long          c             = JobStorage.Current.GetMonitoringApi().ScheduledCount();
            var           scheduledJobs = api.ScheduledJobs(0, (int)c);
            List <string> neededJob     = new List <string>();
            int           id            = 1;

            foreach (var job in scheduledJobs)
            {
                var jobThis = job.Value;
                var index   = (string)jobThis.Job.Arguments.GetValue(0);
                if (index.Contains(chatId.ToString()))
                {
                    neededJob.Add(job.Key);
                    id++;
                }
            }

            if (neededJob.Count >= userNumberJob)
            {
                var editMesage = _message;
                editMesage.Text = newSchedule;
                BackgroundJob.Delete(neededJob[userNumberJob - 1]);
                await new CreateSchedule(_botClient, _db).SamplingTime(editMesage, _keyBoardExit);
            }
            else
            {
                await _botClient.SendTextMessageAsync(chatId, "\U00002757 Извините, такой позиции нету в вашем листе.\U00002757");
            }
        }
        // cas ou le sort final est la destruction selon la date de derniere modification
        public void ConservationSelonModification(Fichier f)
        {
            f.dateSuppression  = DateTime.Now.AddDays(f.type.duree);
            f.dateModification = DateTime.Now;
            int joursRest = f.type.duree;
            int jousRestPourNorification = joursRest - NotifComm;

            //on doit d'abord supprimer l'action de la modification avant celle ci si elle existe:
            if (f.HangFireID != "" && f.HangFireNotificationID != "" &&
                f.HangFireRecJobNotID != "" && f.HangFireRecJobNotID != null && f.HangFireID != null && f.HangFireNotificationID != null)
            {
                BackgroundJob.Delete(f.HangFireNotificationID);
                BackgroundJob.Delete(f.HangFireID);
                RecurringJob.RemoveIfExists(f.HangFireRecJobNotID);
            }
            if (f.HangFireID != "" && f.HangFireNotificationID != "" && f.HangFireID != null && f.HangFireNotificationID != null)
            {
                BackgroundJob.Delete(f.HangFireNotificationID);
                BackgroundJob.Delete(f.HangFireID);
            }
            f.HangFireRecJobNotID = "";
            var JobNotId = BackgroundJob.Schedule(
                () => actionsNotification.RefaireNotifChaqueJour(f),
                TimeSpan.FromDays(jousRestPourNorification));

            var jobID = BackgroundJob.Schedule(
                () => actionsFichier.commencerLesortFinal(f),
                TimeSpan.FromDays(joursRest));

            f.HangFireID             = jobID;
            f.HangFireNotificationID = JobNotId;
            actionsFichier.modifier(f);
        }
Exemple #16
0
        public void stopUnit(string unit)
        {
            string item = ListAgvJob.FirstOrDefault(d => d.Contains(unit));

            if (unit == "RX07" && StaticData.RX07BackGroudJobState)
            {
                StaticData.RX07BackGroudJobState = false;
                string id = item.Contains("_") ? item.Split('_')[1] : item;
                BackgroundJob.Delete(id);
                Clients.All.getRX07BackJobState(StaticData.RX07BackGroudJobState);
                return;
            }
            if (unit == "RX08" && StaticData.RX08BackGroudJobState)
            {
                StaticData.RX08BackGroudJobState = false;
                string id = item.Contains("_") ? item.Split('_')[1] : item;
                BackgroundJob.Delete(id);
                Clients.All.getRX08BackJobState(StaticData.RX08BackGroudJobState);
                return;
            }
            if (unit == "RX09" && StaticData.RX09BackGroudJobState)
            {
                StaticData.RX09BackGroudJobState = false;
                string id = item.Contains("_") ? item.Split('_')[1] : item;
                BackgroundJob.Delete(id);
                Clients.All.getRX09BackJobState(StaticData.RX09BackGroudJobState);
            }
        }
        public static void PurgeOrfanJobsExceptList(this IMonitoringApi monitor, List <string> exceptions)
        {
            var toDelete = new List <string>();

            foreach (QueueWithTopEnqueuedJobsDto queue in monitor.Queues())
            {
                for (var i = 0; i < Math.Ceiling(queue.Length / 1000d); i++)
                {
                    monitor.EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x =>
                    {
                        if (!exceptions.Contains(x.Key))
                        {
                            toDelete.Add(x.Key);
                        }
                        else
                        {
                            Console.WriteLine("x.Key " + x.Key + "  remains.");
                        }
                    }
                             );
                }
            }

            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }
        public async Task <IActionResult> Save([FromForm] Video data)
        {
            if (data.Id.Equals(0))
            {
                data.DateUploaded = DateTime.UtcNow;

                await _ctx.Videos.AddAsync(data);

                await _ctx.SaveChangesAsync();

                data.JobId = BackgroundJob.Enqueue(() => DoAction(data.Id, JobCancellationToken.Null));

                _ctx.Update(data);
                await _ctx.SaveChangesAsync();

                return(Ok(data));
            }

            var video = _ctx.Videos.FirstOrDefault(v => v.Id.Equals(data.Id));

            if (!video.IsDone)
            {
                BackgroundJob.Delete(video.JobId);

                video.JobId = "";
                _ctx.Update(video);
                await _ctx.SaveChangesAsync();
            }

            return(Ok(video));
        }
        public bool SaveSchedulePin(PinterestScheduledPin PinInfo)
        {
            try
            {
                if (PinInfo.Id == 0)
                {
                    var task = _scheduleTaskRepo.AddAndReturn(PinInfo);
                    _unitOfWork.Commit();
                    double secondsToAdd = (PinInfo.ScheduleDate - DateTime.UtcNow).TotalSeconds;
                    task.jobId = BackgroundJob.Schedule <IPinterestServices>(
                        x => x.PostSchedulePin(task.Id, PinInfo.SocialId),
                        TimeSpan.FromSeconds(secondsToAdd));
                }
                else
                {
                    //PinInfo.image_url = GetASchedulePin(PinInfo.Id).image_url;
                    var temp = _scheduleTaskRepo.Get().Where(x => x.Id == PinInfo.Id).FirstOrDefault();
                    BackgroundJob.Delete(temp.jobId);
                    temp.image_url    = PinInfo.image_url;
                    temp.note         = PinInfo.note;
                    temp.jobId        = PinInfo.jobId;
                    temp.ScheduleDate = PinInfo.ScheduleDate;
                    temp.link         = PinInfo.link;
                    temp.board        = PinInfo.board;
                }
                _unitOfWork.Commit();

                return(true);
            }
            catch (Exception)
            {
                BackgroundJob.Delete(PinInfo.jobId);
                return(false);
            }
        }
 public string updateEmail(MessageFromPastSelf messageFromPastSelf)
 {
     BackgroundJob.Delete(messageFromPastSelf.jobid);
     return(BackgroundJob.Schedule(
                () => sendEmail(messageFromPastSelf),
                TimeSpan.FromSeconds(messageFromPastSelf.when)));
 }
        public virtual async Task Manage(JobSettings jobSettings)
        {
            await Task.Run(() =>
            {
                var monitoringApi = JobStorage
                                    .Current
                                    .GetMonitoringApi();

                var queues = monitoringApi
                             .Queues();

                var queueCount = monitoringApi
                                 .EnqueuedCount(jobSettings.QueueIdentifier);

                if (queueCount > 1)
                {
                    var enqueuedJobIds = monitoringApi
                                         .EnqueuedJobs(jobSettings.QueueIdentifier, 0, int.MaxValue)
                                         .Select(j => j.Key);

                    foreach (var jobId in enqueuedJobIds)
                    {
                        BackgroundJob
                        .Delete(jobId);
                    }
                }
            });
        }
Exemple #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();

            app.UseHangfireDashboard();
            app.UseHangfireServer();
            using (var connection = JobStorage.Current.GetConnection())
            {
                foreach (var recurringJob in connection.GetRecurringJobs())
                {
                    RecurringJob.RemoveIfExists(recurringJob.Id);
                }
            }

            var toDelete = new List <string>();

            foreach (QueueWithTopEnqueuedJobsDto queue in JobStorage.Current.GetMonitoringApi().Queues())
            {
                for (var i = 0; i < Math.Ceiling(queue.Length / 1000d); i++)
                {
                    JobStorage.Current.GetMonitoringApi().EnqueuedJobs(queue.Name, 1000 * i, 1000)
                    .ForEach(x => toDelete.Add(x.Key));
                }
            }

            foreach (var jobId in toDelete)
            {
                BackgroundJob.Delete(jobId);
            }
        }
Exemple #23
0
        public void commencerLesortFinal(Fichier f)
        {
            Fichier f2 = getFichierById(f.idFichier);

            f = f2;

            if (f.HangFireNotificationID != null)
            {
                RecurringJob.RemoveIfExists(f.HangFireRecJobNotID);
                BackgroundJob.Delete(f.HangFireNotificationID);
                BackgroundJob.Delete(f.HangFireID);

                f.HangFireNotificationID = 0 + "";
                f.HangFireRecJobNotID    = 0 + "";
            }
            f.sortFinalComm = 1;
            fichierDAOSQLServer.modifierFichier(f);
            new ActionsNotification().supprimerNotDuFichier(f);
            Historique h = new Historique();

            h.textHistorique = "L archive " + f.Nom + " a étè conserve definitivement";
            h.IdFichier      = f.idFichier;
            h.date           = DateTime.Now;
            new ActionsHistorique().ajouterHistorique(h);
        }
        public ActionResult ConfirmAbortOrder(int?id)
        {
            if (id != null)
            {
                bool result = _orderService.ConfirmAbortOrder(id.Value, User.Identity.GetUserId());
                var  order  = _orderService.GetOrder(id.Value, i => i.Seller.ApplicationUser, i => i.Buyer.ApplicationUser, i => i.CurrentStatus);
                if (result && order != null)
                {
                    if (order.JobId != null)
                    {
                        BackgroundJob.Delete(order.JobId);
                        order.JobId = null;
                    }

                    _orderService.SaveOrder();

                    if (Request.Url != null)
                    {
                        MarketHangfire.SetSendEmailChangeStatus(order.Id, order.Seller.ApplicationUser.Email,
                                                                order.CurrentStatus.DuringName,
                                                                Url.Action("SellDetails", "Order", new { id = order.Id }, protocol: Request.Url.Scheme));

                        MarketHangfire.SetSendEmailChangeStatus(order.Id, order.Buyer.ApplicationUser.Email,
                                                                order.CurrentStatus.DuringName,
                                                                Url.Action("BuyDetails", "Order", new { id = order.Id }, protocol: Request.Url.Scheme));
                    }

                    _orderService.SaveOrder();
                    return(RedirectToAction("BuyDetails", "Order", new { id }));
                }
            }
            return(HttpNotFound());
        }
        public ActionResult CloseOrderSuccess(int?id)
        {
            string userId = User.Identity.GetUserId();

            if (userId != null && id != null)
            {
                var order = _orderService.GetOrder(id.Value, i => i.Middleman);
                if (order != null)
                {
                    if (userId == order.MiddlemanId)
                    {
                        var closeResult = _orderService.ConfirmOrderByMiddleman(order.Id, userId);
                        if (closeResult)
                        {
                            if (order.JobId != null)
                            {
                                BackgroundJob.Delete(order.JobId);
                                order.JobId = null;
                            }


                            TempData["orderBuyStatus"] = "Сделка закрыта.";
                            _orderService.SaveOrder();
                            return(RedirectToAction("MyOrderList"));
                        }
                    }
                }
            }
            return(HttpNotFound());
        }
Exemple #26
0
        public async Task <ActionResult> PostCartById(int id)
        {
            var carts = _cartService.GetAllWithNoTracking();
            var cart  = carts.SingleOrDefault(x => x.Id == id);

            if (cart == null)
            {
                return(BadRequest("კალათა ვერ მოიძებნა"));
            }

            List <ProductOrderRequest> orderProducts = new List <ProductOrderRequest>();

            foreach (var cartProduct in cart.CartProducts)
            {
                orderProducts.Add(new ProductOrderRequest {
                    ProductId = cartProduct.ProductId, Quantity = cartProduct.Quantity
                });
            }
            var order = new OrderRequest {
                UserId = cart.UserId, OrderProducts = orderProducts
            };

            if (await _orderService.InsertOrderAsync(_mapper.Map <OrderServiceModel>(order)))
            {
                BackgroundJob.Delete(cart.JobId);
                await _cartService.DeleteCart(cart.Id);

                return(Ok("შეკვეთა წარმატებით დაემატა!"));
            }

            return(BadRequest(ModelState.Where(ms => ms.Value.Errors.Count > 0)
                              .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors.Select(x => x.ErrorMessage).ToArray())));
        }
Exemple #27
0
        public async Task <string> AddFireAndForgetJobAsync(string jobName, string callAddress, string paramJson, string group, string remarks)
        {
            var job = new Job
            {
                CallAddress = callAddress,
                CreatedBy   = string.Empty,
                Name        = jobName,
                Group       = group,
                ParamJson   = paramJson,
                JobType     = JobType.FireAndForgetJob.ToString(),
                Remarks     = remarks
            };

            await _cronJobDbContext.AddAsync(job);

            try
            {
                job.HangfireJobId =
                    BackgroundJob.Enqueue <IJobWorker>(_ => _.DoWorkAsync(job.Id, callAddress, paramJson));

                await _cronJobDbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                BackgroundJob.Delete(job.HangfireJobId);
                throw ex;
            }

            return(job.Id);
        }
Exemple #28
0
        public async Task <string> AddDelayedJobAsync(string jobName, string callAddress, string paramJson, long delayMinutes, string group, string remarks)
        {
            var job = new Job
            {
                CallAddress  = callAddress,
                CreatedBy    = string.Empty,
                Name         = jobName,
                Group        = group,
                ParamJson    = paramJson,
                JobType      = JobType.DelayedJob.ToString(),
                DelayMinutes = delayMinutes,
                Remarks      = remarks
            };

            try
            {
                await _cronJobDbContext.Jobs.AddAsync(job);

                job.HangfireJobId =
                    BackgroundJob.Schedule <IJobWorker>(_ => _.DoWorkAsync(job.Id, callAddress, paramJson), TimeSpan.FromMinutes(delayMinutes));

                await _cronJobDbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                BackgroundJob.Delete(job.HangfireJobId);
                throw ex;
            }

            return(job.Id);
        }
Exemple #29
0
        public void QueueHangfire_WaitForJobToComplete_ZeroTimeout()
        {
            using (var server = new TestBackgroundJobServer(FileSystem, ServiceHost.HangfireTest))
            {
                server.Should().NotBeNull();

                const string testValue = "TestValue";

                var hangFireJob = new HangfireJob(testValue);

                var jobIdString = BackgroundJob.Enqueue <IHangFireTestService>(service =>
                                                                               service.ExecuteHangfireInfiniteJobAsync(hangFireJob));

                CancellationTokenSource cts = new CancellationTokenSource();

                jobIdString.Should().NotBeNull();
                int.TryParse(jobIdString, out var jobId).Should().BeTrue();
                jobId.Should().BeGreaterThan(0);

                cts.CancelAfter(1000);

                var monitoringApi = server.MonitoringApi;

                Func <Task <JobStatus> > fx = async() =>
                                              await JobQueueClient.WaitForJobToComplete(monitoringApi, jobIdString, 500, cts.Token);

                fx.Should().Throw <TaskCanceledException>();

                BackgroundJob.Delete(jobIdString).Should().BeTrue();
            }
        }
        ///<summary>
        ///Elimina una tarea
        ///</summary>
        ///<param name="id">identificador de la tarea</param>
        public void DeleteJob(string id)
        {
            BackgroundJob.Delete(id);
            var rel = _context.JobRepository.FirstOrDefault(item => item.IdJob.Equals(id));

            _context.Entry(rel).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
            _context.SaveChanges();
        }