Beispiel #1
0
        public static User AddFromDto(UULContext context, NewUserDTO newUser)
        {
            var salt = SecHelper.CreateSalt();

            var habitant = new Habitant(newUser);

            context.Habitants.Add(habitant);

            var userToSave = new User {
                Login         = newUser.Login,
                IsActivated   = false,
                CreatedAt     = DateOperations.Now(),
                Hash          = SecHelper.SaltAndHashPwd(newUser.Pwd, salt),
                Salt          = salt,
                ApartmentCode = newUser.ApartmentCode,
                Habitants     = new List <Habitant>()
                {
                    habitant
                }
            };

            context.Users.Add(userToSave);

            return(userToSave);
        }
        Task IHostedService.StartAsync(CancellationToken cancellationToken)
        {
            // timer repeates call to CreateTimeSlots every 24 hours.
            TimeSpan interval = TimeSpan.FromHours(24);                        //.FromMinutes(1);//
                                                                               //calculate time to run the first time & delay to set the timer
                                                                               //DateTime.Today gives time of midnight 00.00
            var nextRunTime   = DateOperations.Today().AddDays(1).AddHours(7); // DateTime.Now.AddMinutes(2);//
            var curTime       = DateOperations.Now();                          // DateTime.Now;
            var firstInterval = nextRunTime.Subtract(curTime);

            void action()
            {
                var t1 = Task.Delay(firstInterval, cancellationToken);

                t1.Wait(cancellationToken);
                //create at expected time
                _logger.LogInformation("First service run");
                CreateTimeSlots(null);
                //now schedule it to be called every 24 hours for future
                // timer repeates call to CreateTimeSlots every 24 hours.
                _timer = new Timer(
                    CreateTimeSlots,
                    null,
                    TimeSpan.Zero,
                    interval
                    );
            }

            // no need to await this call here because this task is scheduled to run much much later.
            Task.Run(action, cancellationToken);
            return(Task.CompletedTask);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            IReader      reader  = new XmlReader();
            List <Entry> entries = reader.Read("data.xml");

            ConsoleUserInterface ui = new ConsoleUserInterface();

            DateTime[] range = ui.init();

            List <Entry> entriesInRange = DateOperations.Intersection(entries, range[0], range[1]);
            List <Entry> sortedEntries  = ValueOperations.SortByAscending(entriesInRange);
            double       avgInRange     = ValueOperations.FindAverage(entriesInRange);
            int          maxInRange     = ValueOperations.FindMax(entriesInRange);

            IWriter writer = new FileWriter();

            writer.AddToWrite("Entries in range " + range[0].ToString("yyyy/MM/dd") + " - " + range[1].ToString("yyyy/MM/dd") + ":");
            foreach (Entry entry in entriesInRange)
            {
                writer.AddToWrite("Date: " + entry.Date.ToString("yyyy/MM/dd") + "  Value: " + entry.Value);
            }

            writer.AddToWrite("Sorted by value in ascending order:");
            foreach (Entry entry in sortedEntries)
            {
                writer.AddToWrite("Date: " + entry.Date.ToString("yyyy/MM/dd") + "  Value: " + entry.Value);
            }

            writer.AddToWrite("Average value: " + avgInRange);
            writer.AddToWrite("Max value: " + maxInRange);

            writer.Write();
        }
Beispiel #4
0
        public async Task <ActionResult <UULResponse> > GetTimeSlots(int year, int month, int day)
        {
            UULResponse response;

            try {
                var rulesDto = await RulesDao.GetCurrentRulesDTOOrDefault(_context);

                if (rulesDto == null)
                {
                    return(Error.RulesNotFound.CreateErrorResponse(_logger, "GetTimeSlots"));
                }
                DateOperations.GetTimeSlotsBoundsUtc(rulesDto.TimeSlotSpan, year, month, day, out DateTime start, out DateTime end);
                var slots = await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, start, end);

                var data = new ScheduleDTO()
                {
                    Date = year + "/" + month + "/" + day, GymId = null, TimeSlots = slots
                };
                response = new UULResponse()
                {
                    Success = true, Message = year + "/" + month + "/" + day, Data = data
                };
            } catch (Exception e) {
                response = Error.TimeSlotsGetFailed.CreateErrorResponse(_logger, "GetTimeSlots", e);
            }
            return(response);
        }
Beispiel #5
0
        public static async Task <List <TimeSlot> > CreateTimeSlotsForDateUTC(UULContext context, DateTime dateUtc, int hourToStart)
        {
            var rules = await RulesDao.GetCurrentRulesOrDefault(context);

            DateOperations.GetTimeSlotsBoundsUtc(rules.TimeSlotSpan, dateUtc.Year, dateUtc.Month, dateUtc.Day, out DateTime start, out DateTime end);
            var existent = await TimeSlotsDao.GetTimeSlotsByUtcBounds(context, start, end);

            if (existent.Count != 0)
            {
                return(new List <TimeSlot>());
            }
            var limit     = dateUtc.AddDays(1);
            var slotStart = dateUtc.AddHours(hourToStart);
            var slots     = new List <TimeSlot>();
            var slotSpan  = TimeSpan.FromMinutes(rules.TimeSlotSpan);

            while (slotStart.CompareTo(limit) < 0)
            {
                foreach (Gym gym in rules.Gyms)
                {
                    var slot = new TimeSlot {
                        Start = slotStart.ToUniversalTime(),
                        End   = (slotStart + slotSpan).ToUniversalTime(),
                        Gym   = gym
                    };
                    slots.Add(slot);
                }
                slotStart += slotSpan;
            }
            return(slots);
        }
Beispiel #6
0
 /// <summary>
 /// Reads last answer.
 /// </summary>
 /// <param name="parent">Xml node that contains question data.</param>
 public void ReadLastResult(XElement parent)
 {
     if (!string.IsNullOrEmpty(parent.Element("date").Value))
     {
         DateOperations operationsOnDate = new DateOperations();
         string         strDate          = parent.Element("date").Value;
         DateTime       date             = operationsOnDate.MilisecondsToDateTime(Convert.ToInt64(strDate));
         Answer = date.ToLongDateString();
         RaisePropertyChanged("Answer");
     }
 }
Beispiel #7
0
        public static User CreateDefaultAdmin()
        {
            var salt = CreateSalt();

            return(new User()
            {
                ApartmentCode = AdminAppCode,
                Login = Admin,
                IsActivated = true,
                CreatedAt = DateOperations.Now(),
                Hash = SaltAndHashPwd("thecownamedlolasayshola", salt),
                Salt = salt,
            });
        }
        public void ItersectionCountTest1()
        {
            List <Entry> entries = new List <Entry>
            {
                new Entry {
                    Date = new DateTime(2019, 10, 1), Value = 3
                },
                new Entry {
                    Date = new DateTime(2019, 10, 2), Value = 4
                },
                new Entry {
                    Date = new DateTime(2019, 10, 3), Value = 7
                },
                new Entry {
                    Date = new DateTime(2019, 10, 4), Value = 2
                },
                new Entry {
                    Date = new DateTime(2019, 10, 5), Value = 1
                },
                new Entry {
                    Date = new DateTime(2019, 10, 6), Value = 6
                },
                new Entry {
                    Date = new DateTime(2019, 10, 7), Value = 10
                }
            };

            List <Entry> expected = new List <Entry>
            {
                new Entry {
                    Date = new DateTime(2019, 10, 3), Value = 7
                },
                new Entry {
                    Date = new DateTime(2019, 10, 4), Value = 2
                },
                new Entry {
                    Date = new DateTime(2019, 10, 5), Value = 1
                },
                new Entry {
                    Date = new DateTime(2019, 10, 6), Value = 6
                }
            };

            DateTime lowerBound = new DateTime(2019, 10, 3);
            DateTime upperBound = new DateTime(2019, 10, 6);

            List <Entry> actual = DateOperations.Intersection(entries, lowerBound, upperBound);

            Assert.AreEqual(expected.Count, actual.Count);
        }
Beispiel #9
0
        /// <summary>
        /// Method to saving new/modified result.
        /// </summary>
        public void SaveSurveyResult()
        {
            Thread t = new Thread(new ThreadStart(() =>
            {
                if (!string.IsNullOrEmpty(ResultInfo.Title))
                {
                    DateOperations operationsOnDate = new DateOperations();

                    XDocument documentXML = PrepareResultDocument();
                    string dataToSave;

                    if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
                    {
                        AESEncryption encrypter = new AESEncryption();
                        dataToSave = encrypter.Encrypt(documentXML.ToString(), App.AppDictionary["EncryptionPassword"] as string, "qwhmvbzx");
                    }
                    else

                    {
                        dataToSave = documentXML.ToString();
                    }

                    using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string directoryPath  = string.Format("surveys/{0}", Id);
                        string resultFilePath = System.IO.Path.Combine(directoryPath, string.Format("r_{0}.xml", ResultInfo.Id));
                        if (!isolatedStorage.DirectoryExists(directoryPath))
                        {
                            isolatedStorage.CreateDirectory(directoryPath);
                        }
                        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Create, isolatedStorage))
                        {
                            StreamWriter writer = new StreamWriter(isoStream);
                            writer.Write(dataToSave);
                            writer.Close();
                        }
                    }
                    AddResultToList();
                }
                EventHandler handler = SavingCompletedEventHandler;
                if (handler != null)
                {
                    handler(this, EventArgs.Empty);
                }
                IsResultChanged = false;
            }));

            t.Start();
        }
Beispiel #10
0
        /// <summary>
        /// Adds question result to xml file.
        /// </summary>
        /// <param name="parent">Xml node that contains question data.</param>
        /// <returns>True if result was added successfully, in any other case false. </returns>
        public bool AddResult(XElement parent)
        {
            XElement       child            = new XElement("date");
            DateOperations operationsOnDate = new DateOperations();
            DateTime       selectedDate     = DateTime.Now;

            if (IsCorrectAnswer && !string.IsNullOrEmpty(Answer) && IsEnabled)
            {
                //selectedDate = DateTime.Parse(_answer, CultureInfo.CurrentCulture);
                selectedDate = DateTime.Parse(_answer, new CultureInfo("en-US"));
            }
            child.Value = operationsOnDate.DateTimeToMiliseconds(selectedDate).ToString();
            parent.Add(child);
            return((IsCorrectAnswer && !string.IsNullOrEmpty(Answer)) || !IsEnabled);
        }
Beispiel #11
0
        private Question CreateDateQuestion(XElement questionIterator, Category parent)
        {
            DateOperations operationsOnDate = new DateOperations();
            DateQuestion   dateQuestion     = new DateQuestion(parent);

            if (questionIterator.Attribute("max").Value != "")
            {
                dateQuestion.MaxDate = operationsOnDate.ParseDate(questionIterator.Attribute("max").Value);
            }
            if (questionIterator.Attribute("min").Value != "")
            {
                dateQuestion.MinDate = operationsOnDate.ParseDate(questionIterator.Attribute("min").Value);
            }
            dateQuestion.Answer = DateTime.Now.ToLongDateString();
            return(dateQuestion);
        }
Beispiel #12
0
        public async Task <ActionResult <UULResponse> > CreateOrUpdateNews(NewsWebDTO dto)
        {
            UULResponse response;

            try {
                var user = await UserDao.GetUserFromClaimsOrThrow(_context, HttpContext.User);

                if (!SecHelper.IsAdmin(user))
                {
                    throw new Exception("Access denied");
                }
                var news = new News(dto);
                var now  = DateOperations.Now();
                if (news.ID == null)
                {
                    news.CreatedAt = now;
                }
                else
                {
                    news.UpdatedAt = now;
                }
                string message = "News was created";
                if (news.ID == null)
                {
                    _context.News.Add(news);
                }
                else
                {
                    _context.News.Update(news);
                    message = "News was upadted";
                }
                await _context.SaveChangesAsync();

                response = new UULResponse()
                {
                    Success = true, Message = message, Data = new NewsWebDTO(news)
                };
            } catch (Exception e) {
                response = new UULResponse()
                {
                    Success = false, Message = e.Message, Data = null
                };
            }
            return(response);
        }
Beispiel #13
0
        public static string GenerateJSONWebToken(string login, string apartmentCode, IConfiguration _config)
        {
            var key         = _config["Jwt:Key"];
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(ClaimLogin, login),
                new Claim(ClaimApartmentCode, apartmentCode)
            };

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                                             _config["Jwt:Issuer"],
                                             claims,
                                             expires: DateOperations.Now().AddDays(360),
                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Beispiel #14
0
        public void LoadResultsIntoDb()
        {
            Database       database    = new Database();
            DateOperations csv         = new DateOperations();
            var            reader      = new StreamReader("D:\\Dropbox\\Share\\Excels\\Indexer Data\\scores.csv");
            List <string>  records     = new List <string>();
            bool           isFirstLine = true;

            while (!reader.EndOfStream)
            {
                var values = reader.ReadLine().Split(';');

                if (isFirstLine == true)
                {
                    isFirstLine = false;
                    continue;
                }

                records.Add(values[0]);
            }

            foreach (var record in records)
            {
                List <string> values = record.Split(',').ToList();
                database.Results.Add(new Result()
                {
                    Date        = csv.StringToInt(values[0]),
                    HomeTeam    = values[1],
                    AwayTeam    = values[2],
                    HomeGoals   = int.Parse(values[3]),
                    AwayGoals   = int.Parse(values[4]),
                    Competition = values[5],
                    Neutral     = Convert.ToBoolean(values[8])
                });
            }

            database.SaveChanges();
        }
 /// <summary>
 /// Adds question result to xml file.
 /// </summary>
 /// <param name="parent">Xml node that contains question data.</param>
 /// <returns>True if result was added successfully, in any other case false. </returns>
 public bool AddResult(XElement parent)
 {
     XElement child = new XElement("date");
     DateOperations operationsOnDate = new DateOperations();
     DateTime selectedDate = DateTime.Now;
     if (IsCorrectAnswer && !string.IsNullOrEmpty(Answer) && IsEnabled)
     {
         //selectedDate = DateTime.Parse(_answer, CultureInfo.CurrentCulture);
         selectedDate = DateTime.Parse(_answer, new CultureInfo("en-US"));
     }
         child.Value = operationsOnDate.DateTimeToMiliseconds(selectedDate).ToString();
     parent.Add(child);
     return (IsCorrectAnswer && !string.IsNullOrEmpty(Answer)) || !IsEnabled;
 }
Beispiel #16
0
 public static Task <List <TimeSlot> > CreateTodayTimeSlots(UULContext context, int hourToStart) => CreateTimeSlotsForDateUTC(context, DateOperations.Today(), hourToStart);
Beispiel #17
0
        /// <summary>
        /// Method to prepare XML file based on information about filled out survey.
        /// </summary>
        /// <returns>Return result in proper XML format.</returns>
        public XDocument PrepareResultDocument()
        {
            _isResultCompleted = true;
            DateOperations operationsOnDate = new DateOperations();
            XDocument      resultDocument   = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

            DateTime centuryBegin = new DateTime(2001, 1, 1);

            string userId = OperationsOnSettings.Instance.IMEI;
            string time   = operationsOnDate.DateTimeToMiliseconds(DateTime.Now).ToString();

            ResultInfo.Time     = time;
            ResultInfo.ParentId = Id;
            string resultId;

            if (string.IsNullOrEmpty(ResultInfo.Id))
            {
                ResultInfo.Id = GenerateUniqueID();
            }
            resultId = ResultInfo.Id;

            XElement root = new XElement("result", new XAttribute("r_id", resultId), new XAttribute("s_id", Id), new XAttribute("u_id", userId), new XAttribute("time", time), new XAttribute("version", 2));

            if (((ResultInfo.Latitude == null) || (ResultInfo.Longitude == null)))
            {
                if (OperationsOnSettings.Instance.GPS)
                {
                    var position = GPSService.Instance.Location;
                    if (position != null)
                    {
                        IsGpsSet = true;
                        XElement latitude  = new XElement("latitude");
                        XElement longitude = new XElement("longitude");
                        latitude.Value       = position.Latitude.ToString();
                        longitude.Value      = position.Longitude.ToString();
                        ResultInfo.Latitude  = position.Latitude.ToString();
                        ResultInfo.Longitude = position.Longitude.ToString();
                        root.Add(latitude);
                        root.Add(longitude);
                        OperationsOnListOfResults listOperator = new OperationsOnListOfResults(Id);
                        listOperator.UpdateLocation(ResultInfo.Id, position.Latitude.ToString(), position.Longitude.ToString());
                    }
                    else
                    {
                        IsGpsSet = false;
                    }
                }
                else
                {
                    IsGpsSet = true;
                }
            }
            else
            {
                XElement latitude  = new XElement("latitude");
                XElement longitude = new XElement("longitude");
                latitude.Value  = ResultInfo.Latitude;
                longitude.Value = ResultInfo.Longitude;
                root.Add(latitude);
                root.Add(longitude);
                IsGpsSet = true;
            }
            XElement titleElement = new XElement("title");

            if (!string.IsNullOrEmpty(ResultInfo.Title))
            {
                titleElement.Value = ResultInfo.Title;
            }
            root.Add(titleElement);

            foreach (Category category in Categories)
            {
                XElement categoryXElement = new XElement("category", new XAttribute("name", category.Name), new XAttribute("id", category.Id));
                if (!category.AddResult(categoryXElement))
                {
                    _isResultCompleted = false;
                }
                root.Add(categoryXElement);
            }
            resultDocument.AddFirst(root);
            ResultInfo.IsResultCompleted = _isResultCompleted;
            return(resultDocument);
        }
Beispiel #18
0
        private async Task <ActionResult <UULResponse> > BookTimeSlotByGym(BookTimeSlotDTO dto, int gymId)
        {
            UULResponse response; // TODO refactor to use exceptions
            var         currentUser = HttpContext.User;

            try {
                var userInfo = SecHelper.GetUserInfo(currentUser.Claims);
                var user     = await _context.Users.Where(u => u.Login.Equals(userInfo.Login) && u.ApartmentCode.Equals(userInfo.ApartmentCode)).SingleOrDefaultAsync();

                if (user is null)
                {
                    return(Error.ProfileNotFound.CreateErrorResponse(_logger, "BookTimeSlotsByGym"));
                }
                if (!user.IsActivated)
                {
                    return(Error.ProfileNotActivated.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                var timeSlot = await _context.TimeSlots
                               .Include(t => t.OccupiedBy)
                               .Include(t => t.Gym)
                               .FirstOrDefaultAsync(t => t.ID == dto.TimeslotId);

                if (timeSlot is null)
                {
                    return(Error.TimeSlotNotFound.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                var rulesDto = await RulesDao.GetCurrentRulesDTOOrDefault(_context);

                if (rulesDto is null)
                {
                    return(Error.RulesNotFound.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                DateOperations.GetTodayTimeSlotsBoundsUtc(rulesDto.TimeSlotSpan, out DateTime todayStart, out DateTime todayEnd);

                if (!timeSlot.Gym.IsOpen)
                {
                    return(Error.GymClosed.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (!(timeSlot.Start.IsWithinBounds(todayStart, todayEnd)))
                {
                    return(Error.TimeSlotNotToday.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (timeSlot.OccupiedBy.Count >= rulesDto.PersonsPerTimeSlot)
                {
                    return(Error.TimeSlotFull.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                if (await AlreadyBookedInBoundsUTC(dto.HabitantId, todayStart, todayEnd))
                {
                    return(Error.TimeSlotOverbooking.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }

                Habitant habitant = await _context.Habitants.FindAsync(dto.HabitantId);

                if (habitant is null)
                {
                    return(Error.ProfileHabitantLookupFailed.CreateErrorResponse(_logger, "BookTimesSlotsByGym"));
                }
                timeSlot.OccupiedBy.Add(habitant);
                habitant.LastGymVisit = timeSlot.Start;
                _context.TimeSlots.Update(timeSlot);
                _context.Habitants.Update(habitant);
                var success = await _context.SaveChangesAsync() != 0;

                var slots = gymId == -1 ? await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, todayStart, todayEnd) : await TimeSlotsDao.GetTimeSlotsByUtcBounds(_context, gymId, todayStart, todayEnd);

                var data = new ScheduleDTO()
                {
                    Date = todayStart.Year + "/" + todayStart.Month + "/" + todayStart.Day, GymId = gymId == -1 ? null : gymId, TimeSlots = slots
                };
                response = new UULResponse()
                {
                    Success = success, Message = "Booked", Data = data
                };
            } catch (Exception e) {
                response = Error.TimeSlotsBookingFailed.CreateErrorResponse(_logger, "BookTimesSlotsByGym", e);
            }
            return(response);
        }
Beispiel #19
0
        /// <summary>
        /// Method to prepare XML file based on information about filled out survey.
        /// </summary>
        /// <returns>Return result in proper XML format.</returns>
        public XDocument PrepareResultDocument()
        {
            _isResultCompleted = true;
            DateOperations operationsOnDate = new DateOperations();
            XDocument resultDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));

            DateTime centuryBegin = new DateTime(2001, 1, 1);

            string userId = OperationsOnSettings.Instance.IMEI;
            string time = operationsOnDate.DateTimeToMiliseconds(DateTime.Now).ToString();
            ResultInfo.Time = time;
            ResultInfo.ParentId = Id;
            string resultId;
            if (string.IsNullOrEmpty(ResultInfo.Id))
            {
                ResultInfo.Id = GenerateUniqueID();
            }
            resultId = ResultInfo.Id;

            XElement root = new XElement("result", new XAttribute("r_id", resultId), new XAttribute("s_id", Id), new XAttribute("u_id", userId), new XAttribute("time", time), new XAttribute("version", 2));
            if (((ResultInfo.Latitude == null) || (ResultInfo.Longitude == null)))
            {
                if (OperationsOnSettings.Instance.GPS)
                {
                    var position = GPSService.Instance.Location;
                    if (position != null)
                    {
                        IsGpsSet = true;
                        XElement latitude = new XElement("latitude");
                        XElement longitude = new XElement("longitude");
                        latitude.Value = position.Latitude.ToString();
                        longitude.Value = position.Longitude.ToString();
                        ResultInfo.Latitude = position.Latitude.ToString();
                        ResultInfo.Longitude = position.Longitude.ToString();
                        root.Add(latitude);
                        root.Add(longitude);
                        OperationsOnListOfResults listOperator = new OperationsOnListOfResults(Id);
                        listOperator.UpdateLocation(ResultInfo.Id, position.Latitude.ToString(), position.Longitude.ToString());
                    }
                    else
                    {
                        IsGpsSet = false;
                    }
                }
                else
                {
                    IsGpsSet = true;
                }
            }
            else
            {
                XElement latitude = new XElement("latitude");
                XElement longitude = new XElement("longitude");
                latitude.Value = ResultInfo.Latitude;
                longitude.Value = ResultInfo.Longitude;
                root.Add(latitude);
                root.Add(longitude);
                IsGpsSet = true;
            }
            XElement titleElement = new XElement("title");
            if (!string.IsNullOrEmpty(ResultInfo.Title))
                titleElement.Value = ResultInfo.Title;
            root.Add(titleElement);

            foreach (Category category in Categories)
            {
                XElement categoryXElement = new XElement("category", new XAttribute("name", category.Name), new XAttribute("id", category.Id));
                if (!category.AddResult(categoryXElement))
                {
                    _isResultCompleted = false;
                }
                root.Add(categoryXElement);
            }
            resultDocument.AddFirst(root);
            ResultInfo.IsResultCompleted = _isResultCompleted;
            return resultDocument;
        }
Beispiel #20
0
        /// <summary>
        /// Method to saving new/modified result.
        /// </summary>
        public void SaveSurveyResult()
        {
            Thread t = new Thread(new ThreadStart(() =>
            {
                if (!string.IsNullOrEmpty(ResultInfo.Title))
                {
                    DateOperations operationsOnDate = new DateOperations();

                    XDocument documentXML = PrepareResultDocument();
                    string dataToSave;

                    if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
                    {
                        AESEncryption encrypter = new AESEncryption();
                        dataToSave = encrypter.Encrypt(documentXML.ToString(), App.AppDictionary["EncryptionPassword"] as string, "qwhmvbzx");
                    }
                    else

                    {
                        dataToSave = documentXML.ToString();
                    }

                    using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string directoryPath = string.Format("surveys/{0}", Id);
                        string resultFilePath = System.IO.Path.Combine(directoryPath, string.Format("r_{0}.xml", ResultInfo.Id));
                        if (!isolatedStorage.DirectoryExists(directoryPath))
                        {
                            isolatedStorage.CreateDirectory(directoryPath);
                        }
                        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Create, isolatedStorage))
                        {

                            StreamWriter writer = new StreamWriter(isoStream);
                            writer.Write(dataToSave);
                            writer.Close();
                        }
                    }
                    AddResultToList();
                }
                EventHandler handler = SavingCompletedEventHandler;
                if (handler != null)
                    handler(this, EventArgs.Empty);
                IsResultChanged = false;
            }));
            t.Start();
        }
Beispiel #21
0
 private Question CreateDateQuestion(XElement questionIterator, Category parent)
 {
     DateOperations operationsOnDate = new DateOperations();
     DateQuestion dateQuestion = new DateQuestion(parent);
     if (questionIterator.Attribute("max").Value != "")
     {
         dateQuestion.MaxDate = operationsOnDate.ParseDate(questionIterator.Attribute("max").Value);
     }
     if (questionIterator.Attribute("min").Value != "")
     {
         dateQuestion.MinDate = operationsOnDate.ParseDate(questionIterator.Attribute("min").Value);
     }
     dateQuestion.Answer = DateTime.Now.ToLongDateString();
     return dateQuestion;
 }
        private void CreateTimeSlots(object state)
        {
            var scope     = _scopeFactory.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService <UULContext>();
            var newSlots  = TimeSlotsFactory.CreateTodayTimeSlots(dbContext, 11);

            newSlots.Wait();
            dbContext.TimeSlots.AddRange(newSlots.Result);
            int rows = dbContext.SaveChanges();

            _logger.LogInformation("Creation func affected " + rows + " rows, run at " + DateOperations.Now().ToString());
            scope.Dispose();
        }
Beispiel #23
0
        /// <summary>
        /// Method to prepare new results with right date and GPS location.
        /// </summary>
        public void PreapreResultsForTests()
        {
            DateOperations operationsOnDate = new DateOperations();

            // Wynik 1_1: Data utworzenia: 2/2/2010,  szerokość: 52, długość: 21 (Warszawa)
            Survey survey = new Survey();

            survey.Display(Convert.ToInt32(SurveyId));
            survey.ResultInfo.Title     = "test1";
            survey.ResultInfo.Latitude  = "52";
            survey.ResultInfo.Longitude = "21";
            XDocument documentXML = survey.PrepareResultDocument();

            survey.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2010, 2, 2)).ToString();

            SavetTestResult(survey, documentXML);

            // Wynik 1_2: Data utworzenia: 2/24/2010, bez GPS
            Survey survey1 = new Survey();

            survey1.Display(Convert.ToInt32(SurveyId));
            survey1.ResultInfo.Title = "test2";
            XDocument documentXML1 = survey1.PrepareResultDocument();

            survey1.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2010, 2, 24)).ToString();
            if (documentXML1.Element("latitude") != null)
            {
                documentXML1.Element("latitude").Remove();
            }

            if (documentXML1.Element("longitude") != null)
            {
                documentXML1.Element("longitude").Remove();
            }

            SavetTestResult(survey1, documentXML1);

            // Wynik 1_3: Data utworzenia: 5/10/2010,  szerokość: 50, długość: 20 (Kraków)
            Survey survey2 = new Survey();

            survey2.Display(Convert.ToInt32(SurveyId));
            survey2.ResultInfo.Title     = "test3";
            survey2.ResultInfo.Latitude  = "50";
            survey2.ResultInfo.Longitude = "20";
            XDocument documentXML2 = survey2.PrepareResultDocument();

            survey2.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2010, 5, 10)).ToString();
            SavetTestResult(survey2, documentXML2);

            // Wynik 2_1: Data utworzenia: 2/2/2011,  szerokość: 50, długość: 19 (Katowice)
            Survey survey3 = new Survey();

            survey3.Display(Convert.ToInt32(SurveyId));
            survey3.ResultInfo.Title     = "test4";
            survey3.ResultInfo.Latitude  = "50";
            survey3.ResultInfo.Longitude = "19";
            XDocument documentXML3 = survey3.PrepareResultDocument();

            survey3.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2011, 2, 2)).ToString();
            SavetTestResult(survey3, documentXML3);

            // Wynik 2_2: Data utworzenia: 10/2/2011, szerokość: 50, długość: 20 (Kraków)
            Survey survey4 = new Survey();

            survey4.Display(Convert.ToInt32(SurveyId));
            survey4.ResultInfo.Title     = "test5";
            survey4.ResultInfo.Latitude  = "50";
            survey4.ResultInfo.Longitude = "20";
            XDocument documentXML4 = survey4.PrepareResultDocument();

            survey4.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2011, 10, 2)).ToString();
            SavetTestResult(survey4, documentXML4);

            // Wynik 3_1: Data utworzenia: 10/2/2011,  szerokość: 51, długość: 17 (Wrocław)
            Survey survey5 = new Survey();

            survey5.Display(Convert.ToInt32(SurveyId));
            survey5.ResultInfo.Title     = "test6";
            survey5.ResultInfo.Latitude  = "51";
            survey5.ResultInfo.Longitude = "17";
            XDocument documentXML5 = survey5.PrepareResultDocument();

            survey5.ResultInfo.Time = operationsOnDate.DateTimeToMiliseconds(new DateTime(2011, 10, 2)).ToString();

            SavetTestResult(survey5, documentXML5);
        }
 /// <summary>
 /// Reads last answer.
 /// </summary>
 /// <param name="parent">Xml node that contains question data.</param>
 public void ReadLastResult(XElement parent)
 {
     if (!string.IsNullOrEmpty(parent.Element("date").Value))
     {
         DateOperations operationsOnDate = new DateOperations();
         string strDate = parent.Element("date").Value;
         DateTime date = operationsOnDate.MilisecondsToDateTime(Convert.ToInt64(strDate));
         Answer = date.ToLongDateString();
         RaisePropertyChanged("Answer");
     }
 }