Exemple #1
0
        public async Task <VooAlterarViewModel> AlterarVoo(VooAlterarViewModel vooInserirViewModel)
        {
            /*fast validation validações de campo má pratica utilizar nas propriedades da view model*/
            var vl = new ValidarVooAlterarViewModel(vooInserirViewModel);

            if (!vl.Evalido)
            {
                _notificacoes.AddRange(vl.notys);
            }

            if (_notificacoes.TemErros)
            {
                return(vooInserirViewModel);
            }

            await ValidacaoCampos(vooInserirViewModel);

            if (_notificacoes.TemErros)
            {
                return(vooInserirViewModel);
            }

            var vooA   = _mapper.Map <Voo>(vooInserirViewModel);
            var vooAdd = await _repositorio.Atualizar(vooA);

            vooInserirViewModel.Id = vooAdd.Id.ToString();

            return(vooInserirViewModel);
        }
Exemple #2
0
        public IEnumerable <Core.ContactDetails> Get()
        {
            var contactDataPetapoco = connection.Query <Data.ContactDetails>("SELECT * FROM ContactDetails"); //PetaPoco

            var contactDataDapper = connection.GetAll <Data.ContactDetails>();                                //Dapper

            return(mapper.Map <IEnumerable <Core.ContactDetails> >(contactDataDapper));
        }
Exemple #3
0
        public async Task <UserDTO> FindUser(string email)
        {
            ApplicationUser targetUser = await identityRepository.FindUser(userManager, email);

            UserDTO user = mapper.Map <ApplicationUser, UserDTO>(targetUser);

            return(user);
        }
Exemple #4
0
        /// <summary>
        /// Method to map object from source into target
        /// </summary>
        /// <typeparam name="T">source generic type</typeparam>
        /// <typeparam name="K">target object generic type</typeparam>
        /// <param name="source">source object</param>
        /// <param name="target">target object</param>
        public void Map <T, K>(T source, K target)
        {
            var config = new MapperConfiguration(cfg => { cfg.CreateMap <T, K>(); });

            // CreateMap<T, K>();
            AutoMapper.IMapper iMapper = config.CreateMapper();
            //var source = new T();
            var destination = iMapper.Map <T, K>(source);

            iMapper.Map(source, target);
        }
Exemple #5
0
        public void AddPostToUsersStreams(CPostDTO post, List <string> UsersLogins)
        {
            using (ISession session = _cluster.Connect(_keyspace))
            {
                Cassandra.Mapping.IMapper mapper = new Cassandra.Mapping.Mapper(session);

                session.UserDefinedTypes.Define(new CommentProfile().Definitions);

                StreamDTO Stream = _StreamMapper.Map <StreamDTO>(post);

                var Ids = mapper.Fetch <CUserDTO>("where \"Email\" in (?)", UsersLogins.ToArray()).ToList();
                this.AddPostToUsersStreams(post, Ids.Select(p => p.User_Id).ToList());
            }
        }
        public void AddPostToUsersStreams(PostDTO post, List <long> UsersIds)
        {
            using (ISession session = _cluster.Connect(_keyspace))
            {
                Cassandra.Mapping.IMapper mapper = new Cassandra.Mapping.Mapper(session);

                session.UserDefinedTypes.Define(new CommentProfile().Definitions);
                StreamDTO Stream = _StreamMapper.Map <StreamDTO>(post);
                foreach (var u in UsersIds)
                {
                    Stream.User_Id = u;
                    mapper.Insert(Stream);
                }
            }
        }
        public async Task <ApiResponse> CreateRole([FromBody] RoleDto dto)
        {
            try
            {
                var getAllRole = await _roleServices.GetAllAsync();

                foreach (var roleName in getAllRole)
                {
                    if (dto.Name == roleName.Name)
                    {
                        return(new ApiResponse("identity entity framework core", dto, 400));
                    }
                }
                // save
                var role = _mapper.Map <Role>(dto);
                await _roleServices.AddAsync(role);

                return(new ApiResponse("Add role success", 200));
            }
            catch (Exception ex)
            {
                // return error message if there was an exception
                return(new ApiResponse("Can't add role", ex, 400));
            }
        }
        public async Task <ResponseData> AddScheduler(CreateScheduler createScheduler)
        {
            var Result = _verificationAddSchedulerData.Validate(createScheduler);

            if (!Result.IsValid)
            {
                return(new ResponseData(Result.ToString(), "", StatusCode.Fail));
            }
            var  OperationSqlData = _mapper.Map <DataBaseScheduler>(createScheduler);
            bool result           = await _jobDetailAndTrigger.AddSchedulerType(OperationSqlData);

            if (!result)
            {
                return(new ResponseData("任务创建失败", "", StatusCode.Fail));
            }
            //var Trigger = await scheduler.GetTrigger(new TriggerKey(OperationSqlData.Name, "defalut"));
            //获取任务的触发器
            var Trigger = await scheduler.GetTrigger(new TriggerKey(OperationSqlData.Name));

            OperationSqlData.IsExists      = 1;
            OperationSqlData.ExecuteReuslt = 0;
            OperationSqlData.CreateTime    = DateTime.Now.ToString("F");
            // 获取任务的执行时间
            OperationSqlData.PresetTime = TimeZoneInfo.ConvertTime((DateTimeOffset)Trigger.GetNextFireTimeUtc(), TimeZoneInfo.Local).ToString("F");
            await _Database.InsertAsync(OperationSqlData);

            return(new ResponseData("新增成功", OperationSqlData, StatusCode.Success));
        }
Exemple #9
0
 public void AutoMapper()
 {
     for (int i = 0; i < N; i++)
     {
         _dest[i] = _autoMapper.Map <Y>(_source[i]);
     }
 }
Exemple #10
0
 public static void MapperMap <T, T1>(T src, T1 dst)
 {
     if (mapperConfig == null)
     {
         throw new Exception("Must call MapperInit !!");
     }
     iMapper.Map <T, T1>(src, dst);
 }
Exemple #11
0
        public T MapTo <T>(object obj)
            where T : class
        {
            if (obj == null)
            {
                return(default(T));
            }

            return(innerMapper.Map <T>(obj));
        }
        public async Task <IActionResult> Index()
        {
            var pages = new Dictionary <Guid, GetIndexModel>();

            var contentPageModels = await contentPageService.GetAllAsync().ConfigureAwait(false);

            if (contentPageModels != null && contentPageModels.Any())
            {
                pages = (from a in contentPageModels.OrderBy(o => o.PageLocation).ThenBy(o => o.CanonicalName)
                         select mapper.Map <GetIndexModel>(a)).ToDictionary(x => x.Id);
                logger.LogInformation($"{nameof(Index)} has succeeded");
            }
            else
            {
                logger.LogWarning($"{nameof(Index)} has returned with no results");
            }

            return(Ok(pages));
        }
        public async Task <IHttpActionResult> Login([FromBody] UserModel user)
        {
            UserDTO userDTO = mapper.Map <UserModel, UserDTO>(user);
            string  token   = await authService.Login(userDTO);

            if (token != null)
            {
                return(Ok(new ResponseSheme(token, "EverythingOk", 200)));
            }
            return(NotFound());
        }
Exemple #14
0
        public static List <TDest> MapList <TSource, TDest>(this AutoMapper.IMapper Mapper, IEnumerable <TSource> Source) where TDest : new()
        {
            var ret = new List <TDest>();

            if (Source != null)
            {
                foreach (var item in Source)
                {
                    var NewItem = Mapper.Map <TSource, TDest>(item);
                    ret.Add(NewItem);
                }
            }
            return(ret);
        }
Exemple #15
0
                static async Task <MailFolder> RequestSpecialFolder(MSGraph.IMailFolderRequestBuilder requestBuilder,
                                                                    FolderType type, bool isFavorite,
                                                                    AM.IMapper mapper)
                {
                    var folder = await requestBuilder.Request()
                                 .GetAsync()
                                 .ConfigureAwait(false);

                    return(mapper.Map <MSGraph.MailFolder, MailFolder>(folder, opt => opt.AfterMap((src, dst) =>
                    {
                        dst.IsFavorite = isFavorite;
                        dst.Type = type;
                    })));
                }
Exemple #16
0
        public void AddContact(Contact contact1)
        {
            //var contact = new DBModels.Contact
            //{
            //    Id = contact1.id,
            //    Name = contact1.name,
            //    Email = contact1.email,
            //    Mobile = contact1.mobile,
            //    Landline = contact1.landline,
            //    Address = contact1.address,
            //    Website = contact1.website
            //};
            //string temp = JsonConvert.SerializeObject(contact);
            //DBContact dbcontact = JsonConvert.DeserializeObject<DBContact>(temp);

            // var model = _mapper.Map<Models.Contact>(contact1);
            //     db.Insert(_mapper.Map<Models.Contact>(DBModels.Contact) );



            db.Insert(mapper.Map <Models.Contact, DBModels.Contact>(contact1));

            Console.WriteLine("Inserted succesffully\n");
        }
 public ApiResponse CreateRole([FromBody] RoleDto dto)
 {
     try
     {
         // save
         var role = _mapper.Map <Role>(dto);
         _roleServices.AddAsync(role);
         return(new ApiResponse("Add role success", 200));
     }
     catch (Exception ex)
     {
         // return error message if there was an exception
         return(new ApiResponse("Can't add role", ex, 400));
     }
 }
 /// <summary>
 /// Retrieve a list of all ReportGroups
 /// <para>Returns List<ReportGroup></para>
 /// </summary>
 /// <returns>List<ReportGroup></returns>
 public List <ReportGroup> GetReportGroups()
 {
     using IDatabase db = Conn();
     try
     {
         List <ReportGroupMapping> data   = db.FetchOneToMany <ReportGroupMapping>(x => x.ReportDefMappings, "exec rpt.GetReportGroups");
         List <ReportGroup>        output = _mapper.Map <List <ReportGroupMapping>, List <ReportGroup> >(data);
         return(output);
     }
     catch (Exception e)
     {
         LogCritical("|" + MethodBase.GetCurrentMethod() + "|" + e.Message);
         throw new Exception(e.Message);
     }
 }
        public async Task <IActionResult> Index()
        {
            var viewModel = new IndexViewModel()
            {
                Path      = LocalPath,
                Documents = new List <IndexDocumentViewModel>()
                {
                    new IndexDocumentViewModel {
                        Title = HealthController.HealthViewCanonicalName
                    },
                    new IndexDocumentViewModel {
                        Title = SitemapController.SitemapViewCanonicalName
                    },
                    new IndexDocumentViewModel {
                        Title = RobotController.RobotsViewCanonicalName
                    },
                },
            };
            var sharedContentItemModels = await sharedContentItemDocumentService.GetAllAsync().ConfigureAwait(false);

            if (sharedContentItemModels != null)
            {
                var documents = from a in sharedContentItemModels.OrderBy(o => o.Title)
                                select mapper.Map <IndexDocumentViewModel>(a);

                viewModel.Documents.AddRange(documents);

                logger.LogInformation($"{nameof(Index)} has succeeded");
            }
            else
            {
                logger.LogWarning($"{nameof(Index)} has returned with no results");
            }

            return(this.NegotiateContentResult(viewModel));
        }
Exemple #20
0
        public double Map <TSource, TDestionation>()
            where TSource : _Base
            where TDestionation : class, new()
        {
            List <long> autoMapperElapsedTicks = new List <long>();

            for (int ii = 0; ii < RandomDataSampleSize; ii++)
            {
                Stopwatch stopwatch = new Stopwatch();
                var       source    = this.GetT <TSource>(ii);
                stopwatch.Start();
                var dest = _mapper.Map <TSource, TDestionation>(source);
                stopwatch.Stop();
                autoMapperElapsedTicks.Add(stopwatch.ElapsedTicks);
            }
            return(autoMapperElapsedTicks.Average());
        }
        public void MapDataModelToApi_AllProperties_ShouldSuccess()
        {
            //arrange
            var target = new Student()
            {
                Code          = "123",
                Firstname     = "John",
                Patronymic    = "Robert",
                Lastname      = "Doe",
                Sex           = "Female",
                StudentGroups = new List <StudentGroups>()
                {
                    new StudentGroups()
                    {
                        Group = new Data.Models.Group()
                        {
                            Name = "Group1"
                        }
                    },
                    new StudentGroups()
                    {
                        Group = new Data.Models.Group()
                        {
                            Name = "Group2"
                        }
                    }
                }
            };
            //act
            var actual = mapper.Map <Features.GetManyStudents.Student>(target);

            //assert
            actual.Should().BeEquivalentTo(
                new Features.GetManyStudents.Student()
            {
                Lastname      = target.Lastname,
                Sex           = Sex.Female,
                Firstname     = target.Firstname,
                Patronymic    = target.Patronymic,
                Code          = target.Code,
                StudentGroups = "Group1,Group2"
            });
        }
        private async Task GetAndMapContentItem(IList <IBaseContentItemModel> contentItem, ILinkDetails linkDetail)
        {
            var mappingToUse = contentTypeMappingService.GetMapping(linkDetail.ContentType !);

            if (mappingToUse != null)
            {
                var pagesApiContentItemModel = GetFromApiCache <IBaseContentItemModel>(mappingToUse, linkDetail.Uri !) ?? AddToApiCache(await GetContentItemAsync <IBaseContentItemModel>(mappingToUse !, linkDetail !.Uri !).ConfigureAwait(false));

                if (pagesApiContentItemModel != null)
                {
                    mapper.Map(linkDetail, pagesApiContentItemModel);

                    if (pagesApiContentItemModel.ContentLinks != null)
                    {
                        pagesApiContentItemModel.ContentLinks.ExcludePageLocation = true;
                        await GetSharedChildContentItems(pagesApiContentItemModel.ContentLinks, pagesApiContentItemModel.ContentItems).ConfigureAwait(false);
                    }

                    contentItem.Add(pagesApiContentItemModel !);
                }
            }
        }
Exemple #23
0
        public JsonResponse <int> SendCorporateTieUpEmail(CorporateTieUpEnquiry model)
        {
            JsonResponse <int> response = new JsonResponse <int>();

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <CorporateTieUpEnquiry, EmailModel>();
            });

            IMapper    iMapper = config.CreateMapper();
            EmailModel email   = iMapper.Map <CorporateTieUpEnquiry, EmailModel>(model);

            string otherContent = "Company: " + model.CompanyName;

            email.Subject = "Enquiry for Corporate Tie Up.";
            int status = EmailHelper.PrepareAndSendEmail(email, otherContent);

            if (status == (int)AspectEnums.EmailStatus.Sent)
            {
                log.Info(string.Format("Email successfully sent to {0} at {1}.", model.Name, model.Email));
                response.Message      = string.Format("Email successfully sent to {0} at {1}.", model.Name, model.Email);
                response.StatusCode   = "200";
                response.IsSuccess    = true;
                response.SingleResult = status;
            }
            else
            {
                log.Info(string.Format("Could not send email to {0} at {1}.", model.Name, model.Email));
                response.Message      = string.Format("Could not send email to {0} at {1}.", model.Name, model.Email);
                response.StatusCode   = "500";
                response.IsSuccess    = false;
                response.SingleResult = status;
            }

            return(response);
        }
 public TDestination Map <TSource, TDestination>(TSource source)
 {
     return(mapper.Map <TSource, TDestination>(source));
 }
Exemple #25
0
 public void AddProduct(ProductDTO product)
 {
     _productRepository.Insert(_mapper.Map <Product>(product));
     _unitOfWork.Save();
 }
 public T Map <T>(object source)
 {
     return(_mapper.Map <T>(source));
 }
Exemple #27
0
 public TU MapToEvent <T, TU>(T source) where TU : IEvent
 {
     return(mapper.Map <T, TU>(source));
 }
Exemple #28
0
 public static T Map <T>(object item)
 {
     return(mapper.Map <T>(item));
 }
Exemple #29
0
 public static TDest SmartMap <TDest>(this AutoMapper.IMapper Mapper, object Source, TDest Dest)
 {
     return((TDest)Mapper.Map(Source, Dest, Source.GetType(), Dest.GetType()));
 }
Exemple #30
0
 public TDestination Map <TSource, TDestination>(TSource source) => mapper.Map <TSource, TDestination>(source);