public async Task <IActionResult> GetProductsAsync(int?pageSize = null, int?pageNumber = null, string name = null) { var products = new ListModelResponse <ProductViewModel>(); try { var response = await AdventureWorksRepository .GetProducts(pageSize, pageNumber, name); products.Model = response.Model.Select(item => item.ToViewModel()).ToList(); products.TotalCount = response.TotalCount; products.Message = string.Format($"Showing {response.Model?.Count()} of total {response.TotalCount} items."); _logger?.LogInfo("Products: " + products.Message); } catch (Exception ex) { products.DidError = true; products.ErrorMessage = ex.Message; _logger.LogError(ex.Message); } return(products.ToHttpResponse()); }
public IActionResult GetUsers() { logger.LogInfo("Admin is looking at accounts"); return(Ok(mapper.Map <IEnumerable <User>, IEnumerable <UserDTO> >(repository.User.GetAll()))); }
public async Task SendToKafka(String message) { var res = await producer.ProduceAsync(topic, new Message<Null, string> { Value = message }); producer.Flush(TimeSpan.FromSeconds(10)); logger.LogInfo($"KAFKA => Delivered '{res.Value}' to '{res.TopicPartitionOffset}'"); }
public async Task <List <JObject> > GetPatientObservationPages(string id, int pages) { _logger.LogInfo("Class: ObservationService, Method: GetPatientObservationPages"); return(await _resource.GetPages($"{requestOption[1]}{id}", pages)); }
public async Task <IActionResult> DisplayTweet() { //Get Logged in user details User loggedUser = await GetLoggedInUserDetails(); _logger.LogInfo($"Get all tweets home page for user: {loggedUser.UserName}"); _logger.LogInfo($"Controller : UserTweet | Action : DisplayTweet | User : {loggedUser.Id}"); List <TweetViewModel> TweetVMList = await GetTweetsForDisplaying(loggedUser); List <UserFollower> tempFollowerCount = await _unitofWork.UserFollowerRepository.FindByConditionAync(p => p.FollowerId.Equals(loggedUser.Id) && p.FollowAction.Equals(FollowActions.Following)) as List <UserFollower>; List <UserFollower> tempFollowingCount = await _unitofWork.UserFollowerRepository.FindByConditionAync(p => p.UserId.Equals(loggedUser.Id) && p.FollowAction.Equals(FollowActions.Following)) as List <UserFollower>; UserTweetViewModel userViewModel = new UserTweetViewModel() { UserId = loggedUser.Id, UserFullName = loggedUser.FirstName + " " + loggedUser.LastName, FollowersCount = tempFollowerCount.Count, FollowingCount = tempFollowingCount.Count, //TotalTweetCount = TweetVMList == null ? 0 : TweetVMList.Count(), UserAccountCreationDate = $"{loggedUser.AccountCreationDate.ToString("MMMM")} {loggedUser.AccountCreationDate.Year}", UserBirthDay = $"{loggedUser.BirthDay.Value.ToString("MMMM")} {loggedUser.BirthDay.Value.Day}", UserAvatarUrl = loggedUser.AvatarUrl, UserBiography = loggedUser.Biography, UserLocation = loggedUser.Location, TwitterHandle = loggedUser.UserName, TweetVM = new TweetViewModel() }; userViewModel.OwnTweets = TweetVMList; _logger.LogInfo($"Returning data: {userViewModel.TotalTweetCount}"); return(View(userViewModel)); }
public async Task <IActionResult> GetAllProperties() { try { var properties = await _repositoryWrapper.Property.GetAllProperties(); if (properties == null) { _logger.LogInfo($"No 'Property' has been found in db."); return(NotFound()); } else { _logger.LogInfo($"Returned all 'Properties' from db. Total number of Properties found: {properties.Count()}."); var propertiesResult = _mapper.Map <IEnumerable <PropertyDto> >(properties); return(Ok(propertiesResult)); } } catch (Exception e) { _logger.LogError($"Something went wrong inside GetAllProperties() action: {e.Message}"); _logger.LogError(e.ErrorMessageExtension()); return(StatusCode(500, e.Message)); } }
public async Task <UserAttributeModel> GetUserAttribute() { try { var client = GraphClientUtility.GetGraphServiceClient(); if (client == null) { _logger.LogError("UserAttributeService-GetUserAttribute: Unable to create proxy for the Azure AD B2C graph client"); return(null); } _logger.LogInfo("UserAttributeService-GetUserAttribute: [Started] to fetch user attribute in Azure AD B2C"); var extensionName = GraphClientUtility.ExtensionName; var schemaExtensions = await client.SchemaExtensions.Request().GetAsync(); var userAttributeModel = new UserAttributeModel(); var extensionSchemas = new List <ExtensionSchema>(); while (schemaExtensions.NextPageRequest != null) { foreach (SchemaExtension extension in schemaExtensions.CurrentPage) { try { if (extension.Id.Contains(extensionName)) { userAttributeModel.Id = extension.Id; foreach (var item in extension.Properties) { try { ExtensionSchema extensionSchema = new ExtensionSchema(); extensionSchema.Name = item.Name; extensionSchema.DataType = item.Type; extensionSchemas.Add(extensionSchema); } catch (Exception ex) { _logger.LogError($"ExtensionController-GetExtensions: fail to add extension [name:{item.Name}] to collection "); _logger.LogError(ex); } } userAttributeModel.ExtensionSchemas = extensionSchemas; } } catch (Exception ex) { _logger.LogError($"ExtensionController-GetExtensions: fail to add extension [name:{extension.Id}] to collection "); _logger.LogError(ex); } } schemaExtensions = await schemaExtensions.NextPageRequest.GetAsync(); } return(userAttributeModel); } catch (Exception ex) { _logger.LogError("ExtensionController-GetExtensions: Exception occured...."); _logger.LogError(ex); } return(null); }
public async Task <ActionResult <List <Shipment> > > GetAllShipments() { _logger.LogInfo("Fetching all shipments"); return(Ok(await _shipmentService.GetAllShipments())); }
public IActionResult Get() { _logger.LogInfo("Fetching all the Customer details"); var customerDetails = _customerService.GetAllCustomerDetails(); if (customerDetails == null || customerDetails.Count() == 0) { return(StatusCode((int)HttpStatusCode.NotFound, "No customers available")); } _logger.LogInfo($"Returning {customerDetails.Count()} customers."); return(StatusCode((int)HttpStatusCode.OK, customerDetails)); }
public IEnumerable <string> GetBooks() { _logger.LogInfo("Here is the info message from GetBooks...."); return(new string[] { "Book_1", "Book_2" }); }
public IActionResult Admin() { ViewBag.opportunities = _repository.Opportunity.GetAllOpportunities(); _logger.LogInfo($"Returned all users from database."); return(View("Admin")); }
public IEnumerable <string> Get() { Logger.LogInfo("ValuesController -> Get()"); return(new string[] { "value1", "value2" }); }
public User BuildUserForCreation(UserModel userModel, string tenantId, string b2cExtensionAppClientId) { User newUser = null; try { if (userModel == null) { _logger.LogError("UserService-BuildUserForCreation: Input value cannot be null"); return(newUser); } _logger.LogInfo($"UserService-BuildUserForCreation: Building User Object for {userModel.SignInName}"); if (string.IsNullOrEmpty(userModel.Password)) { _logger.LogWarn($"UserService-BuildUserForCreation: User {userModel.SignInName} has not set the password. System is assigning automatic password"); userModel.Password = GetRandomPassword(); } //How to get the delegated administration newUser = new User(); newUser.GivenName = userModel.GivenName; newUser.Surname = userModel.Surname; newUser.DisplayName = userModel.DisplayName; newUser.AccountEnabled = userModel.AccountEnabled; newUser.MailNickname = getMailNickName(userModel.GivenName, userModel.Surname); newUser.UsageLocation = userModel.UsageLocation; newUser.JobTitle = userModel.JobTitle; newUser.Department = userModel.Department; newUser.StreetAddress = $"{userModel.Address} {userModel.Address2} {userModel.Address3}"; newUser.State = userModel.State; newUser.Country = userModel.Country; newUser.PostalCode = userModel.PostalCode; newUser.MobilePhone = userModel.MobilePhone; newUser.MySite = userModel.WebSite; newUser.Mail = userModel.BusinessEmail; if (!string.IsNullOrEmpty(userModel.BusinessPhone)) { newUser.BusinessPhones = new List <string> { userModel.BusinessPhone } } ; newUser.Identities = new List <ObjectIdentity> { new ObjectIdentity() { SignInType = CareStreamConst.UserSignInType_UserPrincipalName, Issuer = tenantId, IssuerAssignedId = $"{getMailNickName(userModel.GivenName, userModel.Surname)}@{tenantId}" //IssuerAssignedId = $"{userModel.Password}-{getMailNickName(userModel.GivenName, userModel.Surname)}@{tenantId}" }, new ObjectIdentity() { SignInType = CareStreamConst.UserSignInType_EmailAddress, Issuer = tenantId, IssuerAssignedId = userModel.SignInName } }; newUser.PasswordProfile = new PasswordProfile() { Password = userModel.Password, ForceChangePasswordNextSignIn = userModel.ForceChangePasswordNextSignIn }; if (userModel.CustomAttributes != null) { if (userModel.CustomAttributes.Any()) { var extensionInstance = BulidCustomExtension(b2cExtensionAppClientId, userModel.CustomAttributes); newUser.AdditionalData = extensionInstance; } } _logger.LogInfo($"UserService-BuildUserForCreation: Completed building User Object for {userModel.SignInName}"); } catch (Exception ex) { _logger.LogError("UserService-BuildUserForCreation: Exception occured...."); _logger.LogError(ex); } return(newUser); }
private void BuildWindow() { logger?.LogInfo($"Started buildind {nameof(NavigationPage)}."); SetupControls(); SetControlPositions(); logger?.LogInfo($"Finished building {nameof(NavigationPage)}."); }
public async Task <PrivacyDto> GetPrivacySettings(int userId, int programId) { _logger.LogInfo("================================="); _logger.LogInfo("Get privacy setting started"); var privacySettings = new PrivacyDto(); using (var sqlConnection = await _databaseConnectionFactory.CreateConnectionAsync()) { _logger.LogInfo("Connection Made."); try { _logger.LogInfo("UserID :" + userId + "."); _logger.LogInfo("ProgramId :" + programId + "."); _logger.LogInfo("ImagePath :" + string.Concat(_configuration["ServiceAPIURL"], ImagesDefault.UserDefaultImage) + "."); _logger.LogInfo("IsRequestAccepted :TRUE ."); privacySettings.Benefator = (await sqlConnection.QueryAsync <BenefactorDto>(SQLQueryConstants.GetPrivacySettingQuery, new { UserId = userId, ProgramId = programId, ImagePath = string.Concat(_configuration["ServiceAPIURL"], ImagesDefault.UserDefaultImage), IsRequestAccepted = true })).ToList(); _logger.LogInfo("Get benefactor Details."); if (privacySettings.Benefator.Count > 0 && privacySettings.Benefator.Where(x => x.CanViewTransaction == true).Count() > 0) { _logger.LogInfo("If benefactor count > 0 && privacySettings.Benefator.Where(x=>x.CanViewTransaction == true).Count() > 0 Then IsOnlyMe = False"); privacySettings.IsOnlyMe = false; } else { _logger.LogInfo("IsOnlyMe = True."); privacySettings.IsOnlyMe = true; } _logger.LogInfo("Get privacy setting endeds"); return(privacySettings); } catch (Exception ex) { _logger.LogInfo("Exception = " + ex.ToString()); throw; } finally { sqlConnection.Close(); sqlConnection.Dispose(); _logger.LogInfo("Connection Closed."); } } }
public async Task <List <JObject> > GetPatients() { _logger.LogInfo("Class: PatientService, Method: GetAllPages"); return(await _resource.GetAllPages(requestOption)); }
public async Task <IActionResult> GetWordById(Guid id) { var word = (await _service.FindWordByCondition(p => p.Id.Equals(id), false)).FirstOrDefault(); if (word == null) { _logger.LogInfo($"Word with Id: {id} doesn't exist in the database."); return(NotFound()); } var wordDto = _mapper.Map <WordGetDto>(word); return(Ok(wordDto)); }
public IActionResult Get() { _logger.LogInfo("Get executed"); return(Ok(_repoWrapper.Entity.FindAll())); }
protected void LogInformation(string message) { _loggerManager.LogInfo(message); }
/// <summary> /// Custom request begin. /// </summary> /// <param name="httpContext"></param> private void BeginInvoke(HttpContext httpContext) { _logger.CreateNewSession(httpContext); _logger.LogInfo($"About to start {httpContext.Request.Method} {httpContext.Request.GetDisplayUrl()} request"); }
public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _logger.LogInfo("Login method, model is OK"); if (VerifyMFACode(userForLoginDto.UserName, userForLoginDto.MfaCode)) { _logger.LogInfo("Login method, mfa code is OK"); var userFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password); if (userFromRepo == null) { return(Unauthorized()); } _logger.LogInfo("user exists"); //build token, it will contains user name var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.UserName) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); var user = _mapper.Map <UserForListDto>(userFromRepo); return(Ok(new { token = tokenHandler.WriteToken(token), user })); } else { return(BadRequest("MFA code is invalid")); } } catch (Exception ex) { _logger.LogError($"Something went wrong: {ex}"); return(StatusCode(500, "Internal server error")); } }
// public async Task<PagedList<Product>> ProductInquiry(ProductInquiryParams productInquiryParams) // { // string sortExpression = productInquiryParams.SortExpression; // string sortDirection = productInquiryParams.SortDirection; // int sortOrder = 1; // if (sortDirection == "desc") // { // sortOrder = -1; // } // if (productInquiryParams.CurrentPageNumber > 0) // { // productInquiryParams.CurrentPageNumber = productInquiryParams.CurrentPageNumber - 1; // } // //Func<Product, Object> orderByFunc = null; // if (string.IsNullOrEmpty(sortExpression)) // { // sortExpression = "{Name: 1}"; // // orderByFunc = product => product.Description; // } // else // { // sortExpression = "{" + sortExpression + ": " + sortOrder + "}"; // } // //productInquiryParams.ProductNumber = productInquiryParams.ProductNumber.Trim(); // //productInquiryParams.Description = productInquiryParams.Description.Trim(); // //_context.GetCollection<Product>("Product"). // //var // IQueryable<Product> query = await GetAllQuery(); // // _context.GetCollection<Product>("Product").AsQueryable(); // query = query.OrderByDynamic("Description", true); // /* // query = (from p in query.AsQueryable() // orderby p.Id // select p); // */ // if(!string.IsNullOrEmpty(productInquiryParams.ProductNumber)) // { // // Guid guid; // // Guid.TryParse(productInquiryParams.ProductNumber, out guid); // query = query.Where(x => x.Id == productInquiryParams.ProductNumber); // } // if(!string.IsNullOrEmpty(productInquiryParams.Description)) // { // query = query.Where(x => x.Description == productInquiryParams.Description); // } // //var count = CountAsync(); // //var query = coll.AsQueryable(); // return await PagedList<Product>.CreateAsync(query, productInquiryParams.CurrentPageNumber, productInquiryParams.PageSize); // } public async Task <Pagination <ProductDto> > ProductInquiry(ProductSpecParams productParams) { try { // if (productInquiryParams.PageIndex > 0) // { // productInquiryParams.PageIndex = productInquiryParams.PageIndex - 1; // } FilterDefinition <Product> filter = FilterDefinition <Product> .Empty; if (!string.IsNullOrEmpty(productParams.BrandId)) { filter = Builders <Product> .Filter.Eq(x => x.ProductBrand.Id, productParams.BrandId.ToObjectId()); } if (!string.IsNullOrEmpty(productParams.TypeId)) { filter = filter & Builders <Product> .Filter.Eq(x => x.ProductType.Id, productParams.TypeId.ToObjectId()); } if (!string.IsNullOrEmpty(productParams.Search)) { //var regex = new BsonRegularExpression(productParams.Search +"$"); //var query = Query<Product>.Matches(p => p.Item, regex); filter = filter & Builders <Product> .Filter.Regex(x => x.Name, new BsonRegularExpression(productParams.Search, "i")); //filter = filter & Builders<Product>.Filter.AnyEq("Name", new BsonRegularExpression(productParams.Search)); } SortDefinition <Product> sort = null; switch (productParams.Sort) { case "priceAsc": sort = Builders <Product> .Sort.Ascending("Price"); break; case "priceDesc": sort = Builders <Product> .Sort.Descending("Price"); break; default: sort = Builders <Product> .Sort.Ascending("Name"); break; } // if (!string.IsNullOrEmpty(productParams.Sort)) // { // if (productParams.Sort == "priceDesc") // sort = Builders<Product>.Sort.Descending(sortExpression); // else // sort = Builders<Product>.Sort.Ascending(sortExpression); // } var filteredQuery = _context.Products.Find(filter).Sort(sort); var totalFetch = await filteredQuery.ToListAsync(); var count = totalFetch.Count(); var results = await filteredQuery.Skip((productParams.PageSize) *(productParams.PageIndex - 1)) .Limit(productParams.PageSize).ToListAsync(); // var prodBrands = await _prodBradRepo.GetAll(); var productDtoToReturn = _mapper.Map <List <Product>, List <ProductDto> >(results); // var images = new List<byte[]>(); // var productDtoToReturn = new List<ProductDto>(); // foreach (var item in results) // { // foreach (var img in item.ImageIds) // { // var imageByte = await _imageRepo.Get(img); // images.Add(imageByte.ImageContent); // } // var productDto = new ProductDto // { // Name = item.Name, // Description = item.Description, // Price = item.Price, // // ProductTypeId = item.ProductTypeId, // // ProductBrandId = item.ProductBrandId, // Images = images // }; // productDtoToReturn.Add(productDto); // //var images = await _imageRepo.Get(item.ImageIds); // // var imgfilter = Builders<Image>.Filter.Eq("_id", item.ImageIds); // // await _context.Images.Find(imgfilter).FirstOrDefaultAsync(); // } _logger.LogInfo("inside paged results"); return(new Pagination <ProductDto>(productParams.PageIndex, productParams.PageSize, count, productDtoToReturn)); // return new PagedList<ProductDto>(productDtoToReturn, results.Count, productParams.PageIndex, // productParams.PageSize); //return await PagedList<Product>.CreateAsync(filteredQuery, productInquiryParams.CurrentPageNumber, // productInquiryParams.PageSize); } catch (Exception ex) { // log or manage the exception _logger.LogError(String.Format("ProductRepository-ProductInquiry file:{0} {1}", System.Environment.NewLine, ex.ToString())); throw ex; } }
private static void SeedData(UserManager <User> userManager, RoleManager <IdentityRole <Guid> > roleManager, IFolderManager folderManager, ILoggerManager logger, string targetPath) { var users = SeedingDataHelper.SeedingDataFromJson <User>("Users.json"); try { List <IdentityRole <Guid> > roles = new List <IdentityRole <Guid> > { new IdentityRole <Guid> { Name = "Member" }, new IdentityRole <Guid> { Name = "Moderator" }, new IdentityRole <Guid> { Name = "Admin" } }; foreach (var role in roles) { var isExist = roleManager.FindByNameAsync(role.Name).Result == null; if (isExist) { roleManager.CreateAsync(role).Wait(); logger.LogInfo($"Role: {role.Name} has been created."); } } foreach (var user in users) { if (userManager.FindByNameAsync(user.UserName).Result == null) { if (user.UserName == "Admin") { userManager.CreateAsync(user, "admin").Wait(); userManager.AddToRoleAsync(user, "Admin").Wait(); logger.LogInfo($"User: {user.UserName} has been created."); foreach (var folder in user.StorageItems) { folderManager.CreateFolder(FolderFullPathMaker(targetPath, folder.RelativePath)); logger.LogInfo($"Folder {folder.DisplayName} has been created."); } } else { userManager.CreateAsync(user, "password").Wait(); userManager.AddToRoleAsync(user, "Member").Wait(); logger.LogInfo($"User: {user.UserName} has been created."); foreach (var folder in user.StorageItems) { folderManager.CreateFolder(FolderFullPathMaker(targetPath, folder.RelativePath)); logger.LogInfo($"Folder {folder.DisplayName} has been created."); } } } } } catch (Exception ex) { throw ex; } }
public async Task <ActionResult <IEnumerable <BookDTO> > > GetLivros() { try { // obtem _logger.LogInfo("[BOOK][GET]Buscando livros."); var books = await _bookService.GetAllAsync(); // ordena e mapeia var result = books.OrderBy(x => x.Title).ToList(); var bookDTOs = result.Select(_mapper.Map <Book, BookDTO>).ToList(); // retorna _logger.LogInfo($"Retornando { result.Count} livros."); return(bookDTOs); } catch (Exception ex) { // erro _logger.LogError($"Algo deu errado: { ex.Message }."); _notification.AddNotification("", "Algo deu errado, verifique o LOG para mais informações."); return(StatusCode(500, _notification)); } }
public string GetSample() { _logger.LogInfo("Getting sample from api"); return("Hello!"); }