/// <summary>
        /// Bing Spell Check API
        /// </summary>
        /// <param name="spellCheckParameters"></param>
        /// <returns></returns>
        public async Task<ResultDto<SpellCheckApiFeeds>> SpellCheckApiRequestAsync(
            SpellCheckParameters spellCheckParameters)
        {
            var resultDto = new ResultDto<SpellCheckApiFeeds>();
            try
            {
                var client = new HttpClient();
                // Request headers
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, spellCheckParameters.subscriptionKey);

                // Request parameters
                var queryString =
                    $"text={spellCheckParameters.content}&mode={spellCheckParameters.mode}&mkt={spellCheckParameters.mkt}";
                var url = Constants.SpellCheckApi + queryString;

                var jsonResult = await client.GetStringAsync(url);
                var feed = JsonConvert.DeserializeObject<SpellCheckApiFeeds>(jsonResult);
                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.message;
                resultDto.StatusCode = feed.statusCode.ToString();
                resultDto.Success = string.IsNullOrEmpty(feed.message);
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"Error: {ex}");
            }
            return resultDto;
        }
        /// <summary>
        /// Interprets a natural language user query string
        /// </summary>
        /// <param name="academicParameters"></param>
        /// <returns></returns>
        public async Task<ResultDto<InterpretApiFeeds>> AcademicInterpretApiRequestAsync(
            AcademicParameters academicParameters)
        {
            var resultDto = new ResultDto<InterpretApiFeeds>();
            try
            {
                var client = new HttpClient();

                //request header
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, academicParameters.SubscriptionKey);
                var queryString =
                    $"query={academicParameters.Query}&offset={academicParameters.Offset}&count={academicParameters.Count}&model={academicParameters.Model}&complete={academicParameters.Complete}&timeout={academicParameters.Timeout}";
                var url = Constants.AcademicInterpretApi + queryString;

                var jsonResult = await client.GetStringAsync(url);
                var feed = JsonConvert.DeserializeObject<InterpretApiFeeds>(jsonResult);

                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.error?.message;
                resultDto.StatusCode = feed.error?.code;
                resultDto.Success = feed.error == null;
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"{ex}");
            }
            return resultDto;
        }
Exemple #3
0
        public IActionResult Result(string id)
        {
            var entry = _repository.Get(id);
            var link = entry as LinkEntry;

            if (link != null)
            {
                var url = $"http://307.ch/{id}";
                var escaped = Uri.EscapeDataString(url);
                var qr = $"https://api.qrserver.com/v1/create-qr-code/?data={escaped}&size=200x200";

                var dto = new ResultDto
                {
                    Id = link.Id,
                    Url = url,
                    Link = link.Link,
                    AdminCode = link.AdminCode,
                    Qr = qr
                };
                return View("Result", dto);
            }

            Context.Response.StatusCode = 404;
            return View("404");
        }
Exemple #4
0
        /// <summary>
        /// 分页获取Role
        /// </summary>
        /// <param name="queryBase">QueryBase</param>
        /// <param name="exp">过滤条件</param>
        /// <param name="orderBy">排序条件</param>
        /// <param name="orderDir">排序类型:desc(默认)/asc</param>
        /// <returns></returns>
        public ResultDto <RoleDto> GetWithPages(QueryBase queryBase, Expression <Func <RoleDto, bool> > exp, string orderBy, string orderDir = "desc")
        {
            using (var scope = _dbScopeFactory.CreateReadOnly())
            {
                var db    = GetDb(scope);
                var dbSet = GetDbSet(db);
                var where = exp.Cast <RoleDto, RoleEntity, bool>();
                //var order = orderExp.Cast<RoleDto, RoleEntity, OrderKeyType>();
                var query = GetQuery(dbSet, where, orderBy, orderDir);

                var query_count = query.FutureCount();
                var query_list  = query.Skip(queryBase.Start).Take(queryBase.Length).Future();
                var list        = query_list.ToList();

                var dto = new ResultDto <RoleDto>
                {
                    recordsTotal = query_count.Value,
                    data         = Mapper.Map <List <RoleEntity>, List <RoleDto> >(list)
                };
                return(dto);
            }
        }
Exemple #5
0
        public ResultDto <long> AddEssay(EssayEntity essayEntity, EssayContentEntity essayConentEntity, IEnumerable <TagEntity> tagList)
        {
            var resultDto = new ResultDto <long>();

            resultDto.Result = _defaultRepository.TransExecute((conn, trans) =>
            {
                var insertAndGetIdResultDto = conn.CreateAndGetId <EssayEntity, long>(essayEntity, trans);
                if (!insertAndGetIdResultDto.Result)
                {
                    return(false);
                }

                essayConentEntity.EssayId = insertAndGetIdResultDto.Data;
                if (conn.Insert <EssayContentEntity>(essayConentEntity, trans) <= 0)
                {
                    return(false);
                }

                resultDto.Data = insertAndGetIdResultDto.Data;
                if (tagList != null && tagList.Any())
                {
                    tagList = tagList.Select(tag =>
                    {
                        tag.EssayId = insertAndGetIdResultDto.Data;
                        return(tag);
                    });

                    var insertListResultDto = conn.CreateList(tagList, trans);
                    if (!insertListResultDto.Result)
                    {
                        return(false);
                    }
                }

                return(true);
            });

            return(resultDto);
        }
        public ActionResult CreateContraEntryDeposited(FormCollection form)
        {
            var contraEntryDepositedDto = ReadFormDataDeposited(form);
            var resultDto = new ResultDto();

            if (contraEntryDepositedDto.AccountMasterID == 0)
            {
                resultDto = _ContraEntryService.FederationInsertContraEntryDeposit(contraEntryDepositedDto);
            }
            else
            {
                resultDto = _ContraEntryService.FederationUpdateContraEntryDeposited(contraEntryDepositedDto);
            }

            if (resultDto.ObjectId > 0)
            {
                resultDto.ObjectCode = contraEntryDepositedDto.VoucherNumber;
            }
            ViewBag.Result = resultDto;
            BankMasterViewDto        objBank     = new BankMasterViewDto();
            List <BankMasterViewDto> lstAllBanks = _ContraEntryService.GetAllOrganizationBanks();
            SelectList lstBanks = new SelectList(lstAllBanks, "AHID", "AccountNumber", objBank.BankEntryID);

            ViewBag.AllBanks = lstBanks;

            AccountHeadDto objAccountHead  = _accountheadService.GetCashInHandAccount(true);
            int            ahId            = objAccountHead.AHID;
            AccountHeadDto closeingBalance = _accountheadService.GetAccountHeadViewBalanceSummary(ahId, true);

            objAccountHead.ClosingBalance = closeingBalance.ClosingBalance;
            ViewBag.CashInHandDetails     = objAccountHead;
            contraEntryDepositedDto       = _ContraEntryService.FederationContraEntryDepositedGetByAccountMasterId(resultDto.ObjectId);

            var totalCrAmmount = contraEntryDepositedDto.contraEntryDepositedTransactions[contraEntryDepositedDto.contraEntryDepositedTransactions.Count() - 1].CrAmount;

            ViewBag.TotalCrAmmount = totalCrAmmount;

            return(View(contraEntryDepositedDto));
        }
Exemple #7
0
        /// <summary>
        /// 分页获取EmailReceiver
        /// </summary>
        /// <param name="queryBase">QueryBase</param>
        /// <param name="exp">过滤条件</param>
        /// <param name="orderExp">排序条件</param>
        /// <param name="isDesc">是否是降序排列</param>
        /// <returns></returns>
        public ResultDto <EmailReceiverDto> GetWithPages <OrderKeyType>(QueryBase queryBase, Expression <Func <EmailReceiverDto, bool> > exp, Expression <Func <EmailReceiverDto, OrderKeyType> > orderExp, bool isDesc = true)
        {
            using (var scope = _dbScopeFactory.CreateReadOnly())
            {
                var db    = GetDb(scope);
                var dbSet = GetDbSet(db);
                var where = exp.Cast <EmailReceiverDto, EmailReceiverEntity, bool>();
                var order = orderExp.Cast <EmailReceiverDto, EmailReceiverEntity, OrderKeyType>();
                var query = GetQuery(dbSet, where, order, isDesc);

                var query_count = query.FutureCount();
                var query_list  = query.Skip(queryBase.Start).Take(queryBase.Length).Future();
                var list        = query_list.ToList();

                var dto = new ResultDto <EmailReceiverDto>
                {
                    recordsTotal = query_count.Value,
                    data         = Mapper.Map <List <EmailReceiverEntity>, List <EmailReceiverDto> >(list)
                };
                return(dto);
            }
        }
Exemple #8
0
        public JsonResult GetTreeList(string layout = "", string parentcate = "")
        {
            ResultDto <List <CategoryTree> > result = new ResultDto <List <CategoryTree> >();
            var lists = GetCategoryTree(tenant.Id);

            if (!string.IsNullOrEmpty(layout))
            {
                lists = lists.Where(o => o.Layout == layout).ToList();
            }
            if (!string.IsNullOrEmpty(parentcate))
            {
                var parent = lists.Where(o => o.CategoryName == parentcate || o.CategoryIndex == parentcate).FirstOrDefault();
                if (parent != null)
                {
                    lists = lists.Where(o => o.ParentId == parent.Id).ToList();
                }
            }
            result.datas = lists;
            result.code  = 100;
            result.total = lists.Count;
            return(Json(result));
        }
        public ResultDto Put(int id, [FromBody] CreateUpdateBaseTypeDto updateBaseType)
        {
            BaseType baseType = _baseTypeRepository.Select.Where(r => r.Id == id).ToOne();

            if (baseType == null)
            {
                throw new LinCmsException("该数据不存在");
            }

            bool exist = _baseTypeRepository.Select.Any(r => r.TypeCode == updateBaseType.TypeCode && r.Id != id);

            if (exist)
            {
                throw new LinCmsException($"基础类别-编码[{updateBaseType.TypeCode}]已存在");
            }

            _mapper.Map(updateBaseType, baseType);

            _baseTypeRepository.Update(baseType);

            return(ResultDto.Success("更新类别成功"));
        }
        public ResultDto <object> RunImmediately(Guid id)
        {
            var result = new ResultDto <object>()
            {
                success = false,
            };

            if (id == Guid.Empty)
            {
                result.success = false;
                result.message = "参数错误";
                return(result);
            }

            var trigger = _Context.HangfireTaskTrigger.FirstOrDefault(p => p.Id == id);

            if (trigger == null)
            {
                result.success = false;
                result.message = "触发器不存在";
                return(result);
            }
            else if (trigger.Status == 1)
            {
                RecurringJob.Trigger(id.ToString());   //立即触发
                trigger.Status       = 1;
                trigger.LastModified = DateTime.Now;
                _Context.SaveChanges();
                result.success = true;
                result.message = "触发成功";
                return(result);
            }
            else
            {
                result.success = false;
                result.message = "当前状态不可触发,必须先恢复作业才可触发";
                return(result);
            }
        }
        public ResultDto <object> AddTaskGroup(string groupName, string description)
        {
            ResultDto <object> result = new ResultDto <object>()
            {
                data    = null,
                success = false,
                message = "",
            };

            if (string.IsNullOrEmpty(groupName))
            {
                result.message = "不能为空";
                result.success = false;
                return(result);
            }
            var group = _Context.HangfireTaskGroup.FirstOrDefault(p => p.GroupName == groupName);

            if (group != null)
            {
                result.success = false;
                result.message = "该组已经存在";
                return(result);
            }
            else
            {
                _Context.HangfireTaskGroup.Add(new HangfireTaskGroup()
                {
                    Id           = Guid.NewGuid(),
                    GroupName    = groupName,
                    Description  = description,
                    Created      = DateTime.Now,
                    LastModified = DateTime.Now,
                });
                _Context.SaveChanges();
                result.success = true;
                result.message = "success";
                return(result);
            }
        }
Exemple #12
0
        public ResultDto Put(Guid id, [FromBody] CreateUpdateTagDto updateTag)
        {
            Tag tag = _tagRepository.Select.Where(r => r.Id == id).ToOne();

            if (tag == null)
            {
                throw new LinCmsException("该数据不存在");
            }

            bool exist = _tagRepository.Select.Any(r => r.TagName == updateTag.TagName && r.Id != id);

            if (exist)
            {
                throw new LinCmsException($"标签[{updateTag.TagName}]已存在");
            }

            _mapper.Map(updateTag, tag);

            _tagRepository.Update(tag);

            return(ResultDto.Success("更新标签成功"));
        }
Exemple #13
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="rq"></param>
        /// <returns></returns>
        public ResultDto <UserLoginRP> Login(UserLoginRQ rq)
        {
            var result = new ResultDto <UserLoginRP>(ResponseCode.sys_fail, "登录失败(-1)");
            var pwd    = AESEncrypt.Encrypt(rq.Password, AESEncrypt.pwdKey);
            var r      = repository.wm_user.Where(q => q.Mobile == rq.Name && q.Pwd == pwd)
                         .Select(q => new UserLoginRP
            {
                uid      = q.UID,
                Email    = q.Email,
                Mobile   = q.Mobile,
                Name     = q.Name,
                NickName = q.Nickname
            }).First();

            if (r == null)
            {
                result.Msg = "账户或密码错误!";
                return(result);
            }

            return(Result(r));
        }
Exemple #14
0
        public ResultDto Add(RoleDto dto)
        {
            var result = new ResultDto();

            try
            {
                dto.SetDefaultValue();
                var data = Mapper.Map <Role>(dto);
                _liveShowDB.Add(data);
                var flag = _liveShowDB.SaveChanges();
                if (flag > 0)
                {
                    result.ActionResult = true;
                    result.Message      = "Success";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Exemple #15
0
        public async Task <ResultDto <CommentTreeDto> > GetSingleDataAsync(int id)
        {
            var result      = new ResultDto <CommentTreeDto>();
            var treeDtoList = new List <CommentTreeDto>();
            var dataList    = await _testDB.Comment.AsNoTracking().Where(x => x.IsDelete == false).ToListAsync();

            if (dataList.Where(x => x.Id == id).Any())
            {
                var dtoList = Mapper.Map <List <CommentDto> >(dataList);
                treeDtoList = GetCommentTrees(dtoList, id);
                var data = dataList.Where(x => x.Id == id).FirstOrDefault();
                if (null != data)
                {
                    var treeDto = Mapper.Map <CommentTreeDto>(data);
                    treeDtoList.Insert(0, treeDto);
                }
                result.ActionResult = true;
                result.Message      = "Success";
                result.List         = treeDtoList;
            }
            return(result);
        }
Exemple #16
0
        /// <summary>
        /// 获取我尚未拥有的角色
        /// </summary>
        /// <param name="query"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResultDto <RoleDto> GetNotMyRoles(QueryBase query, int userId)
        {
            var roleIds = repository.GetById(userId).Roles.Select(x => x.Id).Distinct();
            Expression <Func <RoleDto, bool> > exp = item => (!item.IsDeleted && !roleIds.Contains(item.Id));

            if (!query.SearchKey.IsBlank())
            {
                exp = exp.And(item => item.Name.Contains(query.SearchKey));
            }

            var role_db_set = role_service.Query(exp, x => x.CreateDateTime, true);

            var list = role_db_set.Skip(query.Start).Take(query.Length).ToList();

            var dto = new ResultDto <RoleDto>
            {
                recordsTotal = role_db_set.Count(),
                data         = list
            };

            return(dto);
        }
        public async Task <ResultDto <MessageCategoryDto> > GetSingleDataAsync(int id)
        {
            var result = new ResultDto <MessageCategoryDto>();

            try
            {
                var data = await _liveShowDB.MessageCategory.AsNoTracking().Where(x => !x.IsDeleted && x.Id == id).FirstOrDefaultAsync();

                if (null != data)
                {
                    var dto = Mapper.Map <MessageCategoryDto>(data);
                    result.ActionResult = true;
                    result.Message      = "Success";
                    result.Data         = dto;
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Exemple #18
0
        public ResultDto AddSingle(ArticleTypeDto dto)
        {
            var result = new ResultDto();

            dto.CreateTime = DateTime.Now;
            try
            {
                var data = _mapper.Map <ArticleType>(dto);
                _testDB.Add(data);
                var flag = _testDB.SaveChanges();
                if (flag > 0)
                {
                    result.ActionResult = true;
                    result.Message      = "Success";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return(result);
        }
Exemple #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <ResultDto <string> > Handle(UserBtnPermissionQuery request, CancellationToken cancellationToken)
        {
            var sql = @"SELECT SystemMenu.`Code` 
                        FROM SystemUser
                        join SystemRole on SystemUser.RoleId=SystemRole.Id
                        join SystemRoleMenu on SystemRole.Id=SystemRoleMenu.RoleId
                        join SystemMenu on SystemRoleMenu.MenuId=SystemMenu.Id
                        where SystemUser.Id=@UserId and SystemMenu.MenuType=3";

            var strLst = await _dapper.QueryAsync <string>(sql, new { UserId = request.UserId });

            ResultDto <string> result = new ResultDto <string>()
            {
                State = 1,
            };

            strLst.ToList().ForEach(t =>
            {
                result.Data += t + ",";
            });
            return(result);
        }
        public JsonResult GetData()
        {
            ResultDto <dynamic> res = new ResultDto <dynamic>();

            List <dynamic> list = new List <dynamic>(10);

            for (int i = 0; i < 10; i++)
            {
                list.Add(new
                {
                    name     = "AA" + i,
                    position = "局长" + i,
                    office   = "Office" + i,
                    salary   = i * 987
                });
            }

            res.data         = list;
            res.length       = 10;
            res.recordsTotal = 10;
            return(Json(res, JsonRequestBehavior.AllowGet));
        }
        public ActionResult CreateLoanApplication(LoanApplicationModel loanapplicationmodel)
        {
            List<GroupLookupDto> lstGroupDto = _groupService.Lookup();
            SelectList lstgroup = new SelectList(lstGroupDto, "GroupID", "GroupCode");
            ViewBag.GroupNames = lstgroup;

            List<LoanPurposeLookupDto> lstLoanpurposeDto = _loanpurposeService.Lookup();
            SelectList lstloanpurpose = new SelectList(lstLoanpurposeDto, "LoanPurposeID", "Purpose");
            ViewBag.LoanPurposeName = lstloanpurpose;

            var resultDto = new ResultDto();
            var loanapplicationDto = Mapper.Map<LoanApplicationModel, LoanApplicationDto>(loanapplicationmodel);
            loanapplicationDto.UserID = UserInfo.UserID;
            if (loanapplicationDto.LoanMasterId == 0)
                resultDto = _loanapplicationService.Insert(loanapplicationDto);
            else
                resultDto = _loanapplicationService.Update(loanapplicationDto);

            ViewBag.Result = resultDto;

            return View(loanapplicationmodel);
        }
        public ResultDto Post([FromBody] CreateCommentDto createCommentDto)
        {
            Comment comment = _mapper.Map <Comment>(createCommentDto);

            _commentAuditBaseRepository.Insert(comment);

            if (createCommentDto.RootCommentId.HasValue)
            {
                _commentAuditBaseRepository.UpdateDiy.Set(r => r.ChildsCount + 1).Where(r => r.Id == createCommentDto.RootCommentId).ExecuteAffrows();
            }

            switch (createCommentDto.SubjectType)
            {
            case 1:
                _articleRepository.UpdateDiy.Set(r => r.CommentQuantity + 1)
                .Where(r => r.Id == createCommentDto.SubjectId).ExecuteAffrows();
                break;
            }


            return(ResultDto.Success("评论成功"));
        }
Exemple #23
0
        public ResultDto duplicateValues(int[] numbers)
        {
            ResultDto resultDto = new ResultDto();
            long      steps     = 0;

            for (int i = 0; i < numbers.Length; i++)
            {
                for (int j = 0; j < numbers.Length; j++)
                {
                    steps++;
                    if (i != j && numbers[i] == numbers[j])
                    {
                        resultDto.setHasDuplicates(true);
                        resultDto.setSteps(steps);
                        return(resultDto);
                    }
                }
            }
            resultDto.setHasDuplicates(false);
            resultDto.setSteps(steps);
            return(resultDto);
        }
Exemple #24
0
        private async Task <ResultDto> EnsureIsValidAsync(SignUpToCourseDto signupCourseParameter)
        {
            var result = new ResultDto();

            if (signupCourseParameter.Student == null)
            {
                result.Messages.Add("Student not informed.");
            }
            else
            {
                var student = await this.dbContext.Students
                              .Where(s => s.Email == signupCourseParameter.Student.Email)
                              .SingleOrDefaultAsync();

                if (student == null)
                {
                    result.Messages.Add("There's no student with this email.");
                }
                else
                {
                    signupCourseParameter.Student.Id = student.Id;

                    var course = await this.dbContext.Courses
                                 .Where(c => c.Id == signupCourseParameter.CourseId)
                                 .SingleOrDefaultAsync();

                    if (course == null)
                    {
                        result.Messages.Add("The course doesn't exists.");
                    }
                    else
                    {
                        result.Success = true;
                    }
                }
            }

            return(result);
        }
Exemple #25
0
        public async Task <IActionResult> Authenticate([FromBody] LoginDto loginDto)
        {
            var result = new ResultDto <UsuarioAutenticadoDto>();

            try
            {
                if (loginDto == null)
                {
                    throw new AwayException("Datos inválidos.");
                }

                var usuarioDto = await _usuarioService.GetByCredentialsAsync(loginDto.User, loginDto.Pass);

                if ((usuarioDto == null) || (usuarioDto.Id <= 0))
                {
                    throw new AwayException("Usuario/Password inválidos.");
                }

                result.Data = new UsuarioAutenticadoDto()
                {
                    Id       = usuarioDto.Id,
                    Nombre   = usuarioDto.Nombre,
                    Apellido = usuarioDto.Apellido,
                    Rol      = usuarioDto.Rol,
                    Token    = AwayTokenGenerator.GenerateTokenJwt(_appSettings, _jwtIssuerOptions, usuarioDto)
                };
            }
            catch (AwayException ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.Error(KOriginApp, ex.Message, ex);
                result.AddError("Ocurrió un error al intentar logearse en el sistema.");
            }
            return(Ok(result));
        }
Exemple #26
0
        private ResultDto insertupdateGeneralreceipt(GeneralReceiptDto generalreceiptDto)
        {
            ResultDto resultDto = new ResultDto();

            generalreceiptDto.IsGroup = Convert.ToBoolean(0);
            string objectName = "General Receipt";

            try
            {
                string          amountxml            = CommonMethods.SerializeListDto <List <AddAmountDto> >(generalreceiptDto.Addamount);
                ObjectParameter paramAccountMasterID = new ObjectParameter("AccountMasterID", generalreceiptDto.AccountMasterID);
                ObjectParameter paramVoucherNumber   = new ObjectParameter("VoucherNumber", string.Empty);
                _dbContext.uspGeneralReceiptInsertUpdate(paramAccountMasterID, generalreceiptDto.TransactionDate, paramVoucherNumber, generalreceiptDto.VoucherRefNumber, generalreceiptDto.PartyName, generalreceiptDto.EmployeeID, generalreceiptDto.AHID,
                                                         generalreceiptDto.SubHeadID, generalreceiptDto.TransactionType, generalreceiptDto.Amount, generalreceiptDto.TransactionMode, generalreceiptDto.ChequeNumber, generalreceiptDto.ChequeDate,
                                                         generalreceiptDto.BankAccount, generalreceiptDto.Narration, generalreceiptDto.IsGroup, generalreceiptDto.GroupID, generalreceiptDto.UserID, generalreceiptDto.Type, amountxml);
                long masterObjectId = Convert.ToInt64(paramAccountMasterID.Value);
                resultDto.ObjectId   = Convert.ToInt32(masterObjectId);
                resultDto.ObjectCode = string.IsNullOrEmpty((string)paramVoucherNumber.Value) ? generalreceiptDto.VoucherNumber : (string)paramVoucherNumber.Value;

                if (resultDto.ObjectId > 0)
                {
                    resultDto.Message = string.Format("{0} details saved successfully with code : {1}", objectName, resultDto.ObjectCode);
                }
                else if (resultDto.ObjectId == -1)
                {
                    resultDto.Message = string.Format("Error occured while generating {0} code", objectName);
                }
                else
                {
                    resultDto.Message = string.Format("Error occured while saving {0} details", objectName);
                }
            }
            catch (Exception)
            {
                resultDto.Message  = string.Format("Service layer error occured while saving the {0} details", objectName);
                resultDto.ObjectId = -98;
            }
            return(resultDto);
        }
        public ActionResult MoveSubGroupOrAccountHead(AccountHeadModel accountHeadModel)
        {
            bool      isFederation = string.IsNullOrEmpty(Request.Form.Get("isFederation")) ? true : Convert.ToBoolean(Request.Form.Get("isFederation"));
            ResultDto result       = new ResultDto();

            accountHeadModel.UserID     = 1;
            accountHeadModel.StatusID   = 1;
            accountHeadModel.ParentAHID = accountHeadModel.ParentMoveAHID;
            AccountHeadDto accountHeadDto = AutoMapperEntityConfiguration.Cast <AccountHeadDto>(accountHeadModel);

            result = _accountHeadService.MoveAccountHead(accountHeadDto);
            ViewBag.IsFederation   = isFederation;
            TempData["SuccessMsg"] = result;
            if (isFederation)
            {
                return(RedirectToAction("AccountTree"));
            }
            else
            {
                return(RedirectToAction("GroupAccountTree"));
            }
        }
Exemple #28
0
        /// <summary>
        /// 检查文件是否符合规范
        /// </summary>
        /// <returns></returns>
        private static ResultDto Check()
        {
            var resultDto = new ResultDto();

            //第一行第三列是年级
            if (GetCellValue(1, 3) != "年级")
            {
                resultDto.ErrMsg += "表格第 1 行第 3 列错误,该列应为[年级]列;";
            }
            //第一行第五列是教师姓名
            if (GetCellValue(1, 5) != "教师姓名")
            {
                resultDto.ErrMsg += "表格第 1 行第 5 列错误,该列应为[教师姓名]列;";
            }
            //第一行第六列是科目
            if (GetCellValue(1, 7) != "科目")
            {
                resultDto.ErrMsg += "表格第 1 行第 6 列错误,该列应为[科目]列;";
            }
            resultDto.IsSuccess = string.IsNullOrEmpty(resultDto.ErrMsg);
            return(resultDto);
        }
        public async Task <ResultDto <GetSoundsByCategoryDto> > GetSoundNamesByCategory(string category)
        {
            var result = new ResultDto <GetSoundsByCategoryDto>();

            if (!isTypeValid(category))
            {
                result.Errors.Add("Rodzaj trybu jest niezgodny ze zdefiniowanymi typami");

                return(result);
            }

            var soundsByType = await Task.Run(() => _soundRepository.GetAllBy(x => x.Category == category).ToList());

            if (soundsByType.Count < MinimumNumberOfSoundsAndChords)
            {
                result.Errors.Add("Ta gra nie może być rozpoczęta ponieważ system nie posiada wystarczającej ilości próbek dźwiękowych dla tej kategorii");
                return(result);
            }

            Random rnd = new Random();

            var soundsNames = new List <string>();

            int numberOfFilesToTake = SoundTypes.Single(x => x.SoundType == category).NumberOfFiles;

            for (int i = 0; i < numberOfFilesToTake; i++)
            {
                int randomizedIndex = rnd.Next(0, soundsByType.Count());
                var name            = soundsByType.ElementAt(randomizedIndex).FullName;
                soundsNames.Add(soundsByType.ElementAt(randomizedIndex).FullName);
            }

            result.SuccessResult = new GetSoundsByCategoryDto()
            {
                SoundNames = soundsNames
            };

            return(result);
        }
Exemple #30
0
        public ResultDto GetInfo(long id)
        {
            //单品信息
            var essayEntity = _defaultRepository.GetEssay(id, _kardSession.UserId);
            var resultDto   = new ResultDto();

            resultDto.Result = essayEntity != null;
            resultDto.Data   = essayEntity;
            //评论 喜欢

            //增加阅读数
            Task.Run(() =>
            {
                var result = _defaultRepository.UpdateBrowseNum(id);
                if (!result)
                {
                    _logger.LogError($"统计:单品{id}增加阅读数失败");
                }
            });

            return(resultDto);
        }
Exemple #31
0
        private ResultDto InsertUpdateGroupReceipt(ReceiptMasterDto groupReceiptdto)
        {
            ResultDto resultDto  = new ResultDto();
            string    objectName = "GroupReceipt";

            try
            {
                string          receiptxml          = CommonMethods.SerializeListDto <List <ReceiptTranscationDto> >(groupReceiptdto.lstGroupReceiptTranscationDto);
                int             id                  = 1;
                ObjectParameter paramaccounmasterID = new ObjectParameter("AccountMasterID", groupReceiptdto.AccountMasterID);
                ObjectParameter paramreceiptCode    = new ObjectParameter("VoucherNumber", string.Empty);

                _dbContext.uspGroupReceiptInsertUpdate(paramaccounmasterID, groupReceiptdto.TransactionDate, paramreceiptCode, groupReceiptdto.VoucherRefNumber, groupReceiptdto.CodeSno, groupReceiptdto.PartyName, groupReceiptdto.EmployeeID,
                                                       groupReceiptdto.AHID, groupReceiptdto.SubHeadID, groupReceiptdto.TransactionType, groupReceiptdto.Amount, groupReceiptdto.TransactionMode,
                                                       groupReceiptdto.ChequeNumber, groupReceiptdto.ChequeDate, groupReceiptdto.BankAccount, groupReceiptdto.Narration, receiptxml, groupReceiptdto.IsGroup, groupReceiptdto.GroupID, groupReceiptdto.UserID);
                resultDto.ObjectId = Convert.ToInt32(paramaccounmasterID.Value);

                resultDto.ObjectCode = string.IsNullOrEmpty((string)paramreceiptCode.Value) ? groupReceiptdto.VoucherNumber : (string)paramreceiptCode.Value;

                if (resultDto.ObjectId > 0)
                {
                    resultDto.Message = string.Format("{0} details saved successfully with code : {1}", objectName, resultDto.ObjectCode);
                }
                else if (resultDto.ObjectId == -1)
                {
                    resultDto.Message = string.Format("Error occured while generating {0} code", objectName);
                }
                else
                {
                    resultDto.Message = string.Format("Error occured while saving {0} details", objectName);
                }
            }
            catch (Exception)
            {
                resultDto.Message  = string.Format("Service layer error occured while saving the {0} details", objectName);
                resultDto.ObjectId = -98;
            }
            return(resultDto);
        }
Exemple #32
0
        public async Task <ResultDto <bool> > Update(AgendamentoDto agendamentoDto)
        {
            var agendamentoDtoValidate = new AgendamentoDtoValidate(agendamentoDto);

            if (!agendamentoDtoValidate.Validate())
            {
                return(await Task.FromResult(ResultDto <bool> .Validation(agendamentoDtoValidate.Mensagens)));
            }

            var agendamento = await _agendamentoRepository.ObterPorId(agendamentoDto.AgendamentoId);

            agendamento.AtualizarAgendamento(agendamentoDto);

            if (await _agendamentoRepository.ValidaAgendamentoDuplicados(agendamento.EstabelecimentoId, agendamento.AgendamentoId, agendamento.DataAgendamento, agendamento.DataFinalAgendamento))
            {
                return(await Task.FromResult(ResultDto <bool> .Validation("Horário já possui agendamento!")));
            }

            await _agendamentoRepository.Update(agendamento);

            return(await Task.FromResult(ResultDto <bool> .Success(true)));
        }
        public IEnumerable <ResultDto> GetResults(int teamId, int skip, int take)
        {
            List <ResultDto> orderedTeamResults = new List <ResultDto>();

            IEnumerable <Result> teamResults = this.dataUnit.GetRepository <Result>().Get(
                filter: res => res.Team.Id == teamId,
                includeProperties: "Team,SportEvent,SportEvent.Results,SportEvent.Results.Team",
                orderBy: s => s.OrderByDescending(x => x.SportEvent.Date)
                .ThenByDescending(t => t.SportEvent.Id),
                skip: skip,
                take: take);

            foreach (Result teamResult in teamResults)
            {
                IEnumerable <Result> eventResults = teamResult.SportEvent.Results;
                ResultDto            resultDto    = new ResultDto();

                orderedTeamResults.Add(Mapper.Map <Result, ResultDto>(teamResult));
            }

            return(orderedTeamResults);
        }
Exemple #34
0
        public ResultDto<CityViewModel> GenerateCity(int cityWidth, int cityHeight)
        {
            var result = new ResultDto<CityViewModel>();

            var city = _cityFactory.Create(_carFactory, cityWidth, cityHeight);
            if (city != null)
            {

                var cityDto = Mapper.Map<CityDto>(city);
                var passengerDto = Mapper.Map<PassengerDto>(city.Passenger);
                var carDto = Mapper.Map<CarDto>(city.Car);

                var cityPositionsLength = cityWidth * cityHeight;
                cityDto.CityPositionDtos = new CityPositionDto[cityPositionsLength];
                for (int i = 0; i < cityPositionsLength; i++)
                {
                    cityDto.CityPositionDtos[i] = Mapper.Map<CityPositionDto>(city.CityPositions[i]);
                }

                var carPos = carDto.YPos * cityDto.YMax + carDto.XPos;
                var passengerPos = passengerDto.StartingYPos * cityDto.YMax + passengerDto.StartingXPos;

                cityDto.CityPositionDtos[carPos].CarDto = carDto;
                cityDto.CityPositionDtos[passengerPos].PassengerDto = passengerDto;

                var viewModel = new CityViewModel
                {
                    CityDto = cityDto
                };

                result.Data = viewModel;
                result.IsSuccessful = true;
            }

            return result;
        }
        /// <summary>
        /// Empower users to type less and do more with automated and complete search suggestions.
        /// </summary>
        /// <param name="subscriptionKey"></param>
        /// <param name="context">Query body</param>
        /// <param name="market">default set en-au</param>
        /// <returns></returns>
        public async Task<ResultDto<BingAutosuggestApiFeeds>> BingAutosuggestApiRequestAsync(string subscriptionKey,
            string context, string market)
        {
            var resultDto = new ResultDto<BingAutosuggestApiFeeds>();
            try
            {
                var client = new HttpClient();

                //request header
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, subscriptionKey);
                var queryString = $"q={context}&Market={market}";
                var url = Constants.BingAutosuggestAPi + queryString;

                var jsonResult = await client.GetStringAsync(url);
                var feed = JsonConvert.DeserializeObject<BingAutosuggestApiFeeds>(jsonResult);

                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.message;
                resultDto.StatusCode = feed.statusCode.ToString();
                resultDto.Success = string.IsNullOrEmpty(feed.message);
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"{ex}");
            }
            return resultDto;
        }
Exemple #36
0
        /// <summary>
        /// Creates the C32 dto.
        /// </summary>
        /// <param name="patientKey">The patient key.</param>
        /// <returns>A <see cref="C32Gen.DataTransferObject.C32Dto"/></returns>
        public C32Dto CreateC32Dto( long patientKey )
        {
            var patient = GetPatientForC32DtoGeneration ( patientKey );

            var dto = new C32Dto ();
            dto.Body = new C32BodyDto ();
            dto.Header = new C32HeaderDto ();

            var guid = new Guid ();
            var timestampInIso8601Format = DateTime.Now.ToString ( "yyyyMMddHHmm" );

            #region Header creation

            dto.Header.DocumentId = new AssigningAuthorityIdDto { Root = guid.ToString (), Extension = "1", AssigningAuthority = "FEI Systems Inc."};
            dto.Header.Title = string.Format (
                "{0} Continuity of Care Document for {1}", patient.Agency.AgencyProfile.AgencyName.LegalName, patient.Name.Complete );
            dto.Header.Version = new VersionDto { Number = 1, SetId = new IIDataTransferObject { Root = guid.ToString () } };

            //TODO: Lookup table for Confidentiality Code
            dto.Header.Confidentiality = new CodedConceptDataTransferObject { CodeSystem = Hl7Codes.Hl7ConfidentialityCode, Code = "N" };
            dto.Header.DocumentTimestamp = new ValueDataTransferObject { Value = timestampInIso8601Format };
            var personalInfoDto = new PersonalInfoDto ();
            personalInfoDto.PatientInfo = new PatientInfoDto ();
            personalInfoDto.PatientInfo.PersonId = new IIDataTransferObject { Extension = patient.Key.ToString (), Root = guid.ToString () };

            personalInfoDto.PatientInfo.PersonAddress = new AddressDto ();
            var patientHomeAddress =
                patient.Addresses.Where (
                    p => p.PatientAddressType.WellKnownName == PatientAddressType.Home ).FirstOrDefault ();
            if ( patientHomeAddress != null )
            {
                if ( !string.IsNullOrWhiteSpace ( patientHomeAddress.Address.FirstStreetAddress )
                     || !string.IsNullOrWhiteSpace ( patientHomeAddress.Address.SecondStreetAddress ) )
                {
                    personalInfoDto.PatientInfo.PersonAddress.StreetAddressLines = new List<string> ();
                    if ( !string.IsNullOrWhiteSpace ( patientHomeAddress.Address.FirstStreetAddress ) )
                    {
                        personalInfoDto.PatientInfo.PersonAddress.StreetAddressLines.Add ( patientHomeAddress.Address.FirstStreetAddress );
                    }
                    if ( !string.IsNullOrWhiteSpace ( patientHomeAddress.Address.SecondStreetAddress ) )
                    {
                        personalInfoDto.PatientInfo.PersonAddress.StreetAddressLines.Add ( patientHomeAddress.Address.SecondStreetAddress );
                    }
                }
                personalInfoDto.PatientInfo.PersonAddress.City = patientHomeAddress.Address.CityName;
                personalInfoDto.PatientInfo.PersonAddress.State = patientHomeAddress.Address.StateProvince.Name;
                personalInfoDto.PatientInfo.PersonAddress.PostalCode = patientHomeAddress.Address.PostalCode.Code;
            }

            personalInfoDto.PatientInfo.PersonPhone = new ValueDataTransferObject ();
            var patientHomePhone =
                patient.PhoneNumbers.Where (
                    p => p.PatientPhoneType.WellKnownName == PatientPhoneType.Home ).FirstOrDefault ();
            if ( patientHomePhone != null )
            {
                personalInfoDto.PatientInfo.PersonPhone.Value = patientHomePhone.PhoneNumber;
            }

            personalInfoDto.PatientInfo.PersonInfo = new PersonInfoDto
                {
                    PersonName = new PersonNameDto { Given = patient.Name.First, Family = patient.Name.Last, Suffix = patient.Name.Suffix },
                    PersonDateOfBirth =
                        new ValueDataTransferObject
                            {
                                Value = patient.Profile.BirthDate == null ? string.Empty : patient.Profile.BirthDate.Value.ToString ( "yyyyMMdd" )
                            }
                };
            if ( patient.BirthInfo != null )
            {
                personalInfoDto.PatientInfo.PersonInfo.BirthPlace = new NameDataTransferObject
                    {
                        Name =
                            string.Format (
                                "{0}, {1}, {2}",
                                patient.BirthInfo.BirthCityName,
                                patient.BirthInfo.BirthCountyArea,
                                patient.BirthInfo.BirthStateProvince )
                    };
            }

            if ( patient.Profile.PatientGender != null )
            {
                personalInfoDto.PatientInfo.PersonInfo.Gender = new CodedConceptDataTransferObject
                    {
                        Code = patient.Profile.PatientGender.AdministrativeGender.CodedConceptCode,
                        DisplayName = patient.Profile.PatientGender.AdministrativeGender.Name,
                        CodeSystem = patient.Profile.PatientGender.AdministrativeGender.CodeSystemIdentifier,
                        CodeSystemName = patient.Profile.PatientGender.AdministrativeGender.CodeSystemName
                    };
            }

            //if (patient.MaritalStatus != null)
            //{
            //    personalInfoDto.PatientInfo.PersonInfo.MaritalStatus = new CodedConceptDataTransferObject()
            //                        {
            //                            Code = "S",
            //                            DisplayName = patient.MaritalStatus.Name,
            //                            CodeSystem = "2.16.840.1.113883.5.2",
            //                            CodeSystemName = "HL7 Marital status"
            //                        };
            //}
            //if (patient.ReligiousAffiliation != null)
            //{
            //    personalInfoDto.PatientInfo.PersonInfo.ReligiousAffiliation = new CodedConceptDataTransferObject
            //                               {
            //                                   Code = "1022",
            //                                   DisplayName = patient.ReligiousAffiliation.Name,
            //                                   CodeSystem = "2.16.840.1.113883.5.1076",
            //                                   CodeSystemName = "ReligiousAffiliation"
            //                               };
            //}
            //var primaryRace =
            //    patient.Races.Where(p => (p.PrimaryIndicator != null && p.PrimaryIndicator.Value == true)).
            //        FirstOrDefault();
            ////TODO: Race CodedConceptLookupBase
            //if (primaryRace != null)
            //{
            //    personalInfoDto.PatientInfo.PersonInfo.Race = new CodedConceptDataTransferObject
            //                                                      {
            //                                                          Code = "2178-2",
            //                                                          DisplayName = primaryRace.Race.Name,
            //                                                          CodeSystem = "2.16.840.1.113883.6.238",
            //                                                          CodeSystemName = "CDC Race and Ethnicity"
            //                                                      };
            //    //TODO: Enthnicity? DetailedEnthnicity? Which one to use?
            //    var primaryRaceEthnicity = primaryRace.Race.RaceDetailedEthnicities.FirstOrDefault();
            //    if (primaryRaceEthnicity != null)
            //    {
            //        personalInfoDto.PatientInfo.PersonInfo.Ethnicity = new CodedConceptDataTransferObject
            //                                                               {
            //                                                                   Code = "2178-2",
            //                                                                   DisplayName =
            //                                                                       primaryRaceEthnicity.DetailedEthnicity.
            //                                                                       Name,
            //                                                                   CodeSystem = "2.16.840.1.113883.6.238",
            //                                                                   CodeSystemName = "CDC Race and Ethnicity"
            //                                                               };
            //    }
            //}

            dto.Header.PersonalInfo = personalInfoDto;

            //TODO: Our language on patient doesn't have these information
            var languageSpokenDto = new LanguageSpokenDto ();
            languageSpokenDto.LanguageCode = new CodeDto { Code = "en-US" };
            languageSpokenDto.ModeCode = new OriginalTextCodedConceptDto
                {
                    Code = "RWR", DisplayName = "Receive Written", CodeSystem = "2.16.840.1.113883.5.60", CodeSystemName = "LanguageAbilityMode"
                };
            languageSpokenDto.PreferenceInd = new ValueDataTransferObject { Value = "false" };
            if ( dto.Header.Languages == null )
            {
                dto.Header.Languages = new List<LanguageSpokenDto> ();
            }
            dto.Header.Languages.Add ( languageSpokenDto );

            var supportDto = new SupportDto ();

            //supportDto.Date = new OperatorDateTimeDto();

            var guardianPatientContact =
                patient.Contacts.FirstOrDefault (
                    patientContact =>
                    patientContact.ContactTypes.Any (
                        patientContactContactType =>
                        patientContactContactType.PatientContactType.WellKnownName ==
                        PatientContactType.Guardian ) );

            if ( guardianPatientContact != null )
            {
                supportDto.Guardian = new GuardianDto
                    {
                        ContactAddress =
                            new AddressDto
                                {
                                    StreetAddressLines =
                                        new List<string> { guardianPatientContact.FirstStreetAddress, guardianPatientContact.SecondStreetAddress },
                                    City = guardianPatientContact.CityName,
                                    PostalCode = guardianPatientContact.PostalCode
                                },
                        ContactName = new PersonNameDto { Given = guardianPatientContact.FirstName, Family = guardianPatientContact.LastName }
                    };

                if ( guardianPatientContact.StateProvince != null )
                {
                    supportDto.Guardian.ContactAddress.State = guardianPatientContact.StateProvince.Name;
                }
                var patientContactHomePhone =
                    guardianPatientContact.PhoneNumbers.Where (
                        p => p.PatientContactPhoneType.WellKnownName == PatientPhoneType.Home ).FirstOrDefault ();
                if ( patientContactHomePhone != null )
                {
                    supportDto.Guardian.ContactTelecom = new ValueDataTransferObject { Value = patientContactHomePhone.PhoneNumber };
                }
            }

            if ( dto.Header.Supports == null )
            {
                dto.Header.Supports = new List<SupportDto> ();
            }
            dto.Header.Supports.Add ( supportDto );

            var agency = patient.Agency;
            if ( agency != null )
            {
                var custodianDto = new CustodianDto
                    {
                        CustodianId = new IIDataTransferObject { Root = guid.ToString (), Extension = patient.Agency.Key.ToString () },
                        CustodianName = agency.AgencyProfile.AgencyName.LegalName
                    };
                dto.Header.Custodian = custodianDto;
            }

            ////TODO: Should HealthCareProviders be a collection?
            //var clinicalCase = patient.ClinicalCases.FirstOrDefault();
            //if (clinicalCase != null)
            //{
            //    var healthcareProvider = clinicalCase.PerformedByStaff;
            //    if (healthcareProvider != null)
            //    {
            //        var healthCareProvidersDto = new HealthCareProvidersDto()
            //        {
            //            HealthcareProvider = new HealthcareProviderDto()
            //            {
            //                Role = new OriginalTextCodedConceptDto()
            //                {
            //                    Code = "PCP",
            //                    CodeSystem = "2.16.840.1.113883.5.88",
            //                    OriginalText = "Primary Care Physician"
            //                },
            //                DateRange = new DateDateRangeDto() { StartDate = new ValueDataTransferObject() { Value = "19320924" }, EndDate = new ValueDataTransferObject() { Value = "20000407" } },

            //                ProviderEntity = new ProviderEntityDto()
            //                {
            //                    ProviderId = new IIDataTransferObject() { Root = "20cf14fb-b65c-4c8c-a54d-b0cca834c18c" },
            //                    ProviderName = new PersonNameDto() { Prefix = healthcareProvider.PrefixName, Given = healthcareProvider.FirstName , Family = healthcareProvider.LastName }
            //                }
            //            }
            //        };

            //        var healthProviderAgency = healthcareProvider.Agency;
            //        if (healthProviderAgency != null)
            //        {
            //            healthCareProvidersDto.HealthcareProvider.ProviderEntity.ProviderOrganizationName = healthProviderAgency.LegalName;
            //        }
            //        dto.Header.HealthCareProviders = healthCareProvidersDto;
            //    }
            //}

            // TODO: Author? Creating Machine or Person
            var informationSourceDto = new InformationSourceDto ();
            informationSourceDto.Author = new AuthorDto
                {
                    AuthorTime = new ValueDataTransferObject { Value = "20000407130000+0500" },
                    AuthorName = new PersonNameDto { Prefix = "prefix", Given = "given", Family = "family", Suffix = "suffix" },
                    Reference = new ReferenceDto
                        {
                            ReferenceDocumentId = new IIDataTransferObject { Root = "root6", Extension = "extension6" },
                            ReferenceDocumentUrl = new ValueDto { Value = "http://www.feiinfo.com" }
                        }
                };

            //informationSourceDto.InformationSourceName = new InformationSourceNameDto
            //{
            //    PersonName = new PersonNameDto { Prefix = "prefix", Given = "given", Family = "family", Suffix = "suffix" },
            //};
            dto.Header.InformationSource = informationSourceDto;

            #endregion Header creation

            #region Body creation

            foreach (var clinicalCase in patient.ClinicalCases)
            {
                foreach ( var visit in clinicalCase.Visits.Where ( p => p.VisitStatus.WellKnownName == VisitStatus.CheckedIn ) )
                {
                    #region Encounters

                    AddEncounterDto ( dto, visit );

                    #endregion Encounters

                    var visitActivities = visit.Activities.ToList ();

                    #region Encounters of BriefIntervention

                    foreach (
                        var briefIntervention in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.BriefIntervention ) )
                    {
                        if ( ( briefIntervention as BriefIntervention ).TobaccoCessationCounselingIndicator.HasValue
                             && ( briefIntervention as BriefIntervention ).TobaccoCessationCounselingIndicator.Value )
                        {
                            var tobaccoCessationCounselingEncounter = AddEncounterDto ( dto, visit );
                            tobaccoCessationCounselingEncounter.EncounterType = new OriginalTextCodedConceptDto
                                {
                                    Code = "99406",
                                    CodeSystem = "2.16.840.1.113883.6.12",
                                    CodeSystemName = "CPT",
                                    DisplayName = "Tobacco Use Cessation Counseling"
                                };
                        }
                    }

                    #endregion

                    #region Problem List (aka Conditions, Diagnoses ), from Visit Problem

                    var visitProblems = visit.Problems;
                    foreach ( var visitProblem in visitProblems )
                    {
                        var problem = visitProblem.Problem;

                        AddProblem ( dto, problem, visit.AppointmentDateTimeRange.StartDateTime );
                    }

                    #endregion Problem List (aka Conditions, Diagnoses), from Visit Problem

                    #region Diagnostic Results (aka Labs)

                    foreach ( var labSpeciment in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.LabSpecimen ) )
                    {
                        foreach ( var labTest in ( labSpeciment as LabSpecimen ).LabTests )
                        {
                            foreach ( var labResult in labTest.LabResults )
                            {
                                var resultDto = new ResultDto ();
                                resultDto.ResultId = new IIDataTransferObject { Root = guid.ToString (), Extension = labResult.Key.ToString () };
                                if ( labTest.LabTestInfo.TestReportDate != null )
                                {
                                    resultDto.ResultDateTime = new OperatorDateTimeDto
                                        {
                                            Date = labTest.LabTestInfo.TestReportDate.Value.ToString ( "yyyyMMdd" )
                                        };
                                }

                                resultDto.ProcedureCode = new OriginalTextCodedConceptDto
                                    {
                                        Code = labResult.LabTestResultNameCodedConcept.CodedConceptCode,
                                        CodeSystem = labResult.LabTestResultNameCodedConcept.CodeSystemIdentifier,
                                        CodeSystemName = labResult.LabTestResultNameCodedConcept.CodeSystemName,
                                        DisplayName = labResult.LabTestResultNameCodedConcept.DisplayName,
                                        OriginalText = labResult.LabTestResultNameCodedConcept.OriginalDescription
                                    };

                                if ( labTest.LabTestInfo.LabTestTypeCodedConcept != null )
                                {
                                    resultDto.ResultType = new OriginalTextCodedConceptDto
                                        {
                                            Code = labTest.LabTestInfo.LabTestTypeCodedConcept.CodedConceptCode,
                                            CodeSystem = labTest.LabTestInfo.LabTestTypeCodedConcept.CodeSystemIdentifier,
                                            CodeSystemName = labTest.LabTestInfo.LabTestTypeCodedConcept.CodeSystemName,
                                            DisplayName = labTest.LabTestInfo.LabTestTypeCodedConcept.DisplayName,
                                        };
                                }
                                else
                                {
                                    resultDto.ResultType = new OriginalTextCodedConceptDto
                                        {
                                            Code = "30313-1",
                                            CodeSystem = "2.16.840.1.113883.6.1",
                                            CodeSystemName = "LOINC",
                                            DisplayName = "HGB",
                                        };
                                }

                                resultDto.ResultStatus = labTest.LabTestInfo.LabResultStatusCodedConcept != null
                                                             ? new CodeDto { Code = labTest.LabTestInfo.LabResultStatusCodedConcept.CodedConceptCode }
                                                             : new CodeDto { Code = "completed" };

                                if ( labResult.Value != null )
                                {
                                    resultDto.ResultValue = new ResultValueDto
                                        {
                                            PhysicalQuantity =
                                                new ValueUnitDataTransferObject
                                                    {
                                                        Value = labResult.Value.Value.ToString ( "F1" ),
                                                        Unit = labResult.UnitOfMeasureCode
                                                    }
                                        };
                                }
                                if ( labTest.LabTestInfo.InterpretationCodeCodedConcept != null )
                                {
                                    resultDto.ResultInterpretation = new OriginalTextCodedConceptDto
                                        {
                                            Code = labTest.LabTestInfo.InterpretationCodeCodedConcept.CodedConceptCode,
                                            CodeSystem = labTest.LabTestInfo.InterpretationCodeCodedConcept.CodeSystemIdentifier,
                                            CodeSystemName = labTest.LabTestInfo.InterpretationCodeCodedConcept.CodeSystemName,
                                            DisplayName = labTest.LabTestInfo.InterpretationCodeCodedConcept.DisplayName,
                                        };
                                }
                                resultDto.ResultReferenceRange = labTest.LabTestInfo.NormalRangeDescription;

                                if ( dto.Body.Results == null )
                                {
                                    dto.Body.Results = new List<ResultDto> ();
                                }
                                dto.Body.Results.Add ( resultDto );
                            }
                        }
                    }

                    #endregion

                    foreach ( var vitalSignActivity in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.VitalSign ) )
                    {
                        #region Vital Signs

                        var vitalSign = vitalSignActivity as VitalSign;

                        // Body Height
                        if ( vitalSign.Height != null && ( vitalSign.Height.FeetMeasure != null || vitalSign.Height.InchesMeasure != null ) )
                        {
                            var vitalSignBodyHeightDto = GetVitalSignResultDto ( visit, vitalSign );

                            var heightCmMeasure = ( ( vitalSign.Height.FeetMeasure == null
                                                          ? 0
                                                          : vitalSign.Height.FeetMeasure.Value ) * 12.0 ) +
                                                  ( ( ( vitalSign.Height.InchesMeasure == null
                                                            ? 0
                                                            : vitalSign.Height.InchesMeasure.Value ) ) * 2.54 );
                            vitalSignBodyHeightDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED CT",
                                    Code = "50373000",
                                    DisplayName = "Body Height"
                                };
                            vitalSignBodyHeightDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignBodyHeightDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject { Value = Math.Round ( heightCmMeasure ).ToString (), Unit = "cm" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignBodyHeightDto );
                        }

                        // Body Weight
                        if ( vitalSign.WeightLbsMeasure != null )
                        {
                            var vitalSignBodyWeightDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignBodyWeightDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED CT",
                                    Code = "27113001",
                                    DisplayName = "Body Weight"
                                };
                            vitalSignBodyWeightDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignBodyWeightDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject { Value = vitalSign.WeightLbsMeasure.Value.ToString ( "0.00" ), Unit = "lbs" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignBodyWeightDto );
                        }

                        // BMI
                        var bmi = vitalSign.CalculateBmi ();
                        if ( bmi != null )
                        {
                            var vitalSignBmiDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignBmiDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED CT",
                                    Code = "225171007",
                                    DisplayName = "Body mass index"
                                };
                            vitalSignBmiDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignBmiDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject { Value = Math.Round ( bmi.Value ).ToString (), Unit = "kg/m2" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignBmiDto );

                            var vitalSignBmiPercentileDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignBmiPercentileDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED CT",
                                    Code = "162860001",
                                    DisplayName = "BMI percentile"
                                };
                            vitalSignBmiPercentileDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignBmiPercentileDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity = new ValueUnitDataTransferObject ()

                                    //{ Value = Math.Round(bmi.Value).ToString(), Unit = "kg/m2" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignBmiPercentileDto );
                        }

                        // Blood Pressures
                        foreach ( var bloodPressure in vitalSign.BloodPressures )
                        {
                            var vitalSignSystollicBpDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignSystollicBpDto.ResultId = new IIDataTransferObject { Root = bloodPressure.Key.ToString () };
                            vitalSignSystollicBpDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED CT",
                                    Code = "12929001",
                                    DisplayName = "Systolic BP"
                                };
                            vitalSignSystollicBpDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignSystollicBpDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject { Value = bloodPressure.SystollicMeasure.ToString (), Unit = "mm[Hg]" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignSystollicBpDto );

                            var vitalSignDiastolicBpDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignDiastolicBpDto.ResultId = new IIDataTransferObject { Root = bloodPressure.Key.ToString () };
                            vitalSignDiastolicBpDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED",
                                    Code = "163031004",
                                    DisplayName = "Diastolic BP"
                                };
                            vitalSignDiastolicBpDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignDiastolicBpDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject { Value = bloodPressure.DiastollicMeasure.ToString (), Unit = "mm[Hg]" }
                                };

                            AddVitalSignResultDto ( dto, vitalSignDiastolicBpDto );
                        }

                        // Heart Rates
                        foreach ( var hearRate in vitalSign.HeartRates )
                        {
                            var vitalSignSystollicBpDto = GetVitalSignResultDto ( visit, vitalSign );
                            vitalSignSystollicBpDto.ResultId = new IIDataTransferObject { Root = hearRate.Key.ToString () };
                            vitalSignSystollicBpDto.ResultType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.96",
                                    CodeSystemName = "SNOMED",
                                    Code = "364075005",
                                    DisplayName = "Heart rate"
                                };
                            vitalSignSystollicBpDto.ResultStatus = new CodeDto { Code = "completed" };
                            vitalSignSystollicBpDto.ResultValue = new ResultValueDto
                                {
                                    PhysicalQuantity =
                                        new ValueUnitDataTransferObject
                                            {
                                                Value = hearRate.BeatsPerMinuteMeasure.ToString (),
                                                Unit = "beats per minute"
                                            }
                                };

                            AddVitalSignResultDto ( dto, vitalSignSystollicBpDto );
                        }

                        #endregion Vital Signs

                        #region Plan of Care

                        // The Dietary Consultation Order maps to the C32 using a SNOMED code.
                        if ( vitalSign.DietaryConsultationOrderIndicator != null && vitalSign.DietaryConsultationOrderIndicator.Value )
                        {
                            var plannedObservationPlannedEventDto = new PlannedEventDto
                                {
                                    PlanFreeText = "dietary consultation order",
                                    PlanId = new IIDataTransferObject { Root = vitalSign.Key.ToString () },
                                    PlannedTime =
                                        new OperatorDateTimeDto
                                            { Date = visit.AppointmentDateTimeRange.StartDateTime.AddDays ( 10 ).ToString ( "yyyyMMdd" ) },
                                    PlanType = new OriginalTextCodedConceptDto
                                        {
                                            Code = "103699006",
                                            DisplayName = "dietary consultation order",
                                            CodeSystem = "2.16.840.1.113883.6.96"
                                        }
                                };

                            //TODO: Hard coded 10 days after the visit for the planned event

                            AddPlannedEvent ( dto, plannedObservationPlannedEventDto );
                        }

                        // The Follow-up Management Plan for BMI Management maps to the c32 using a HCPCS code.
                        if ( vitalSign.BmiFollowUpPlanIndicator != null && vitalSign.BmiFollowUpPlanIndicator.Value )
                        {
                            var plannedObservationPlannedEventDto = new PlannedEventDto
                                {
                                    PlanFreeText = "BMI Management",
                                    PlanId = new IIDataTransferObject { Root = vitalSign.Key.ToString () },
                                    PlannedTime =
                                        new OperatorDateTimeDto
                                            { Date = visit.AppointmentDateTimeRange.StartDateTime.AddDays ( 10 ).ToString ( "yyyyMMdd" ) },
                                    PlanType = new OriginalTextCodedConceptDto
                                        {
                                            Code = "169411000",
                                            DisplayName = "BMI Management",
                                            CodeSystem = "2.16.840.1.113883.6.96"
                                        }
                                };

                            //TODO: Hard coded 10 days after the visit for the planned event

                            AddPlannedEvent ( dto, plannedObservationPlannedEventDto );
                        }

                        #endregion Plan of Care
                    }

                    foreach (
                        var socialHistoryActivity in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.SocialHistory ) )
                    {
                        var socialHistory = socialHistoryActivity as SocialHistory;

                        #region Vital Signs and SocialHistory for Tobacco User

                        if ( socialHistory.SocialHistorySmoking != null && socialHistory.SocialHistorySmoking.SmokingStatus != null )
                        {
                            if ( socialHistory.SocialHistorySmoking.SmokingStatus.WellKnownName == SmokingStatus.EverydaySmoker ||
                                 socialHistory.SocialHistorySmoking.SmokingStatus.WellKnownName == SmokingStatus.SomedaySmoker )
                            {
                                var vitalSignTobaccoUserpDto = new ResultDto ();
                                vitalSignTobaccoUserpDto.ResultId = new IIDataTransferObject { Root = socialHistory.Key.ToString () };
                                vitalSignTobaccoUserpDto.ResultDateTime = new OperatorDateTimeDto
                                    {
                                        Date = visit.AppointmentDateTimeRange.StartDateTime.ToString ( "yyyyMMdd" )
                                    };

                                vitalSignTobaccoUserpDto.ResultType = new OriginalTextCodedConceptDto
                                    {
                                        CodeSystem = "2.16.840.1.113883.6.96",
                                        CodeSystemName = "SNOMED",
                                        Code = "160603005",
                                        DisplayName = "Tobacco User"
                                    };
                                vitalSignTobaccoUserpDto.ResultStatus = new CodeDto { Code = "completed" };

                                AddVitalSignResultDto ( dto, vitalSignTobaccoUserpDto );

                                var socialHistoryTypeDto = new OriginalTextCodedConceptDto
                                    {
                                        CodeSystem = "2.16.840.1.113883.6.96",
                                        CodeSystemName = "SNOMED CT",
                                        Code = "160603005"
                                    };
                                AddSocialHistory ( dto, visit, socialHistory, socialHistoryTypeDto );
                            }
                        }

                        #endregion Vital Signs and SocialHistory for Tobacco User
                    }

                    #region Immunization and Influenza Immunization Procedures

                    foreach (
                        var immunizationActivity in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.Immunization ) )
                    {
                        var immunization = immunizationActivity as Immunization;

                        var immunizationDto = new C32Gen.DataTransferObject.ImmunizationDto ();

                        //TODO: Which value to put here?
                        immunizationDto.AdministeredDate = new ValueDataTransferObject { Value = "199911" };

                        if ( immunization.ImmunizationVaccineInfo != null && immunization.ImmunizationVaccineInfo.VaccineCodedConcept != null )
                        {
                            immunizationDto.MedicationInformations = new List<MedicationInformationDto> ();

                            var medicationInformationDto = new MedicationInformationDto ();
                            immunizationDto.MedicationInformations.Add ( medicationInformationDto );

                            medicationInformationDto.CodedProductName = new OriginalTextCodedConceptDto
                                {
                                    Code = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodedConceptCode,
                                    DisplayName = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.DisplayName,
                                    CodeSystem = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodeSystemIdentifier,
                                    CodeSystemName = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodeSystemName
                                };

                            //medicationInformationDto.CodedBrandName = new CodedConceptDataTransferObject() { Code = "code41", DisplayName = "displayName39", CodeSystem = "codeSystem39", CodeSystemName = "codeSystemName39" };
                            //medicationInformationDto.FreeTextProductName = "Influenza virus vaccine";
                            //medicationInformationDto.FreeTextBrandName = "freeTextBrandName0";

                            if ( immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer != null
                                 &&
                                 ( immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerCode != null
                                   || immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerName != null ) )
                            {
                                medicationInformationDto.DrugManufacturer = new OrganizationDto ();
                                if ( immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerCode != null )
                                {
                                    medicationInformationDto.DrugManufacturer.OrganizationId = new IIDataTransferObject
                                        {
                                            Root = immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerCode
                                        };
                                }

                                //medicationInformationDto.DrugManufacturer.OrganizationAddress = new AddressDto() { StreetAddress = "Street Address", City = "city", State = "state", PostalCode = "postalcode"};
                                if ( immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerName != null )
                                {
                                    medicationInformationDto.DrugManufacturer.OrganizationName = new TextNullFlavorDataTransferObject
                                        {
                                            TextValue = immunization.ImmunizationVaccineInfo.ImmunizationVaccineManufacturer.VaccineManufacturerName
                                        };
                                }

                                //medicationInformationDto.DrugManufacturer.OrganizationTelecom = new ValueDataTransferObject(){Value = "1-999-999-9999"};
                            }
                        }

                        //immunizationDto.MedicationSeriesNumber = new ValueDataTransferObject() { Value = "123456789" };
                        //immunizationDto.Provider = new OrganizationDto
                        //                               {
                        //                                   OrganizationId = new IIDataTransferObject() { Root = "root11", Extension = "extension11" },
                        //                                   OrganizationAddress = new AddressDto() { StreetAddress = "Street Address", City = "city", State = "state", PostalCode = "postalcode" },
                        //                                   OrganizationName = new TextNullFlavorDataTransferObject() { Value = "drug manufacturer" },
                        //                                   OrganizationTelecom = new ValueDataTransferObject() { Value = "1-999-999-9999" }
                        //                               };
                        //immunizationDto.Reactions = new List<OriginalTextCodedConceptDto>()
                        //    {
                        //        new OriginalTextCodedConceptDto()
                        //        {
                        //            Code = "43789009",
                        //            CodeSystem = "2.16.840.1.113883.6.96",
                        //            DisplayName = "CBC WO DIFFERENTIAL",
                        //            OriginalText = "Extract blood for CBC test"
                        //        }
                        //    };
                        //TODO:
                        if ( immunization.ImmunizationNotGivenReason != null )
                        {
                            //immunizationDto.RefusalInd = "Refusal Ind";
                            immunizationDto.RefusalReason = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = immunization.ImmunizationNotGivenReason.CodeSystemIdentifier,
                                    CodeSystemName = immunization.ImmunizationNotGivenReason.CodeSystemName,
                                    Code = immunization.ImmunizationNotGivenReason.CodedConceptCode,
                                    DisplayName = immunization.ImmunizationNotGivenReason.Name
                                };
                        }

                        if ( dto.Body.ImmunizationsDto == null )
                        {
                            dto.Body.ImmunizationsDto = new ImmunizationsDto ();
                        }
                        if ( dto.Body.ImmunizationsDto.Immunizations == null )
                        {
                            dto.Body.ImmunizationsDto.Immunizations = new List<C32Gen.DataTransferObject.ImmunizationDto> ();
                        }
                        dto.Body.ImmunizationsDto.Immunizations.Add ( immunizationDto );

                        #region Procedure of Immunization

                        var procedureDto = new ProcedureDto ();

                        procedureDto.ProcedureDateTime = new OperatorDateTimeDto
                            {
                                Date = visit.AppointmentDateTimeRange.StartDateTime.ToString ( "yyyyMMdd" )
                            };

                        procedureDto.ProcedureFreeTextType = "Influenza Vaccination";
                        procedureDto.ProcedureIds = new List<IIDataTransferObject> ();
                        procedureDto.ProcedureIds = new List<IIDataTransferObject>
                            {
                                new IIDataTransferObject { Root = immunization.Key.ToString () }
                            };
                        if ( visit != null && visit.Staff != null )
                        {
                            var providerInformationDto = new ProviderInformationDto
                                {
                                    ProviderId = new IIDataTransferObject { Root = visit.Staff.Key.ToString () },
                                    ProviderName = new PersonNameDto
                                        {
                                            Family = visit.Staff.StaffProfile.StaffName.Last,
                                            Given = visit.Staff.StaffProfile.StaffName.First,
                                            Prefix = visit.Staff.StaffProfile.StaffName.Prefix,
                                            Suffix = visit.Staff.StaffProfile.StaffName.Suffix
                                        }
                                };

                            if ( visit.Staff.Agency != null )
                            {
                                providerInformationDto.ProviderOrganizationName = new TextNullFlavorDataTransferObject
                                    {
                                        TextValue = visit.Staff.Agency.AgencyProfile.AgencyName.LegalName
                                    };
                            }

                            if ( procedureDto.ProcedureProviders == null )
                            {
                                procedureDto.ProcedureProviders = new List<ProviderInformationDto> ();
                            }

                            procedureDto.ProcedureProviders.Add ( providerInformationDto );
                        }

                        if ( immunization.ImmunizationVaccineInfo != null )
                        {
                            procedureDto.ProcedureType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodeSystemIdentifier,
                                    CodeSystemName = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodeSystemName,
                                    Code = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.CodedConceptCode,
                                    DisplayName = immunization.ImmunizationVaccineInfo.VaccineCodedConcept.DisplayName
                                };
                        }

                        if ( dto.Body.ProceduresDto == null )
                        {
                            dto.Body.ProceduresDto = new ProceduresDto ();
                        }
                        if ( dto.Body.ProceduresDto.Procedures == null )
                        {
                            dto.Body.ProceduresDto.Procedures = new List<ProcedureDto> ();
                        }
                        dto.Body.ProceduresDto.Procedures.Add ( procedureDto );

                        #endregion Procedure of Immunization
                    }

                    #endregion Immunization and Influenza Immunization Procedures

                    #region Procedures of BriefIntervention

                    foreach (
                        var briefIntervention in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.BriefIntervention ) )
                    {
                        if ( ( briefIntervention as BriefIntervention ).TobaccoCessationCounselingIndicator.HasValue
                             && ( briefIntervention as BriefIntervention ).TobaccoCessationCounselingIndicator.Value )
                        {
                            var procedureFreeTextType = "Tobacco Use Cessation Counseling";
                            var procedureType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.12",
                                    CodeSystemName = "CPT",
                                    Code = "99406",
                                    DisplayName = "Tobacco Use Cessation Counseling"
                                };
                            AddProcedureForBriefIntervention (
                                dto, visit, briefIntervention as BriefIntervention, procedureFreeTextType, procedureType );
                        }

                        if ( ( briefIntervention as BriefIntervention ).NutritionCounselingIndicator.HasValue
                             && ( briefIntervention as BriefIntervention ).NutritionCounselingIndicator.Value )
                        {
                            var procedureFreeTextType = "nutrition counseling";
                            var procedureType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.12",
                                    CodeSystemName = "CPT",
                                    Code = "97802",
                                    DisplayName = "nutrition counseling"
                                };
                            AddProcedureForBriefIntervention (
                                dto, visit, briefIntervention as BriefIntervention, procedureFreeTextType, procedureType );
                        }

                        if ( ( briefIntervention as BriefIntervention ).PhysicalActivityCounselingIndicator.HasValue
                             && ( briefIntervention as BriefIntervention ).PhysicalActivityCounselingIndicator.Value )
                        {
                            var procedureFreeTextType = "physical activity counseling";
                            var procedureType = new OriginalTextCodedConceptDto
                                {
                                    CodeSystem = "2.16.840.1.113883.6.14",
                                    CodeSystemName = "HCPCS",
                                    Code = "S9451",
                                    DisplayName = "physical activity counseling"
                                };
                            AddProcedureForBriefIntervention (
                                dto, visit, briefIntervention as BriefIntervention, procedureFreeTextType, procedureType );
                        }
                    }

                    #endregion Procedures

                    //#region Social History (Smoking Status)

                    //foreach ( Activity procedureActivity in visitActivities.Where ( p => p.ActivityType.WellKnownName == ActivityType.SocialHistory ) )
                    //{
                    //}

                    //#endregion Social History (Smoking Status)
                }
            }

            #region Problem List (aka Conditions, Diagnoses )

            foreach ( var clinicalCaseForProblems in patient.ClinicalCases )
            {
                var problems = clinicalCaseForProblems.Problems;
                foreach ( var problem in problems )
                {
                    AddProblem ( dto, problem, null );
                }
            }

            #endregion Problem List (aka Conditions, Diagnoses )

            #region Allergies and Reactions

            var allergies = patient.Allergies;
            foreach ( var allergy in allergies )
            {
                var allergyDto = new AllergyDto ();

                if ( allergy.AllergyType != null )
                {
                    allergyDto.AdverseEventType = new OriginalTextCodedConceptDto
                        {
                            Code = allergy.AllergyType.CodedConceptCode,
                            CodeSystem = allergy.AllergyType.CodeSystemIdentifier,
                            DisplayName = allergy.AllergyType.Name,
                            CodeSystemName = allergy.AllergyType.CodeSystemName
                        };
                }

                allergyDto.AdverseEventDate = new OperatorDateTimeDto ();

                if ( allergy.OnsetDateRange != null && ( allergy.OnsetDateRange.StartDate != null || allergy.OnsetDateRange.EndDate != null ) )
                {
                    if ( allergy.OnsetDateRange.StartDate != null )
                    {
                        allergyDto.AdverseEventDate.StartDate = new ValueDataTransferObject
                            {
                                Value = allergy.OnsetDateRange.StartDate.Value.ToString ( "yyyyMMdd" )
                            };
                    }
                    if ( allergy.OnsetDateRange.EndDate != null )
                    {
                        allergyDto.AdverseEventDate.EndDate = new ValueDataTransferObject
                            {
                                Value = allergy.OnsetDateRange.EndDate.Value.ToString ( "yyyyMMdd" )
                            };
                    }
                }

                if ( allergy.AllergenCodedConcept != null )
                {
                    allergyDto.Product = new OriginalTextCodedConceptDto
                        {
                            CodeSystem = allergy.AllergenCodedConcept.CodeSystemIdentifier,
                            DisplayName = allergy.AllergenCodedConcept.DisplayName,
                            Code = allergy.AllergenCodedConcept.CodedConceptCode,
                            CodeSystemName = allergy.AllergenCodedConcept.CodeSystemName
                        };
                }

                var allergyDtoReactions = new List<OriginalTextCodedConceptDto> ();
                foreach ( var allergyReaction in allergy.AllergyReactions )
                {
                    allergyDtoReactions.Add (
                        new OriginalTextCodedConceptDto
                            {
                                CodeSystem = allergyReaction.Reaction.CodeSystemIdentifier,
                                DisplayName = allergyReaction.Reaction.Name,
                                Code = allergyReaction.Reaction.CodedConceptCode,
                                CodeSystemName = allergyReaction.Reaction.CodeSystemName
                            } );
                }
                allergyDto.Reactions = allergyDtoReactions;

                if ( allergy.AllergySeverityType != null )
                {
                    allergyDto.Severity = new OriginalTextCodedConceptDto
                        {
                            CodeSystem = allergy.AllergySeverityType.CodeSystemIdentifier,
                            DisplayName = allergy.AllergySeverityType.Name,
                            Code = allergy.AllergySeverityType.CodedConceptCode,
                            CodeSystemName = allergy.AllergySeverityType.CodeSystemName
                        };
                }

                if ( allergy.AllergyStatus != null )
                {
                    allergyDto.AllergyStatus = new OriginalTextCodedConceptDto
                        {
                            Code = allergy.AllergyStatus.CodedConceptCode,
                            CodeSystem = allergy.AllergyStatus.CodeSystemIdentifier,
                            DisplayName = allergy.AllergyStatus.Name,
                            CodeSystemName = allergy.AllergyStatus.CodeSystemName
                        };
                }

                if ( dto.Body.Allergies == null )
                {
                    dto.Body.Allergies = new List<AllergyDto> ();
                }
                dto.Body.Allergies.Add ( allergyDto );
            }

            #endregion Allergies and Reactions

            #region Medications

            var medications = patient.Medications;
            foreach ( var medication in medications )
            {
                var medicationDto = new C32Gen.DataTransferObject.MedicationDto ();

                //medicationDto.IndicateMedicationStopped = new ValueDataTransferObject() { Value = "20101010" };

                if ( medication.UsageDateRange != null && ( medication.UsageDateRange.StartDate != null || medication.UsageDateRange.EndDate != null ) )
                {
                    medicationDto.MedicationDateRange = new OperatorDateTimeDto ();
                    if ( medication.UsageDateRange.StartDate != null )
                    {
                        medicationDto.MedicationDateRange.StartDate = new ValueDataTransferObject
                            {
                                Value = medication.UsageDateRange.StartDate.Value.ToString ( "yyyyMMdd" )
                            };
                    }
                    if ( medication.UsageDateRange.EndDate != null )
                    {
                        medicationDto.MedicationDateRange.EndDate = new ValueDataTransferObject
                            {
                                Value = medication.UsageDateRange.EndDate.Value.ToString ( "yyyyMMdd" )
                            };
                    }
                }

                ////TODO: AdmissionTiming
                //medicationDto.AdmissionTiming = new AdmissionTimingDto() { InstitutionSpecified = false, Period = new ValueDataTransferObject() { Value = "6", Unit = "h" } };

                if ( medication.MedicationRoute != null )
                {
                    medicationDto.Route = new OriginalTextCodedConceptDto
                        {
                            CodeSystem = medication.MedicationRoute.CodeSystemIdentifier,
                            Code = medication.MedicationRoute.CodedConceptCode,
                            DisplayName = medication.MedicationRoute.Name,
                            CodeSystemName = medication.MedicationRoute.CodeSystemName
                        };
                }

                if ( medication.MedicationDoseValue != null )
                {
                    medicationDto.Dose = new ValueUnitDataTransferObject
                        {
                            Value = medication.MedicationDoseValue.ToString (), Unit = medication.MedicationDoseUnit.ShortName
                        };
                }

                if ( medication.MedicationDoseUnit != null )
                {
                    medicationDto.Dose.Unit = medication.MedicationDoseUnit.Name;
                }

                ////TODO: Site, DoseRestriction?
                //medicationDto.Site = new CodedConceptDataTransferObject() { Code = "code31", DisplayName = "displayName29", CodeSystem = "codeSystem29", CodeSystemName = "codeSystemName29" };
                //medicationDto.DoseRestriction = new DoseRestrictionDto() { Numerator = new ValueDataTransferObject() { Value = "value63", Unit = "unit18" }, Denominator = new ValueDataTransferObject() { Value = "value64", Unit = "unit19" } };

                // ProductForm
                //medicationDto.ProductForm = new OriginalTextCodedConceptDto { CodeSystem = "2.16.840.1.113883.3.26.1.1", DisplayName = "Puff", Code = "415215001" };

                //TODO: DeliveryMethod?
                //medicationDto.DeliveryMethod = new CodedConceptDataTransferObject() { Code = "code37", DisplayName = "displayName35", CodeSystem = "codeSystem29", CodeSystemName = "codeSystemName35" };

                if ( medication.MedicationCodeCodedConcept != null )
                {
                    medicationDto.MedicationInformation = new MedicationInformationDto
                        {
                            CodedProductName =
                                new OriginalTextCodedConceptDto
                                    {
                                        CodeSystem = medication.MedicationCodeCodedConcept.CodeSystemIdentifier,
                                        DisplayName = medication.MedicationCodeCodedConcept.DisplayName,
                                        Code = medication.MedicationCodeCodedConcept.CodedConceptCode,
                                        CodeSystemName = medication.MedicationCodeCodedConcept.CodeSystemName
                                    },

                            ////TODO: The following information?
                            //CodedBrandName = new CodedConceptDataTransferObject() { Code = "code41", DisplayName = "displayName39", CodeSystem = "codeSystem39", CodeSystemName = "codeSystemName39" },
                            FreeTextProductName = medication.MedicationCodeCodedConcept.DisplayName,

                            //FreeTextBrandName = "freeTextBrandName0",
                            //DrugManufacturer = new OrganizationDto()
                            //{
                            //    OrganizationId = new IIDataTransferObject() { Root = "root11", Extension = "extension11" },
                            //    OrganizationAddress = new AddressDto() { StreetAddress = "Street Address", City = "city", State = "state", PostalCode = "postalcode" },
                            //    OrganizationName = new TextNullFlavorDataTransferObject() { Value = "drug manufacturer" },
                            //    OrganizationTelecom = new ValueDataTransferObject() { Value = "1-999-999-9999" }
                            //}
                        };
                }

                // TODO: Hard Coded
                medicationDto.TypeOfMedication = new OriginalTextCodedConceptDto
                    {
                        Code = "329505003", CodeSystem = "2.16.840.1.113883.6.96", CodeSystemName = "SNOMED CT"
                    };

                if ( medication.MedicationStatus != null )
                {
                    medicationDto.StatusOfMedication = new StatusCodedConceptDataTransferObject
                        {
                            ValueType = "CE",
                            Status = medication.MedicationStatus.Name,
                            Code = medication.MedicationStatus.CodedConceptCode,
                            DisplayName = medication.MedicationStatus.Name,
                            CodeSystem = medication.MedicationStatus.CodeSystemIdentifier,
                            CodeSystemName = medication.MedicationStatus.CodeSystemName
                        };
                }

                //TODO:
                //medicationDto.Indication = new StatusCodedConceptDataTransferObject() { Status = "normal", FreeTextRef = "freeTextRef0", Code = "code46", DisplayName = "displayName44", CodeSystem = "codeSystem44", CodeSystemName = "codeSystemName44" };

                medicationDto.Frequency = medication.FrequencyDescription;
                medicationDto.PatientInstructions = medication.InstructionsNote;

                ////TODO:
                //medicationDto.Reaction = new CodedConceptDataTransferObject() { Code = "code47", DisplayName = "displayName45", CodeSystem = "codeSystem45", CodeSystemName = "codeSystemName45" };
                //medicationDto.Vehicle = new NameDataTransferObject() { Name = "name1", Code = "code48", DisplayName = "displayName45", CodeSystem = "codeSystem45", CodeSystemName = "codeSystemName45" };
                //medicationDto.DoseIndicator = "dose";
                //medicationDto.OrderInformation = new OrderInformationDto()
                //{
                //    OrderNumber = new IIDataTransferObject() { Root = "root10", Extension = "extension10" },
                //    Fills = new ValueDataTransferObject() { Value = "value65" },
                //    QuantityOrdered = new ValueDataTransferObject() { Value = "value66", Unit = "unit20" },
                //    OrderExpirationDateTime = new ValueDataTransferObject() { Value = "value67" },
                //    OperatorDateTime = new OperatorDateTimeDto() { StartDate = new ValueDataTransferObject() { Value = "20101010" }, Operator = "operator0" }
                //};
                //medicationDto.FulfillmentInstructions = "fullfillmentinstructions";
                //medicationDto.FulfillmentHistory = new FullfillmentHistoryDto()
                //{
                //    PrescriptionNumber = new IIDataTransferObject() { Root = "root11", Extension = "extension11" },
                //    Provider = new OrganizationDto()
                //    {
                //        OrganizationId = new IIDataTransferObject() { Root = "root11", Extension = "extension11" },
                //        OrganizationAddress = new AddressDto() { StreetAddress = "Street Address", City = "city", State = "state", PostalCode = "postalcode" },
                //        OrganizationName = new TextNullFlavorDataTransferObject() { Value = "provider" },
                //        OrganizationTelecom = new ValueDataTransferObject() { Value = "1-999-999-9999" }
                //    },
                //    DispensingPharmacyLocation = new TextNullFlavorDataTransferObject(),
                //    DispenseDate = new OperatorDateTimeDto() { StartDate = new ValueDataTransferObject() { Value = "20101010" }, EndDate = new ValueDataTransferObject() { Value = "20101010" }, Operator = "operator1" },
                //    QuantityDispensed = new ValueDataTransferObject() { Value = "value87", Unit = "unit23" },
                //    FillNumber = new ValueDataTransferObject() { Value = "value28" },
                //    FillStatus = new ValueDataTransferObject() { Value = "normal" }
                //};

                if ( dto.Body.Medications == null )
                {
                    dto.Body.Medications = new List<C32Gen.DataTransferObject.MedicationDto> ();
                }
                dto.Body.Medications.Add ( medicationDto );

                #endregion Medications
            }

            #endregion

            return dto;
        }
        /// <summary>
        /// Insert spaces into a string of words lacking spaces, like a hashtag or part of a URL.
        /// </summary>
        /// <param name="breakIntoWordsParameters"></param>
        /// <returns></returns>
        public async Task<ResultDto<BreakIntoWordsApiFeeds>> BreakIntoWordsApiRequestAsync(
            BreakIntoWordsParameters breakIntoWordsParameters)
        {
            var resultDto = new ResultDto<BreakIntoWordsApiFeeds>();
            try
            {
                var client = new HttpClient();

                //request header
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, breakIntoWordsParameters.subscriptionKey);
                var queryString =
                    $"model={breakIntoWordsParameters.model}&text={breakIntoWordsParameters.text}&order={breakIntoWordsParameters.order}&maxNumOfCandidatesReturned={breakIntoWordsParameters.maxNumOfCandidatesReturned}";
                var body = string.Empty;
                var uri = Constants.BreakIntoWordsApi + queryString;

                HttpResponseMessage response;
                //request body
                var byteData = Encoding.UTF8.GetBytes(body);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue(breakIntoWordsParameters.contentType);
                    response = await client.PostAsync(uri, content);
                }

                var jsonResult = await response.Content.ReadAsStringAsync();
                var feed = JsonConvert.DeserializeObject<BreakIntoWordsApiFeeds>(jsonResult);

                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.error?.message;
                resultDto.StatusCode = feed.error?.code;
                resultDto.Success = feed.error == null;
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"{ex}");
            }
            return resultDto;
        }
Exemple #38
0
 public UserAgentDto(ResultDto result)
 {
     Browser = result.UserAgentBrowser;
     Name = result.UserAgentName;
     Id = result.UserAgentId;
 }
        /// <summary>
        /// The API returns a numeric score between 0 and 1. Scores close to 1 indicate positive sentiment and scores close to 0 indicate negative sentiment.
        /// </summary>
        /// <param name="subscriptionKey"></param>
        /// <param name="jsonString">Request body</param>
        /// <param name="contentType">Media type of the body sent to the API.</param>
        /// <returns></returns>
        public async Task<ResultDto<SentimentApiFeeds>> SentimentApiRequestAsync(string subscriptionKey,
            string jsonString, string contentType = Constants.DefaultContentType)
        {
            var resultDto = new ResultDto<SentimentApiFeeds>();
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, subscriptionKey);
                HttpResponseMessage response;

                // Request body
                var byteData = Encoding.UTF8.GetBytes(jsonString);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    response = await client.PostAsync(Constants.SentimentApi, content);
                }
                var jsonResult = await response.Content.ReadAsStringAsync();
                var feed = JsonConvert.DeserializeObject<SentimentApiFeeds>(jsonResult);

                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.message;
                resultDto.StatusCode = feed.statusCode.ToString();
                foreach (var error in feed.errors)
                {
                    resultDto.ErrorMessage += $"InnerError :{error.message}";
                    resultDto.StatusCode += $"InnerErrorCode :{error.id}";
                }
                resultDto.Success = string.IsNullOrEmpty(feed.message);
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"Error: {ex}");
            }
            return resultDto;
        }
Exemple #40
0
        private static ResultDto GetVitalSignResultDto( Visit visit, VitalSign vitalSign )
        {
            var vitalSignResultDto = new ResultDto
                {
                    ResultId = new IIDataTransferObject { Root = vitalSign.Key.ToString () },
                    ResultDateTime = new OperatorDateTimeDto { Date = visit.AppointmentDateTimeRange.StartDateTime.ToString ( "yyyyMMdd" ) }
                };

            return vitalSignResultDto;
        }
 /// <summary>
 /// Analyze faces to detect a range of feelings and personalize your app's responses.
 /// </summary>
 /// <param name="subscriptionKey"></param>
 /// <param name="photoStream"></param>
 /// <returns>
 /// Return emptionRects
 /// </returns>
 public async Task<ResultDto<Emotion[]>> VisionEmotionApiRequestAsync(string subscriptionKey, Stream photoStream)
 {
     var resultDto = new ResultDto<Emotion[]>();
     try
     {
         using (photoStream)
         {
             var emotionRects = await UploadAndDetectEmotion(subscriptionKey, photoStream);
             resultDto.Result = emotionRects;
             resultDto.Success = resultDto.Result != null;
         }
     }
     catch (Exception ex)
     {
         resultDto.ErrorMessage = ex.Message;
         resultDto.Exception = ex;
         Debug.WriteLine($"{ex}");
     }
     return resultDto;
 }
Exemple #42
0
        private static void AddVitalSignResultDto( C32Dto dto, ResultDto vitalSignResultDto )
        {
            if ( dto.Body.VitalSignsDto == null )
            {
                dto.Body.VitalSignsDto = new VitalSignsDto ();
            }

            if ( dto.Body.VitalSignsDto.VitalSignResults == null )
            {
                dto.Body.VitalSignsDto.VitalSignResults = new List<ResultDto> ();
            }

            dto.Body.VitalSignsDto.VitalSignResults.Add ( vitalSignResultDto );
        }
        /// <summary>
        /// Add a variety of image search options to your app or website, from trending images to detailed insights.
        /// </summary>
        /// <param name="bingSearchParameters"></param>
        /// <returns></returns>
        public async Task<ResultDto<BingSearchApiFeeds>> BingSearchApiRequestAsync(BingSearchParameters bingSearchParameters)
        {
            var resultDto = new ResultDto<BingSearchApiFeeds>();
            try
            {
                var client = new HttpClient();

                //request header
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle, bingSearchParameters.subscriptionKey);
                var queryString = $"q={bingSearchParameters.content}&count={bingSearchParameters.count}&offset={bingSearchParameters.offset}&mkt={bingSearchParameters.mkt}&safesearch={bingSearchParameters.safesearch}";
                var url = Constants.BingSearchApi + queryString;

                var jsonResult = await client.GetStringAsync(url);
                var feed = JsonConvert.DeserializeObject<BingSearchApiFeeds>(jsonResult);

                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.message;
                resultDto.StatusCode = feed.statusCode.ToString();
                resultDto.Success = string.IsNullOrEmpty(feed.message);
            }
            catch (Exception ex)
            {
                resultDto.Exception = ex;
                Debug.WriteLine($"{ex}");
            }
            return resultDto;
        }
 /// <summary>
 /// Detect human faces and compare similar ones, organize people into groups according to visual similarity, and identify previously tagged people in images.
 /// </summary>
 /// <param name="subscriptionKey"></param>
 /// <param name="photoStream"></param>
 /// <returns></returns>
 public async Task<ResultDto<FaceRectangle[]>> VisionFaceApiCheckAsync(string subscriptionKey, Stream photoStream)
 {
     var resultDto = new ResultDto<FaceRectangle[]>();
     try
     {
         using (photoStream)
         {
             var faceRects = await UploadAndDetectFaces(subscriptionKey, photoStream);
             resultDto.Result = faceRects;
             resultDto.Success = resultDto.Result != null;
         }
     }
     catch (Exception ex)
     {
         resultDto.ErrorMessage = ex.Message;
         Debug.WriteLine($"Error: {ex}");
     }
     return resultDto;
 }
Exemple #45
0
        public ResultDto<CityViewModel> Tick(CityViewModel cityViewModel)
        {
            var result = new ResultDto<CityViewModel>();
            if (cityViewModel != null)
            {
                var city = _cityFactory.Create(_carFactory, cityViewModel.CityDto.XMax, cityViewModel.CityDto.YMax);
                var destinationPos = city.CityPositions.First(c => c.IsDestinationPosition);
                destinationPos.IsDestinationPosition = false;

                var carDto = cityViewModel.CityDto.CityPositionDtos.First(c => c.CarDto != null).CarDto;
                var passengerDto = cityViewModel.CityDto.CityPositionDtos.First(c => c.PassengerDto != null).PassengerDto;

                var car = city.AddCarToCity(carDto.CarType, carDto.XPos, carDto.YPos);
                var passenger = city.AddPassengerToCity(passengerDto.StartingXPos, passengerDto.StartingYPos, passengerDto.DestinationXPos, passengerDto.DestinationYPos);

                if (car.XPos == passenger.StartingXPos
                    && car.YPos == passenger.StartingYPos)
                {
                    car.PickupPassenger(passenger);
                }

                var hasCarMoved = false;

                DirectionToMove directionToMove = GetDirectionToMove(car, passenger);

                switch (directionToMove)
                {
                    case DirectionToMove.DoNothing:
                        break;
                    case DirectionToMove.Left:
                        car.MoveLeft(passenger);
                        hasCarMoved = true;
                        break;
                    case DirectionToMove.Right:
                        car.MoveRight(passenger);
                        hasCarMoved = true;
                        break;
                    case DirectionToMove.Up:
                        car.MoveUp(passenger);
                        hasCarMoved = true;
                        break;
                    case DirectionToMove.Down:
                        car.MoveDown(passenger);
                        hasCarMoved = true;
                        break;
                    case DirectionToMove.Arrived:
                        if (!car.HasPassenger)
                        {
                            passenger.GetInCar(car);
                        }
                        else
                        {
                            passenger.GetOutOfCar();
                        }
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                if (hasCarMoved)
                {
                    Task.Run(() => Get2PointBWebsiteInBytesAsync());
                }

                var newViewModel = CreateCityViewModel(city, cityViewModel.CityDto.XMax, cityViewModel.CityDto.YMax);
                result.Data = newViewModel;
                result.IsSuccessful = true;
            }

            return result;
        }
        /// <summary>
        /// Extract rich information from images to categorize and process visual data—and protect your users from unwanted Query.
        /// </summary>
        /// <param name="subscriptionKey"></param>
        /// <param name="photoStream"></param>
        /// <returns>
        /// Computer vision analysis result
        /// </returns>
        public async Task<ResultDto<AnalysisResult>> ComputerVisionApiRequestAsync(string subscriptionKey, Stream photoStream)
        {
            var resultDto = new ResultDto<AnalysisResult>();
            try
            {
                var analysisResult = await UploadAndAnalyzeImage(subscriptionKey, photoStream);

                resultDto.Result = analysisResult;
                resultDto.Success = resultDto.Result != null;
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
                Debug.WriteLine($"Error: {ex}");
            }
            return resultDto;
        }
        public ActionResult Result(Criteria criteria)
        {
            var model = new ResultDto();

            var query = _repo.Query<MatchView>(criteria, x => x.ResultHome.HasValue && x.ResultAway.HasValue);

            var mapper = MatchDto.ConfigMapper().CreateMapper();

            var list = mapper.Map<IEnumerable<MatchDto>>(query.AsEnumerable());

            model.Criteria = criteria;
            model.Data = list;

            return View(model);
        }
        /// <summary>
        /// Entity Linking is a natural language processing tool to help analyzing text for your application
        /// </summary>
        /// <param name="subscriptionKey"></param>
        /// <param name="requestBody">
        /// Request body
        /// </param>
        /// <param name="contentType">
        /// Media type of the body sent to the API.
        /// </param>
        /// <param name="selection">
        /// The specific word or phrase within the text that is to be entity linked
        /// </param>
        /// <param name="offset">
        /// The location (in offset by characters) of the selected word or phrase within the input text.
        /// </param>
        /// <returns></returns>
        public async Task<ResultDto<EntityLinkingApiFeeds>> EntityLinkingApiRequestAsync(string subscriptionKey,
            string requestBody, string contentType = "text/plain",string selection = null,string offset = null)
        {
            var resultDto = new ResultDto<EntityLinkingApiFeeds>();
            try
            {
                var client = new HttpClient();
                //request header
                client.DefaultRequestHeaders.Add(Constants.SubscriptionTitle,subscriptionKey);
                HttpResponseMessage response;
                //request body
                var byteData = Encoding.UTF8.GetBytes(requestBody);
                var  parameters = string.Empty;
                var pNo = 0;
                if (!string.IsNullOrEmpty(selection))
                {
                    pNo++;
                    parameters += $"selection={selection}";
                }
                if (!string.IsNullOrEmpty(offset))
                {
                    pNo++;
                    parameters += pNo == 2 ? $"&offset={offset}" : $"offset={offset}";
                }
                
                var requestUrl = Constants.EntityLinkingApi + parameters;

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    response = await client.PostAsync(requestUrl, content);
                }

                var jsonResult = await response.Content.ReadAsStringAsync();

                var feed = JsonConvert.DeserializeObject<EntityLinkingApiFeeds>(jsonResult);


                resultDto.Result = feed;
                resultDto.ErrorMessage = feed.message;
                resultDto.StatusCode = feed.statusCode.ToString();
                resultDto.Success = string.IsNullOrEmpty(feed.message);
            }
            catch (Exception ex)
            {
                resultDto.ErrorMessage = ex.Message;
                resultDto.Exception = ex;
            }

            return resultDto;
        }