private static List <EventInfoDTO> generateEvents(TimePeriodDTO timePeriod)
        {
            Random rnd         = new Random((int)DateTime.Now.ToFileTime());
            int    capacity    = rnd.Next(3, 7);
            var    eventsInfos = new List <EventInfoDTO>(capacity);

            var endTime   = timePeriod.EndTime;
            var timeDelta = (timePeriod.EndTime - timePeriod.StartTime) / (capacity + 2);

            for (int i = 0; i < capacity; i++)
            {
                eventsInfos.Add(new EventInfoDTO()
                {
                    // if it first event => should be 'Выход' if it last event => should be 'Вход' else random
                    //Direction = (((rnd.Next() % 2) == 0 || i == 0) && (i != (capacity - 1))) ? new byte?(1) : new byte?(0),
                    Direction = (rnd.Next() % 2) == 0 ? new byte?(1) : new byte?(0),
                    EventCode = 105,
                    EventTime = (endTime -= timeDelta + TimeSpan.FromMinutes(rnd.Next(59)))?.DateTime,

                    StartAreaName  = ((rnd.Next() % 2) == 0 || i == 0) ? "\u0423\u043B\u0438\u0446\u0430" : "\u041E\u0444\u0438\u0441",                    //улица/офис
                    TargetAreaName = ((rnd.Next() % 2) == 0 || i == (capacity - 1)) ? "\u0423\u043B\u0438\u0446\u0430" : "\u041E\u0444\u0438\u0441",

                    ObjectType = "\u0414\u0432\u0435\u0440\u0438 \u0441 \u0434\u0432\u043E\u0439\u043D\u044B\u043C \u0437\u0430\u043C\u043A\u043E\u043C", //Двери с двойным замком
                    ObjectName = "\u0414\u0432\u0435\u0440\u0438 #" + rnd.Next(10)                                                                        //Двери #
                });
            }

            return(eventsInfos);
        }
        private Response onWhereCoworker(WhereCoworkerDTO userQuery)
        {
            Console.WriteLine(userQuery.ToJson(true));

            var tp = new TimePeriodDTO()
            {
                StartTime = DateTimeOffset.Now.Date.Add(TimeSpan.Zero),
                EndTime   = DateTimeOffset.Now.Date.Add(new TimeSpan(23, 59, 59))
            };

            Console.WriteLine("Default: " + tp.StartTime.ToString() + " " + tp.EndTime.ToString());

            // if user hasn't entered any data and time -> set to current date and time
            if (userQuery.TimePeriod == null &&
                (!userQuery.Date.HasValue) &&
                userQuery.DateTimeObject == null &&
                (!userQuery.Time.HasValue))
            {
                userQuery.DateTimeObject = new DateTimeWraper(DateTimeOffset.UtcNow);
            }

            // recognize any possible time and data
            tp = RecognizeDate(userQuery.Date, oldTp: tp);
            tp = RecognizeTime(userQuery, oldTp: tp);
            tp = RecognizeDateTime(userQuery, oldTp: tp);

            // create params for Event Server request
            var whereHolderRequest = new HolderLocationPeriodDTO()
            {
                QueryType        = ((DateTime.UtcNow - tp.StartTime)?.TotalMinutes < 15) ? QueryType.Type.WhereNow : QueryType.Type.Where,
                HolderName       = userQuery.TargetName.Trim().Replace("?", ""),
                HolderMiddlename = userQuery.TargetMiddlename.Trim().Replace("?", ""),
                HolderSurname    = userQuery.TargetLastname.Trim().Replace("?", ""),
                TimePeriod       = ((DateTime.UtcNow - tp.StartTime)?.TotalMinutes < 15)
                                        ? new TimePeriodDTO()
                {
                    StartTime = DateTimeOffset.Now.Date.Add(TimeSpan.Zero), EndTime = DateTimeOffset.Now.Date.Add(new TimeSpan(23, 59, 59))
                }
                                        : tp
            };

            Console.WriteLine(whereHolderRequest.ToJson(true));

            foreach (var eventsListener in GlobalScope.CSEventsListeners)
            {
                eventsListener.PostCommand(new RequestHolderLocation(whereHolderRequest));
            }

            // send response to Dialogflow (Dialogflow automatically resend it to Slack, Telegram, Skype, etc.)
            //return new ResponseWebHookIntent() {
            //	FulfillmentText = $"*Буду искать:* '{whereHolderRequest.HolderName} {whereHolderRequest.HolderMiddlename} {whereHolderRequest.HolderSurname}'\n" +
            //				      $"*c :* {whereHolderRequest.TimePeriod.StartTime.ToString()}\n" +
            //					  $"*по:* {whereHolderRequest.TimePeriod.EndTime.ToString()}"
            //}.ToJson();
            return(200);
        }
Exemple #3
0
        public void AddJob(TimePeriodDTO timeperiod, IJob job)
        {
            var type = job.GetType();

            var jobdetail = scheduler.GetJobDetail(JobKey.Create(type.Name))
                            ?? JobBuilder.Create(type)
                            .WithIdentity(type.Name, "DefaultJobGroup")
                            .Build();

            var triggername = timeperiod.Label + type.Name;

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(timeperiod.Label + type.Name, type.Name + "TriggerGroup")
                          .StartAt(timeperiod.Scheduled)
                          .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever())
                          .Build();
        }
        private static TimePeriodDTO RecognizeDateTime(WhereCoworkerDTO userQuery, TimePeriodDTO oldTp)
        {
            TimePeriodDTO newTp = new TimePeriodDTO(oldTp);

            // if user input date
            if (userQuery.DateTimeObject != null && userQuery.DateTimeObject.DateTime.HasValue)
            {
                DateTimeOffset newDateTime = userQuery.DateTimeObject.DateTime.Value;                 //extract date and time

                newTp.StartTime = newDateTime.Add(TimeSpan.FromMinutes(-10));
                newTp.EndTime   = newDateTime.Add(TimeSpan.FromMinutes(+10));

                Console.WriteLine("\nNew DateTime:");
                Console.WriteLine("newDateTime: " + newDateTime.ToString());
                Console.WriteLine("DateTimePeriod: " + newTp.StartTime.ToString() + " " + newTp.EndTime.ToString());
            }

            return(newTp);
        }
        private Response onWhenCoworker(WhenCoworkerDTO userQuery)
        {
            //Console.WriteLine(userQuery.ToJson(true));

            var tp = new TimePeriodDTO()
            {
                StartTime = DateTimeOffset.UtcNow.Date.Add(TimeSpan.Zero),
                EndTime   = DateTimeOffset.UtcNow.Date.Add(new TimeSpan(23, 59, 59))
            };

            // if user hasn't entered any data and time -> set to current date and time
            if (!userQuery.Date.HasValue)
            {
                userQuery.Date = DateTimeOffset.UtcNow;
            }

            // recognize any possible time and data
            tp = RecognizeDate(date: userQuery.Date, oldTp: tp);

            // create params for Event Server request
            var holderRequest = new HolderLocationPeriodDTO()
            {
                QueryType        = QueryType.GetType(userQuery.QueryType),
                HolderName       = userQuery.TargetName.Trim().Replace("?", ""),
                HolderMiddlename = userQuery.TargetMiddlename.Trim().Replace("?", ""),
                HolderSurname    = userQuery.TargetLastname.Trim().Replace("?", ""),
                TimePeriod       = tp,
                IsHolderIn       = userQuery.InOrOut == null ? new bool?() :
                                   userQuery.InOrOut.Trim().Equals("пришла", StringComparison.OrdinalIgnoreCase) ? true : false
            };

            Console.WriteLine(holderRequest.ToJson(true));

            foreach (var eventsListener in GlobalScope.CSEventsListeners)
            {
                eventsListener.PostCommand(new RequestHolderLocation(holderRequest));
            }

            return(200);
        }
Exemple #6
0
        public override double?[] GetUnits(int startFiscalYear, int months,
                                           TimeInvariantInputDTO timeInvariantData, IReadOnlyList <TimeVariantInputDTO> timeVariantData)
        {
            var estimatedDesignLifeMeasure = timeInvariantData.Transmission_32_Station_32_Equipment_32_Risk_Transmission_32_Station_32__45__32_Design_32_Life_ConsqUnitOutput_B;

            if (estimatedDesignLifeMeasure == null)
            {
                return(null);
            }

            double estimatedDesignLife     = estimatedDesignLifeMeasure[0].Value;
            double defaultOutcomeCondition = 10.0;

            TimePeriodDTO timePeriod            = new TimePeriodDTO();
            var           endOfSpendMonthOffset = FindEndOfSpendMonth(timeInvariantData.InvestmentSpendByAccountType);

            if (!endOfSpendMonthOffset.HasValue)
            {
                return(null);
            }
            timePeriod.StartTime = GetCalendarDateTime(startFiscalYear, fiscalPeriod: 1)
                                   .AddMonths(endOfSpendMonthOffset.Value + 1); // + 1 because the benefit starts in the first month after end of spend.

            TimeVariantLocalConditionDTO localTimeInvariantData =
                new TimeVariantLocalConditionDTO(defaultOutcomeCondition, timePeriod);

            List <TimeVariantLocalConditionDTO> localTimeInvariantDataList
                = new List <TimeVariantLocalConditionDTO>();

            localTimeInvariantDataList.Add(localTimeInvariantData);

            // A generic end of life condition decay curve, generated based on the design life entered by user.
            XYCurveDTO conditionDecayCurve = HelperFunctions.GenericEndOfLifeModel.constructConditionDecayCurve(estimatedDesignLife);

            return(InterpolateCurve <TimeVariantLocalConditionDTO>(localTimeInvariantDataList,
                                                                   startFiscalYear,
                                                                   months,
                                                                   conditionDecayCurve,
                                                                   x => x.ConditionScoreLocal));
        }
        private static TimePeriodDTO RecognizeTime(WhereCoworkerDTO userQuery, TimePeriodDTO oldTp)
        {
            TimePeriodDTO newTp = new TimePeriodDTO(oldTp);

            // if time period exist
            if (userQuery.TimePeriod != null && userQuery.TimePeriod.StartTime.HasValue)
            {
                newTp.StartTime = oldTp.StartTime?.Date.Add(userQuery.TimePeriod.StartTime.Value.TimeOfDay);
                newTp.EndTime   = oldTp.EndTime?.Date.Add(userQuery.TimePeriod.EndTime.Value.TimeOfDay);
                Console.WriteLine("\nNew TimePeriod:");
                Console.WriteLine("DateTimePeriod: " + newTp.StartTime.ToString() + " " + newTp.EndTime.ToString());
            }
            else if (userQuery.Time.HasValue)                // if time exist
            {
                TimeSpan userQueryTime = userQuery.Time.Value.DateTime.TimeOfDay;
                newTp.StartTime = oldTp.StartTime?.Date.Add(userQueryTime).Add(TimeSpan.FromMinutes(-10));
                newTp.EndTime   = oldTp.EndTime?.Date.Add(userQueryTime).Add(TimeSpan.FromMinutes(+10));
                Console.WriteLine("\nNew Time:");
                Console.WriteLine("DateTimePeriod: " + newTp.StartTime.ToString() + " " + newTp.EndTime.ToString());
            }

            return(newTp);
        }
        private static TimePeriodDTO RecognizeDate(DateTimeOffset?date, TimePeriodDTO oldTp)
        {
            TimePeriodDTO newTp = new TimePeriodDTO(oldTp);

            // if user input date
            if (date.HasValue)
            {
                DateTimeOffset newDateTimeUtc = date.Value.UtcDateTime;
                DateTimeOffset newDate        = newDateTimeUtc.Date.Add(TimeSpan.Zero);          //extract date with zero time

                TimeSpan?deltaStart = oldTp.StartTime?.Date.Subtract(newDate.Date);
                TimeSpan?deltaEnd   = oldTp.EndTime?.Date.Subtract(newDate.Date);

                newTp.StartTime = oldTp.StartTime.Value.DateTime - deltaStart;
                newTp.EndTime   = oldTp.EndTime.Value.DateTime - deltaEnd;               //delta the same as for tp.StartTime

                Console.WriteLine("\nNew Date:");
                Console.WriteLine("newDate: " + newDate.ToString());
                Console.WriteLine("delta: " + deltaStart.ToString() + "   " + deltaEnd.ToString());
                Console.WriteLine("DateExist: " + newTp.StartTime.ToString() + " " + newTp.EndTime.ToString());
            }

            return(newTp);
        }
 public TimePeriodVM(TimePeriodDTO row)
 {
     Id         = row.Id;
     TimePeriod = row.TimePeriod;
 }
        public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file)
        {
            // Check model state
            if (!ModelState.IsValid)
            {
                using (Db db = new Db())
                {
                    model.Categories  = new SelectList(db.Categories.ToList(), "Id", "Name");
                    model.TimePeriods = new SelectList(db.TimePeriods.ToList(), "Id", "TimePeriod");
                    model.Cities      = new SelectList(db.Cities.ToList(), "Id", "CityName");
                    return(View(model));
                }
            }

            // Make sure product name is unique
            using (Db db = new Db())
            {
                if (db.Products.Any(x => x.Name == model.Name))
                {
                    model.Categories  = new SelectList(db.Categories.ToList(), "Id", "Name");
                    model.TimePeriods = new SelectList(db.TimePeriods.ToList(), "Id", "TimePeriod");
                    model.Cities      = new SelectList(db.Cities.ToList(), "Id", "CityName");
                    ModelState.AddModelError("", "That product name is taken!");
                    return(View(model));
                }
            }

            // Declare product id
            int id;

            // Init and save productDTO
            using (Db db = new Db())
            {
                ProductDTO product = new ProductDTO();

                product.Name        = model.Name;
                product.Description = model.Description;
                product.Price       = model.Price;
                product.Date        = model.Date;

                product.CategoryId = model.CategoryId;
                CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId);
                product.CategoryName = catDTO.Name;

                product.TimePeriodId = model.TimePeriodId;
                TimePeriodDTO timePeriodDTO = db.TimePeriods.FirstOrDefault(x => x.Id == model.TimePeriodId);
                product.TimePeriodName = timePeriodDTO.TimePeriod;

                product.PlaceId = model.PlaceId;
                CityDTO cityDTO = db.Cities.FirstOrDefault(x => x.Id == model.PlaceId);
                product.Place = cityDTO.CityName;

                db.Products.Add(product);
                db.SaveChanges();

                // Get the id
                id = product.Id;
            }

            // Set TempData message
            TempData["SM"] = "You have added a product!";

            #region Upload Image

            // Create necessary directories
            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\")));

            var pathString1 = Path.Combine(originalDirectory.ToString(), "Products");
            var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString());
            var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs");
            var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery");
            var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs");

            if (!Directory.Exists(pathString1))
            {
                Directory.CreateDirectory(pathString1);
            }

            if (!Directory.Exists(pathString2))
            {
                Directory.CreateDirectory(pathString2);
            }

            if (!Directory.Exists(pathString3))
            {
                Directory.CreateDirectory(pathString3);
            }

            if (!Directory.Exists(pathString4))
            {
                Directory.CreateDirectory(pathString4);
            }

            if (!Directory.Exists(pathString5))
            {
                Directory.CreateDirectory(pathString5);
            }

            // Check if a file was uploaded
            if (file != null && file.ContentLength > 0)
            {
                // Get file extension
                string ext = file.ContentType.ToLower();

                // Verify extension
                if (ext != "image/jpg" &&
                    ext != "image/jpeg" &&
                    ext != "image/pjpeg" &&
                    ext != "image/gif" &&
                    ext != "image/x-png" &&
                    ext != "image/png")
                {
                    using (Db db = new Db())
                    {
                        model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");
                        ModelState.AddModelError("", "The image was not uploaded - wrong image extension.");
                        return(View(model));
                    }
                }

                // Init image name
                string imageName = file.FileName;

                // Save image name to DTO
                using (Db db = new Db())
                {
                    ProductDTO dto = db.Products.Find(id);
                    dto.ImageName = imageName;

                    db.SaveChanges();
                }

                // Set original and thumb image paths
                var path  = string.Format("{0}\\{1}", pathString2, imageName);
                var path2 = string.Format("{0}\\{1}", pathString3, imageName);

                // Save original
                file.SaveAs(path);

                // Create and save thumb
                WebImage img = new WebImage(file.InputStream);
                img.Resize(200, 200);
                img.Save(path2);
            }

            #endregion

            // Redirect
            return(RedirectToAction("AddProduct"));
        }