Example #1
0
        private void SetUpForSucceededOrderHandle(DateTime sightseeingDate, IEnumerable <Ticket> tickets)
        {
            var info = new VisitInfo {
                MaxAllowedGroupSize = 3
            };
            var existentGroup = new SightseeingGroup {
                MaxGroupSize = info.MaxAllowedGroupSize, SightseeingDate = sightseeingDate, Tickets = new Ticket[] { _ticket }
            };
            var newGroup = new SightseeingGroup {
                MaxGroupSize = info.MaxAllowedGroupSize, SightseeingDate = sightseeingDate, Tickets = (ICollection <Ticket>)tickets
            };

            _infoDbServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(new VisitInfo[] { info });

            _groupDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <SightseeingGroup, bool> > >())).ReturnsAsync(new SightseeingGroup[] { existentGroup });
            _groupDbServiceMock.Setup(x => x.RestrictedAddAsync(It.IsAny <SightseeingGroup>())).ReturnsAsync(newGroup);
            _groupDbServiceMock.Setup(x => x.RestrictedUpdateAsync(It.IsAny <SightseeingGroup>())).ReturnsAsync(existentGroup);

            _discountDbServiceMock.Setup(x => x.GetAsync(It.IsAny <string>())).ReturnsAsync(_discount);

            _ticketTariffDbServiceMock.Setup(x => x.GetAsync(It.IsAny <string>())).ReturnsAsync(_ticketTariff);

            // Only for CreateOrderAsync() purposes.
            _customerDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <Customer, bool> > >())).ReturnsAsync(new Customer[] { _customer });
        }
        public string GetForumFeedBack(string url, string remark)
        {
            ManageUserModel uM    = (ManageUserModel)Session["logUser"];
            string          uName = uM.Name;

            return(VisitInfo.GetForumFeedBack(url, uName, remark));
        }
Example #3
0
        public void SetUp()
        {
            _groupDbServiceMock = new Mock <ISightseeingGroupDbService>();
            _infoDbServiceMock  = new Mock <IVisitInfoDbService>();

            _dbServiceFactoryMock = new Mock <IIndex <string, IServiceBase> >();
            _dbServiceFactoryMock.Setup(x => x["ISightseeingGroupDbService"]).Returns(_groupDbServiceMock.Object);
            _dbServiceFactoryMock.Setup(x => x["IVisitInfoDbService"]).Returns(_infoDbServiceMock.Object);

            _validSightseeingGroup = new SightseeingGroup
            {
                Id              = "1",
                MaxGroupSize    = 30,
                SightseeingDate = new DateTime(2019, 12, 12, 12, 0, 0)
            };
            _validSightseeingGroupDto = new SightseeingGroupDto
            {
                Id               = "1",
                MaxGroupSize     = 30,
                SightseeingDate  = new DateTime(2019, 12, 12, 12, 0, 0),
                IsAvailablePlace = true,
                CurrentGroupSize = 20
            };

            _info = CreateModel.CreateInfo();

            _logger = Mock.Of <ILogger <GroupsController> >();

            _mapperMock = new Mock <IMapper>();
            _mapperMock.Setup(x => x.Map <SightseeingGroupDto>(It.IsAny <SightseeingGroup>())).Returns(_validSightseeingGroupDto);
            _mapperMock.Setup(x => x.Map <SightseeingGroup>(It.IsAny <SightseeingGroupDto>())).Returns(_validSightseeingGroup);
        }
Example #4
0
        private VisitInfoDto CreateInfoDto(VisitInfo info)
        {
            var infoDto = new VisitInfoDto
            {
                Id                     = info.Id,
                Description            = info.Description,
                MaxAllowedGroupSize    = info.MaxAllowedGroupSize,
                MaxChildAge            = info.MaxChildAge,
                MaxTicketOrderInterval = info.MaxTicketOrderInterval,
                SightseeingDuration    = info.SightseeingDuration,
                OpeningHours           = new OpeningHoursDto[] { }
            };

            foreach (var openingHour in info.OpeningHours)
            {
                infoDto.OpeningHours.ToList().Add(new OpeningHoursDto
                {
                    OpeningHour = openingHour.OpeningHour,
                    ClosingHour = openingHour.ClosingHour,
                    DayOfWeek   = openingHour.DayOfWeek
                });
            }

            return(infoDto);
        }
Example #5
0
        public async Task <IActionResult> GetAvailableGroupDatesAsync()
        {
            VisitInfo                  recentInfo     = null;
            IVisitInfoDbService        infoDbService  = null;
            ISightseeingGroupDbService groupDbService = null;
            List <GroupInfo>           availableDates = new List <GroupInfo>();

            try
            {
                infoDbService  = _dbServiceFactory[nameof(IVisitInfoDbService)] as IVisitInfoDbService;
                groupDbService = _dbServiceFactory[nameof(ISightseeingGroupDbService)] as ISightseeingGroupDbService;

                recentInfo = await GetRecentSightseeingInfoAsync(infoDbService);

                if (!IsSightseeingDurationSet(recentInfo))
                {
                    _logger.LogWarning($"{nameof(VisitInfo.SightseeingDuration)} is set to 0 hours.");
                    return(Ok(new ResponseWrapper(availableDates)));
                }

                // Calculate the latest date when you can still buy a ticket. MaxTicketOrderInterval is in weeks.
                var maxTicketPurchaseDate = DateTime.Now.AddDays(recentInfo.MaxTicketOrderInterval * 7);
                var dateTime = DateTime.Now;

                var futureGroups = await groupDbService.GetByAsync(x => x.SightseeingDate > DateTime.Now);

                // Create available sightseeing dates.
                while (dateTime <= maxTicketPurchaseDate)
                {
                    availableDates.AddRange(GetDailyDates(recentInfo, dateTime, futureGroups));
                    dateTime = dateTime.AddDays(1);
                }

                var response = new ResponseWrapper(availableDates);
                return(Ok(response));
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogWarning(ex, $"Element '{nameof(VisitInfo)}' not found.");
                return(Ok(new ResponseWrapper(availableDates)));
            }
            catch (InternalDbServiceException ex) when(recentInfo is null)
            {
                // Exception thrown by IVisitInfoDbService instance.
                LogInternalDbServiceException(ex, infoDbService.GetType());
                throw;
            }
            catch (InternalDbServiceException ex) when(recentInfo != null)
            {
                // Exception thrown by ISightseeingGroupDbService instance.
                LogInternalDbServiceException(ex, groupDbService.GetType());
                throw;
            }
            catch (Exception ex)
            {
                LogUnexpectedException(ex);
                throw;
            }
        }
Example #6
0
        /// <summary>
        /// Asynchronously retrieves <see cref="VisitInfo"/> entities with specified page size and page number.
        /// Throws an exception if arguments is out of range or any problem with retrieving occurred.
        /// </summary>
        /// <param name="pageNumber">Page number that will be retrieved. Must be greater than 0.</param>
        /// <param name="pageSize">Page size. Must be a positive number.</param>
        /// <returns>Set of <see cref="VisitInfo"/> entities.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="pageSize"/> is a negative number or <paramref name="pageNumber"/> is less than 1.</exception>
        /// <exception cref="InternalDbServiceException">The resource does not exist or has a null value or any
        /// other problems with retrieving data from database occurred.</exception>
        public async Task <IEnumerable <VisitInfo> > GetWithPaginationAsync(int pageNumber = 1, int pageSize = 30)
        {
            _logger.LogInformation($"Starting method '{nameof(GetWithPaginationAsync)}'.");

            if (pageNumber < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(pageNumber), $"'{pageNumber}' is not valid value for argument '{nameof(pageNumber)}'. Only number greater or equal to 1 are valid.");
            }

            if (pageSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(pageSize), $"'{pageSize}' is not valid value for argument '{nameof(pageSize)}'. Only number greater or equal to 0 are valid.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.Info ?? throw new InternalDbServiceException($"Table of type '{typeof(VisitInfo).Name}' is null.");

            try
            {
                IEnumerable <VisitInfo> info = new VisitInfo[] { }.AsEnumerable();
                int maxNumberOfPageWithData;

                int numberOfResourceElements = await _context.Info.CountAsync();

                int numberOfElementsOnLastPage = numberOfResourceElements % pageSize;
                int numberOfFullPages          = (numberOfResourceElements - numberOfElementsOnLastPage) / pageSize;

                if (numberOfElementsOnLastPage > 0)
                {
                    maxNumberOfPageWithData = ++numberOfFullPages;
                    _logger.LogWarning($"Last page of data contain {numberOfElementsOnLastPage} elements which is less than specified in {nameof(pageSize)}: {pageSize}.");
                }
                else
                {
                    maxNumberOfPageWithData = numberOfFullPages;
                }

                if (numberOfResourceElements == 0 || pageSize == 0 || pageNumber > maxNumberOfPageWithData)
                {
                    _logger.LogInformation($"Finished method '{nameof(GetWithPaginationAsync)}'. Returning {info.Count()} elements.");
                    return(info);
                }

                _logger.LogDebug($"Starting retrieve data. '{nameof(pageNumber)}': {pageNumber.ToString()}, '{nameof(pageSize)}': {pageSize.ToString()}.");
                info = _context.Info.Include(x => x.OpeningHours).Skip(pageSize * (pageNumber - 1)).Take(pageSize);
                _logger.LogDebug("Retrieve data succeeded.");
                _logger.LogInformation($"Finished method '{nameof(GetWithPaginationAsync)}'.");
                return(info);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when retrieving sightseeing info from the database. See the inner exception for more details.", ex);
                throw internalException;
            }
        }
Example #7
0
        private void DeleteUnusedOpeningHours(VisitInfo originalInfo, VisitInfo newInfo)
        {
            // Delete only those hours which belong to the updating info and don't belong to a new version of this info.
            // The OpeningHoursComparer to check which hours are unused in a new info version, is used here.
            var originalOpeningHours  = _context.OpeningDates.Where(x => x.Info.Id.Equals(originalInfo.Id)).AsEnumerable();
            var differentOpeningHours = originalOpeningHours.Except(newInfo.OpeningHours.AsEnumerable(), new OpeningHoursComparer());

            _context.OpeningDates.RemoveRange(differentOpeningHours);
        }
Example #8
0
        public IEnumerable<BfsState> DoSimpleBfs(UnitState startState, bool backwards, bool returnStateCopies)
        {
            var queue = new Queue<UnitState>();

            Debug.Assert(startState.GetCells(_unit).All(_field.IsValidCell));

            _visited[startState] = new VisitInfo
            {
                MoveFuncIndex = -1,
                PrevState = null,
                AllPrevStates = new HashSet<UnitState>(),
            };

            queue.Enqueue(startState);

            var moveFuncs = backwards ? UnitState.BackMoveFuncs : UnitState.MoveFuncs;

            BfsState returnState = new BfsState(null, null);

            while (queue.Count > 0)
            {
                var state = queue.Dequeue();

                int blockingMove = -1;
                for (int funcIndex = 0; funcIndex < moveFuncs.Length; ++funcIndex)
                {
                    UnitState newUnitState = moveFuncs[funcIndex](state);
                    newUnitState.Normalize(_unit);

                    Cell[] cells;
                    bool isBlocking;
                    if (!TryAddVisitedState(newUnitState, state, funcIndex, out cells, out isBlocking))
                    {
                        if (isBlocking)
                            blockingMove = funcIndex;
                        continue;
                    }

                    queue.Enqueue(newUnitState);
                }

                if (blockingMove >= 0 || backwards)
                {
                    if (returnStateCopies)
                    {
                        var retState = new BfsState(state, state.GetCells(_unit));
                        retState.BlockingMove = blockingMove;
                        yield return retState;
                    }
                    else
                    {
                        returnState.UnitState = state;
                        yield return returnState;
                    }
                }
            }
        }
Example #9
0
        public IEnumerable<BfsState> DoBfs(UnitState startState, PowerPhraseInfo[] powerPhrases)
        {
            var queue = new Queue<BfsState>();

            Debug.Assert(startState.GetCells(_unit).All(_field.IsValidCell));

            _visited[startState] = new VisitInfo
            {
                MoveFuncIndex = -1,
                PrevState = null,
                AllPrevStates = new HashSet<UnitState>(),
            };

            var startBfsState = new BfsState(startState, startState.GetCells(_unit));
            //BfsState stateAfterPhrase = startBfsState;
            //if (powerPhrases != null)
            //{
            //    foreach (var phraseInfo in powerPhrases)
            //    {
            //        stateAfterPhrase = ApplyPhraseManyTimes(startBfsState, phraseInfo);
            //        if (stateAfterPhrase.UnitState.Pivot != startState.Pivot || stateAfterPhrase.UnitState.Rotation != startState.Rotation)
            //            break;
            //    }
            //}

            var stateAfterPhrase = ApplyManyPhrasesManyTimes(startBfsState);

            queue.Enqueue(stateAfterPhrase);

            while (queue.Count > 0)
            {
                var state = queue.Dequeue();

                int blockingMove = -1;
                for (int funcIndex = 0; funcIndex < UnitState.MoveFuncs.Length; ++funcIndex)
                {
                    UnitState newUnitState = UnitState.MoveFuncs[funcIndex](state.UnitState);

                    Cell[] cells;
                    bool isBlocking;
                    if (!TryAddVisitedState(newUnitState, state.UnitState, funcIndex, out cells, out isBlocking))
                    {
                        if (isBlocking)
                            blockingMove = funcIndex;
                        continue;
                    }

                    queue.Enqueue(new BfsState(newUnitState, cells));
                }

                if (blockingMove >= 0)
                {
                    state.BlockingMove = blockingMove;
                    yield return state;
                }
            }
        }
Example #10
0
        public void SetUp()
        {
            _info = CreateModel.CreateInfo(maxAllowedGroupSize: MaxAllowedGroupSize);
            var _dbContextMock = new Mock <ApplicationDbContext>();

            _dbContextMock.Setup(x => x.Info).Returns(CreateMock.CreateDbSetMock <VisitInfo>(new VisitInfo[] { _info }).Object);
            _validator       = new SightseeingGroupValidator(_dbContextMock.Object);
            _maxDaysForOrder = _info.MaxTicketOrderInterval * 7;
        }
Example #11
0
 public void SetUp()
 {
     _infoDbServiceMock = new Mock <IVisitInfoDbService>();
     _logger            = Mock.Of <ILogger <VisitInfoController> >();
     _mapperMock        = new Mock <IMapper>();
     _info     = CreateModel.CreateInfo();
     _infoDto  = CreateInfoDto(_info);
     _infoDtos = new VisitInfoDto[] { _infoDto };
 }
        public JsonResult CheckIp(VisitInfo info)
        {
            var k = AntiForgeryConfig.CookieName;

            AntiForgery.Validate();
            var c       = Request.Cookies;
            var address = Request.UserHostAddress;

            info.Ip = address;
            return(Json(info));
        }
Example #13
0
        private void SetUpForFailedCreateNewGroup()
        {
            var info = new VisitInfo {
                MaxAllowedGroupSize = 1
            };

            _infoDbServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(new VisitInfo[] { info });

            _groupDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <SightseeingGroup, bool> > >())).ReturnsAsync(Enumerable.Empty <SightseeingGroup>());

            // Only for CreateOrderAsync() purposes.
            _customerDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <Customer, bool> > >())).ReturnsAsync(new Customer[] { _customer });
        }
Example #14
0
        private static string GetPrice
        (
            [NotNull] VisitInfo debt,
            [NotNull] MarcRecord bookRecord
        )
        {
            Code.NotNull(debt, "debt");

            string inventory = debt.Inventory;
            string barcode   = debt.Barcode;

            RecordField[] fields = bookRecord.Fields
                                   .GetField("910");

            string result = null;

            foreach (RecordField field in fields)
            {
                ExemplarInfo exemplar = ExemplarInfo.Parse(field);

                if (!string.IsNullOrEmpty(inventory))
                {
                    if (exemplar.Number.SameString(inventory))
                    {
                        if (!string.IsNullOrEmpty(barcode))
                        {
                            if (exemplar.Barcode.SameString(barcode))
                            {
                                result = exemplar.Price;
                                break;
                            }
                        }
                        else
                        {
                            result = exemplar.Price;
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                result = bookRecord.FM("10", 'd');
            }

            return(result);
        }
Example #15
0
        private void SetUpForFailedUpdate(DateTime sightseeingDate)
        {
            var info = new VisitInfo {
                MaxAllowedGroupSize = 1
            };
            var existentGroup = new SightseeingGroup {
                MaxGroupSize = 1, SightseeingDate = sightseeingDate, Tickets = new Ticket[] { _ticket }
            };

            _infoDbServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(new VisitInfo[] { info });

            _groupDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <SightseeingGroup, bool> > >())).ReturnsAsync(new SightseeingGroup[] { existentGroup });

            // Only for CreateOrderAsync() purposes.
            _customerDbServiceMock.Setup(x => x.GetByAsync(It.IsAny <Expression <Func <Customer, bool> > >())).ReturnsAsync(new Customer[] { _customer });
        }
Example #16
0
    /// <summary>
    /// 获取图片列表
    /// </summary>
    public void CreateItems(VisitInfo info)
    {
        pageCount++;
        SetContent(pageCount);
        ChangeItem item = GameObject.Instantiate <ChangeItem>(pageItemPrefab);

        item.transform.SetParent(Content.transform);
        item.transform.localScale    = Vector3.one;
        item.transform.localPosition = Vector3.zero;

        item.id        = info.id;
        item.name      = info.name;
        item.thumbnail = info.Thumbnail;
        item.content   = info.description;

        itemObj.Add(item.gameObject);
        item.gameObject.SetActive(true);
    }
Example #17
0
        private VisitInfo GetVisitInfo(string patientId, string visitId)
        {
            EMRDBLib.PatVisitInfo patVisitInfo = null;
            PatVisitAccess.Instance.GetPatVisitInfo(patientId, visitId, ref patVisitInfo);
            if (patVisitInfo == null)
            {
                return(null);
            }
            VisitInfo clientVisitInfo = new VisitInfo();

            clientVisitInfo.ID       = visitId;
            clientVisitInfo.InpID    = patVisitInfo.INP_NO;
            clientVisitInfo.Time     = patVisitInfo.VISIT_TIME;
            clientVisitInfo.WardCode = patVisitInfo.WARD_CODE;
            clientVisitInfo.WardName = patVisitInfo.WardName;
            clientVisitInfo.BedCode  = patVisitInfo.BED_CODE;
            clientVisitInfo.Type     = VisitType.IP;
            return(clientVisitInfo);
        }
Example #18
0
        private IList <GroupInfo> GetDailyDates(VisitInfo info, DateTime dateTime, IEnumerable <SightseeingGroup> futureGroups)
        {
            List <GroupInfo> availableDates = new List <GroupInfo>();
            var sightseeingDuration         = info.SightseeingDuration;
            var openingDateTime             = info.GetOpeningDateTime(dateTime);
            var openingHoursNumber          = info.GetClosingDateTime(dateTime) - openingDateTime;
            int groupsPerDay = (int)(openingHoursNumber.Hours / sightseeingDuration);

            // Get available sightseeing dates for one day.
            for (int i = 0; i < groupsPerDay; i++)
            {
                GroupInfo groupInfo     = new GroupInfo();
                var       groupDateTime = openingDateTime.AddHours(i * sightseeingDuration);

                // Get existed group with the same date as currently processing.
                var existedGroup = futureGroups.Where(z => z.SightseeingDate == groupDateTime);

                if (existedGroup.Count() == 0)
                {
                    groupInfo.AvailablePlace = info.MaxAllowedGroupSize;
                }
                else
                {
                    var group = existedGroup.FirstOrDefault();

                    if (group.IsAvailablePlace)
                    {
                        groupInfo.AvailablePlace = group.MaxGroupSize - group.CurrentGroupSize;
                    }
                    else
                    {
                        // If there is no group with available places, do not add the group and start the next iteration.
                        continue;
                    }
                }

                groupInfo.SightseeingDate = groupDateTime;
                availableDates.Add(groupInfo);
            }

            return(availableDates);
        }
Example #19
0
        /// <exception cref="InvalidOperationException"></exception>
        /// <exception cref="InternalDbServiceException"></exception>
        /// <exception cref="ArgumentException"></exception>
        private async Task <SightseeingGroup> HandleNonexistentGroupAsync(VisitInfo recentInfo, DateTime sightseeingDate, IEnumerable <ShallowTicket> shallowTickets)
        {
            if (shallowTickets.Count() > recentInfo.MaxAllowedGroupSize)
            {
                throw new InvalidOperationException($"Attempt to add tickets to the group failed. There are '{recentInfo.MaxAllowedGroupSize}' available places on date '{sightseeingDate.ToString()}'.");
            }

            SightseeingGroup newGroup = null;

            try
            {
                newGroup = new SightseeingGroup
                {
                    MaxGroupSize    = recentInfo.MaxAllowedGroupSize,
                    SightseeingDate = sightseeingDate
                };

                // Check if new group based on order data is valid (SightseeingDate etc.).
                var validationResult = _groupValidator.Validate(newGroup);

                if (!validationResult.IsValid)
                {
                    throw new InvalidOperationException($"The group cannot be properly handled due to validation problems. {validationResult.Errors.First().ErrorMessage}");
                }

                var tickets = await CreateTicketsAsync(shallowTickets) as ICollection <Ticket>;

                AddCustomerToTickets(_customer, tickets);
                newGroup.Tickets = tickets;
                return(await _groupDbService.RestrictedAddAsync(newGroup));
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError(ex, ex.Message);
                throw;
            }
            catch (InternalDbServiceException ex)
            {
                _logger.LogError(ex, $"The group cannot be properly handled. Group sightseeing date: '{newGroup.SightseeingDate.ToString()}'. { ex.Message}");
                throw;
            }
        }
Example #20
0
        private VisitInfo GetVisitInfo()
        {
            if (SystemParam.Instance.PatVisitInfo == null)
            {
                return(new VisitInfo());
            }

            VisitInfo clientVisitInfo = new VisitInfo();

            clientVisitInfo.ID       = SystemParam.Instance.PatVisitInfo.VISIT_ID;
            clientVisitInfo.InpID    = SystemParam.Instance.PatVisitInfo.INP_NO;
            clientVisitInfo.Time     = SystemParam.Instance.PatVisitInfo.VISIT_TIME;
            clientVisitInfo.WardCode = SystemParam.Instance.PatVisitInfo.DEPT_CODE;
            clientVisitInfo.WardName = SystemParam.Instance.PatVisitInfo.DEPT_NAME;
            //clientVisitInfo.CareCode = visitInfo.CareCode;
            //clientVisitInfo.CareName = visitInfo.CareName;
            clientVisitInfo.BedCode = SystemParam.Instance.PatVisitInfo.BED_CODE;
            clientVisitInfo.Type    = VisitType.IP;
            return(clientVisitInfo);
        }
Example #21
0
        public static VisitInfo GetActiveAllergyInfo(string bdResult)
        {
            var values = bdResult.Split('*');
            var result = new VisitInfo();

            if (string.IsNullOrEmpty(bdResult))
            {
                return(new VisitInfo());
            }

            VisitInfo info = new VisitInfo()
            {
                DoctorFirstName = Convert.ToString(values.GetValue(0)),
                DoctorLastName  = Convert.ToString(values.GetValue(1)),
                StartDateTime   = Convert.ToDateTime(values.GetValue(2)),
                Description     = Convert.ToString(values.GetValue(3)),
                Treatment       = Convert.ToString(values.GetValue(4))
            };

            return(info);
        }
Example #22
0
        public static List <ClosedAllergyInfo> GetClosedAllergiesInfo(string bdResult)
        {
            int index  = 0;
            var values = bdResult.Split('*');
            var result = new List <ClosedAllergyInfo>();

            if (string.IsNullOrEmpty(bdResult))
            {
                return(result);
            }
            for (int i = 0; i < values.Length; i += 11)
            {
                var visitOpening = new VisitInfo()
                {
                    DoctorFirstName = Convert.ToString(values.GetValue(1 + i)),
                    DoctorLastName  = Convert.ToString(values.GetValue(2 + i)),
                    StartDateTime   = Convert.ToDateTime(values.GetValue(3 + i)),
                    Description     = values.GetValue(4 + i).ToString(),
                    Treatment       = values.GetValue(5 + i).ToString(),
                };
                var visitClosing = new VisitInfo()
                {
                    DoctorFirstName = Convert.ToString(values.GetValue(6 + i)),
                    DoctorLastName  = Convert.ToString(values.GetValue(7 + i)),
                    StartDateTime   = Convert.ToDateTime(values.GetValue(8 + i)),
                    Description     = values.GetValue(9 + i).ToString(),
                    Treatment       = values.GetValue(10 + i).ToString(),
                };
                var allergyInfo = new ClosedAllergyInfo()
                {
                    AllergyName = Convert.ToString(values.GetValue(i)),
                    OpeningClosingVisitsInfo = new Tuple <VisitInfo, VisitInfo>(visitOpening, visitClosing)
                };
                result.Add(allergyInfo);
            }
            return(result);
        }
Example #23
0
        private VisitInfo GetVisitInfo(string patientId, string visitId)
        {
            if (m_ListPatVisitInfos == null)
            {
                return(null);
            }
            PatVisitInfo patVisitInfo =
                m_ListPatVisitInfos.Find(item => item.PATIENT_ID == patientId && item.VISIT_ID == visitId);

            if (patVisitInfo == null)
            {
                return(null);
            }
            VisitInfo clientVisitInfo = new VisitInfo();

            clientVisitInfo.ID       = visitId;
            clientVisitInfo.InpID    = patVisitInfo.INP_NO;
            clientVisitInfo.Time     = patVisitInfo.VISIT_TIME;
            clientVisitInfo.WardCode = patVisitInfo.WARD_CODE;
            clientVisitInfo.WardName = patVisitInfo.WardName;
            clientVisitInfo.BedCode  = patVisitInfo.BED_CODE;
            clientVisitInfo.Type     = VisitType.IP;
            return(clientVisitInfo);
        }
Example #24
0
        private static void Main()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                string connectionString = ConfigurationUtility
                                          .GetString("connectionString")
                                          .ThrowIfNull("connectionString not set");

                int delay = ConfigurationUtility
                            .GetInt32("delay");

                DateTime threshold = DateTime.Today
                                     .AddMonths(-delay);

                using (IrbisConnection connection
                           = new IrbisConnection(connectionString))
                {
                    DatabaseInfo[] databases
                        = connection.ListDatabases();

                    DebtorManager manager
                        = new DebtorManager(connection)
                        {
                        ToDate = threshold
                        };
                    manager.BatchRead += (sender, args) =>
                    {
                        Console.Write(".");
                    };
                    DebtorInfo[] debtors = manager.GetDebtors
                                           (
                        connection.Search("RB=$")
                                           );
                    debtors = debtors.Where
                              (
                        debtor => !debtor.WorkPlace
                        .SafeContains(LibraryName)
                              )
                              .ToArray();
                    Console.WriteLine();
                    Console.WriteLine
                    (
                        "Debtors: {0}",
                        debtors.Length
                    );

                    VisitInfo[] allDebt = debtors.SelectMany
                                          (
                        debtor => debtor.Debt
                                          )
                                          .ToArray();
                    Console.WriteLine
                    (
                        "Books in debt: {0}",
                        allDebt.Length
                    );


                    Workbook workbook = new Workbook();
                    workbook.CreateNewDocument();
                    Worksheet worksheet = workbook.Worksheets[0];

                    int row = 0;

                    worksheet.Cells[row, 0].Value = "ФИО";
                    worksheet.Cells[row, 1].Value = "Билет";
                    worksheet.Cells[row, 2].Value = "Краткое описание";
                    worksheet.Cells[row, 3].Value = "Год";
                    worksheet.Cells[row, 4].Value = "Номер";
                    worksheet.Cells[row, 5].Value = "Цена";
                    worksheet.Cells[row, 6].Value = "Хранение";
                    worksheet.Cells[row, 7].Value = "Дата";
                    worksheet.Cells[row, 8].Value = "Отдел";

                    row++;

                    for (int i = 0; i < allDebt.Length; i++)
                    {
                        if (i % 100 == 0)
                        {
                            Console.Write(".");
                        }

                        VisitInfo debt = allDebt[i];

                        string description = debt.Description;
                        string inventory   = debt.Inventory;
                        string database    = debt.Database;
                        string year        = string.Empty;
                        string index       = debt.Index;
                        string price       = string.Empty;

                        if (!string.IsNullOrEmpty(index) &&
                            !string.IsNullOrEmpty(database))
                        {
                            if (databases.FirstOrDefault
                                (
                                    db => db.Name.SameString(database)
                                )
                                == null)
                            {
                                continue;
                            }

                            try
                            {
                                connection.Database = database;
                                MarcRecord record
                                    = connection.SearchReadOneRecord
                                      (
                                          "\"I={0}\"",
                                          index
                                      );
                                if (!ReferenceEquals(record, null))
                                {
                                    description = connection.FormatRecord
                                                  (
                                        FormatName,
                                        record.Mfn
                                                  );
                                    year  = GetYear(record);
                                    price = GetPrice(debt, record);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }

                        worksheet.Cells[row, 0].Value = debt.Reader.FullName;
                        worksheet.Cells[row, 1].Value = debt.Reader.Ticket;
                        worksheet.Cells[row, 2].Value = description;
                        worksheet.Cells[row, 3].Value = year;
                        worksheet.Cells[row, 4].Value = inventory;
                        worksheet.Cells[row, 5].Value = price;
                        worksheet.Cells[row, 6].Value = debt.Sigla;
                        worksheet.Cells[row, 7].Value = debt.DateExpectedString;
                        worksheet.Cells[row, 8].Value = debt.Department;

                        for (int j = 0; j <= 6; j++)
                        {
                            Cell cell = worksheet.Cells[row, j];
                            cell.Borders.SetAllBorders
                            (
                                Color.Black,
                                BorderLineStyle.Hair
                            );
                        }

                        row++;
                    }

                    workbook.SaveDocument(OutputFile);

                    Console.WriteLine("All done");

                    stopwatch.Stop();
                    TimeSpan elapsed = stopwatch.Elapsed;
                    Console.WriteLine("Elapsed: {0}", elapsed);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
 public string GetForumContent(string url)
 {
     return(CommonLib.Helper.JsonSerializeObject(VisitInfo.GetForumContent(url)));
 }
        public string ImportFeedBack(int accid, string content)
        {
            ManageUserModel uM = (ManageUserModel)Session["logUser"];

            return(VisitInfo.AddCustomCareFeedBack(uM.Name, content, accid, 1).ToString());
        }
Example #27
0
 /// <summary>
 /// Asynchronously adds <see cref="VisitInfo"/> entity to the database. Throws an exception if
 /// already there is the same entity in database or any problem with saving changes occurred.
 /// </summary>
 /// <param name="info">The info to be added. Cannot be null.</param>
 /// <returns>The added entity.</returns>
 /// <exception cref="ArgumentNullException">The value of <paramref name="info"/> to be added is null.</exception>
 /// <exception cref="InvalidOperationException">There is the same entity that one to be added in database.</exception>
 /// <exception cref="InternalDbServiceException">The table with <see cref="VisitInfo"/> entities does not exist or it is null or
 /// cannot save properly any changes made by add operation.</exception>
 public async Task <VisitInfo> AddAsync(VisitInfo info)
 {
     _logger.LogInformation($"Starting method '{nameof(AddAsync)}'.");
     // Call restricted add mode.
     return(await AddBaseAsync(info));
 }
Example #28
0
        public void ReachStateUsingPhrases(UnitState startState, UnitState finalState)
        {
            var backBfs = new BFS2(_field, _unit, _gameData);
            #if false// DEBUG
            DebugPrinter.WriteLine("Checking what is reachable back from: ({0}, {1}) rot {2}", finalState.Pivot.x, finalState.Pivot.y, finalState.Rotation);
            var reachableArr = backBfs.DoSimpleBfs(finalState, true).Select(st => st.UnitState).ToArray();

            foreach (var st in reachableArr)
                DebugPrinter.WriteLine("    reachable: ({0}, {1}) rot {2}", st.Pivot.x, st.Pivot.y, st.Rotation);
            var reachableStates = new HashSet<UnitState>(reachableArr);
            #else
            var reachableStates = new HashSet<UnitState>(backBfs.DoSimpleBfs(finalState, true, false).Select(st => st.UnitState));
            #endif

            _visited[startState] = new VisitInfo
            {
                MoveFuncIndex = -1,
                PrevState = null,
                AllPrevStates = new HashSet<UnitState>(),
            };

            UnitState curState = startState;

            PowerPhraseInfo prevPhrase = _gameData.PowerPhraseData.Phrases[0]; // empty phrase

            List<int> curReversedPath = null;

            while (curState != finalState)
            {
                UnitState stateAfterPhrase;
                PowerPhraseInfo appliedPhrase;
                List<int> reversedPathAfterPhrase;
                var prevState = curState;
                bool phraseApplied = ApplySomePhrase(curState, prevPhrase, reachableStates, finalState,
                    out stateAfterPhrase, out appliedPhrase, out reversedPathAfterPhrase);
                curState = stateAfterPhrase;

                if (phraseApplied)
                {
                    //movesStr += appliedPhrase.Phrase;
                    curReversedPath = reversedPathAfterPhrase;
                    prevPhrase = appliedPhrase;
                    continue;
                }

                prevPhrase = _gameData.PowerPhraseData.Phrases[0];

                // Do BFS step
                if (curReversedPath == null)
                {
                    bool reachable = _IsReachable(curState, finalState, out curReversedPath);
                    Debug.Assert(reachable);
                }

                int move = curReversedPath[curReversedPath.Count - 1];
                var state = curState;
                curState = UnitState.MoveFuncs[move](curState);
                curState.Normalize(_unit);
                curReversedPath.RemoveAt(curReversedPath.Count - 1);

                _visited[curState] = new VisitInfo
                {
                    MoveFuncIndex = move,
                    PrevState = state,
                    MoveChar = ANY_CHAR,
                };
            }
        }
Example #29
0
        /// <summary>
        /// Asynchronously updates <see cref="VisitInfo"/> entity. If <paramref name="isRestrict"/> set to false then no restrictions will be used and update allow entirely entity updating.
        /// Otherwise the restricted mode will be using. It will ignore updating some read-only properties.
        /// </summary>
        /// <param name="info"><see cref="VisitInfo"/> to be updated.</param>
        /// <param name="isRestrict">If set to false then no restrictions will be used and update allow entirely entity updating. If set to true then the restricted mode will be used.
        /// It will ignore some read-only properties changes.</param>
        /// <returns>Updated <see cref="Customer"/> entity.</returns>
        private async Task <VisitInfo> UpdateBaseAsync(VisitInfo info, bool isRestrict = false)
        {
            _logger.LogDebug($"Starting method '{nameof(UpdateBaseAsync)}'.");

            _ = info ?? throw new ArgumentNullException(nameof(info), $"Argument '{nameof(info)}' cannot be null.");

            if (string.IsNullOrEmpty(info.Id))
            {
                throw new ArgumentException($"Argument '{nameof(info.Id)}' cannot be null or empty.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.Info ?? throw new InternalDbServiceException($"Table of type '{typeof(VisitInfo).Name}' is null.");

            try
            {
                if (_context.Info.Count() == 0)
                {
                    throw new InvalidOperationException($"Cannot found element with id '{info.Id}' for update. Resource {_context.Info.GetType().Name} does not contain any element.");
                }

                if (await _context.Info.ContainsAsync(info) == false)
                {
                    throw new InvalidOperationException($"Cannot found element with id '{info.Id}' for update. Any element does not match to the one to be updated.");
                }

                _logger.LogDebug($"Starting update customer with id '{info.Id}'.");

                VisitInfo updatedInfo = null;
                info.UpdatedAt = DateTime.UtcNow;

                if (isRestrict)
                {
                    // Restricted update mode that ignores all changes in read-only properties like Id, CreatedAt, UpdatedAt, ConcurrencyToken.
                    var originalInfo = await _context.Info.Include(x => x.OpeningHours).SingleAsync(x => x.Id.Equals(info.Id));

                    updatedInfo = BasicRestrictedUpdate(originalInfo, info) as VisitInfo;
                }
                else
                {
                    // Normal update mode without any additional restrictions.
                    updatedInfo = _context.Info.Update(info).Entity;
                }

                await _context.TrySaveChangesAsync();

                _logger.LogDebug($"Update data succeeded.");
                _logger.LogDebug($"Finished method '{nameof(UpdateBaseAsync)}'.");
                return(updatedInfo);
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - Cannot found element for update. See exception for more details. Operation failed.");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} - {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when updating general sightseing info with id '{info.Id}'. See the inner exception for more details.", ex);
                throw internalException;
            }
        }
Example #30
0
        /// <summary>
        /// Asynchronously adds <see cref="VisitInfo"/> entity. If <paramref name="isRestrict"/> set to false then no restrictions will be used. If set to true then the restricted mode will be used.
        /// It will check if in database is entity with the same Description, OpeningHour, MaxAllowedGroupSize and MaxChildAge values.
        /// </summary>
        /// <param name="info"><see cref="VisitInfo"/> to be added.</param>
        /// <param name="isRestrict">If set to false then no restrictions will be used and update allow entirely entity updating. If set to true then the restricted mode will be used.
        /// It will check if in database is entity with the same Description, OpeningHour, MaxAllowedGroupSize and MaxChildAge values. </param>
        /// <returns>Added <see cref="VisitInfo"/> entity.</returns>
        private async Task <VisitInfo> AddBaseAsync(VisitInfo info, bool isRestrict = false)
        {
            _logger.LogDebug($"Starting method '{nameof(AddBaseAsync)}'.");

            if (info is null)
            {
                throw new ArgumentNullException($"Argument '{nameof(info)}' cannot be null.");
            }

            await EnsureDatabaseCreatedAsync();

            _ = _context?.Info ?? throw new InternalDbServiceException($"Table of type '{typeof(VisitInfo).Name}' is null.");

            try
            {
                if (isRestrict)
                {
                    // Restricted add mode that use custom equality comparer. Discounts are equal if they have the same Description, DiscountValueInPercentage, GroupSizeForDiscount and Type.

                    // Check if exist in db disount with the same properties as adding.
                    if (await IsEntityAlreadyExistsAsync(info))
                    {
                        throw new InvalidOperationException($"There is already the same element in the database as the one to be added. " +
                                                            $"The value of '{nameof(info.Description)}', '{nameof(info.MaxChildAge)}', '{nameof(info.OpeningHours)}'" +
                                                            $"'{nameof(info.MaxAllowedGroupSize)}' are not unique.");
                    }
                }
                else
                {
                    // Normal add mode without any additional restrictions.
                    if (_context.Info.Contains(info))
                    {
                        throw new InvalidOperationException($"There is already the same element in the database as the one to be added. Id of this element: '{info.Id}'.");
                    }
                }

                _logger.LogDebug($"Starting add general sightseeing info with id '{info.Id}'.");
                var addedInfo = _context.Info.Add(info).Entity;
                await _context.TrySaveChangesAsync();

                _logger.LogDebug("Add data succeeded.");
                _logger.LogInformation($"Finished method '{nameof(AddAsync)}'.");
                return(addedInfo);
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError($"{ex.GetType().Name} - Changes made by add operations cannot be saved properly. See the inner exception for more details. Operation failed.", ex);
                var internalException = new InternalDbServiceException("Changes made by add operations cannot be saved properly. See the inner exception for more details.", ex);
                throw internalException;
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError($"{ex.GetType().Name} - There is already the same element in the database as the one to be added. Id of this element: '{info.Id}'.", ex);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"{ex.GetType().Name} {ex.Message}");
                var internalException = new InternalDbServiceException($"Encountered problem when adding disount with id '{info.Id}' to database. See the inner exception for more details.", ex);
                throw internalException;
            }
        }
Example #31
0
 /// <summary>
 /// Asynchronously updates <see cref="SightseeingTariff"/> entity ignoring read-only properties like Id, CreatedAt, UpdatedAt, ConcurrencyToken.
 /// Throws an exception if cannot found entity or any problem with updating occurred.
 /// </summary>
 /// <param name="tariff">The tariff to be updated. Cannot be null or has Id property set to null or empty string.</param>
 /// <returns>Updated entity.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="tariff"/> is null.</exception>
 /// <exception cref="ArgumentException"><paramref name="tariff"/> has Id property set to null or empty string.</exception>
 /// <exception cref="InvalidOperationException">Cannot found entity to be updated.</exception>
 /// <exception cref="InternalDbServiceException">The resource does not exist or has a null value or any
 /// other problems with retrieving data from database occurred.</exception>
 public async Task <VisitInfo> RestrictedUpdateAsync(VisitInfo info)
 {
     _logger.LogInformation($"Starting method '{nameof(RestrictedUpdateAsync)}'.");
     // Call restricted update mode.
     return(await UpdateBaseAsync(info, true));
 }
Example #32
0
 /// <summary>
 /// Asynchronously updates <see cref="VisitInfo"/> entity.
 /// Throws an exception if cannot found entity or any problem with updating occurred.
 /// </summary>
 /// <param name="info">The sightseeing info to be updated. Cannot be null or has Id property set to null or empty string.</param>
 /// <returns>Updated entity.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="info"/> is null.</exception>
 /// <exception cref="ArgumentException"><paramref name="info"/> has Id property set to null or empty string.</exception>
 /// <exception cref="InvalidOperationException">Cannot found entity to be updated.</exception>
 /// <exception cref="InternalDbServiceException">The resource does not exist or has a null value or any
 /// other problems with retrieving data from database occurred.</exception>
 public async Task <VisitInfo> UpdateAsync(VisitInfo info)
 {
     _logger.LogInformation($"Starting method '{nameof(UpdateAsync)}'.");
     // Call normal update mode.
     return(await UpdateBaseAsync(info));
 }
Example #33
0
        private bool TryAddVisitedState(UnitState newState, UnitState state, int funcIndex, out Cell[] cells, out bool isBlockingMove, char moveChar = ANY_CHAR)
        {
            cells = null;
            isBlockingMove = false;
            if (_visited.ContainsKey(newState))
                return false;

            cells = newState.GetCells(_unit);

            if (!cells.All(_field.IsValidCell))
            {
                isBlockingMove = true;
                return false;
            }

            //if (_IsDuplicateState(state, newState))
            //    return false;

            var vi = new VisitInfo
                {
                    MoveFuncIndex = funcIndex,
                    PrevState = state,
                    MoveChar = moveChar,
                    //AllPrevStates = _visited[state].AllPrevStates
                    //   AllPrevStates = new HashSet<UnitState>(_visited[state].AllPrevStates)
                };
              //  vi.AllPrevStates.Add(new UnitState(state.Pivot, _unit.GetCanonicalRotation(state.Rotation)));

            _visited[newState] = vi;
            return true;
        }
Example #34
0
 private bool IsSightseeingDurationSet(VisitInfo info)
 {
     return(info.SightseeingDuration > 0.0f);
 }