Exemplo n.º 1
0
        public async Task <IActionResult> ListUsers([FromQuery] UsersQuery request)
        {
            try
            {
                var result = await _service.GetUsers(request);

                return(Ok(result));
            }
            catch (BusinessLogicException ex)
            {
                return(BadRequest(new Response
                {
                    Status = false,
                    Message = ex.Message
                }));
            }
            catch (Exception e)
            {
                return(BadRequest(new Response
                {
                    Status = false,
                    Message = ErrorMessages.UnkownError
                }));
            }
        }
Exemplo n.º 2
0
        public Base <object> Inviter(UsersQuery model)
        {
            Meta meta = new Meta();
            PageModel <Users> list = new PageModel <Users>();

            //取token值
            TokenReponse repository = new TokenReponse();
            Token        token      = repository.First(model.Token);

            if (token == null)
            {
                meta.ErrorCode = ErrorCode.LoginError.GetHashCode().ToString();
                meta.ErrorMsg  = EnumHelper.GetDescriptionFromEnumValue(ErrorCode.LoginError);
            }
            else
            {
                model.UserID = token.UserId;
                list         = UserService.Inviter(model, ref meta);
            }
            Base <object> response = new Base <object>
            {
                Body = list,
                Meta = meta
            };

            return(response);
        }
Exemplo n.º 3
0
Arquivo: User.cs Projeto: HTheng/Teage
        //修改用户
        public bool Edit(UsersQuery model, ref Meta meta)
        {
            string msg     = EnumHelper.GetDescriptionFromEnumValue(ErrorCode.Success);
            string msgCode = ErrorCode.Success.GetHashCode().ToString();

            Try(context =>
            {
                //查询用户名是否存在
                var user = context.Users.Where(c => c.UserID == model.UserID && model.UserStateId == 0).FirstOrDefault();
                if (user != null)
                {
                    msgCode = ErrorCode.Error.GetHashCode().ToString();
                    msg     = EnumHelper.GetDescriptionFromEnumValue(ErrorCode.Error);
                }
                else
                {
                    //开始修改
                    user.LoginName = model.LoginName;
                    user.Phone     = model.Phone;
                    user.Icon      = model.Icon;
                    user.Mail      = model.Mail;
                    context.SaveChanges();
                }
            });
            meta.ErrorCode = msgCode;
            meta.ErrorMsg  = msg;
            return(true);
        }
        public async Task <PagedResult <UserModel> > GetAll(UsersQuery query, ClaimsPrincipal principal)
        {
            if (!principal.IsSchemeOwner())
            {
                query.PartyId = principal.GetPartyId();
            }
            var usersResult = await _usersRepository.GetAll(query);

            var users         = usersResult.Data;
            var identitiesIds = users.Select(c => c.AspNetUserId).ToList();
            var identities    = await _identityService.GetIdentities(identitiesIds);

            var mappedUsers = from user in users
                              join identity in identities on user.AspNetUserId equals identity.Id
                              select new UserModel
            {
                Id          = user.Id,
                Username    = identity.UserName,
                PartyId     = user.PartyId,
                PartyName   = user.PartyName,
                CreatedDate = user.CreatedDate,
                Roles       = identity.Roles.ToArray(),
                IdentityId  = identity.Id,
                Active      = user.Active
            };

            return(mappedUsers.ToPagedResult(usersResult.Count));
        }
Exemplo n.º 5
0
        public Base <object> Edit(UsersQuery model)
        {
            Meta meta     = new Meta();
            bool editNote = true;
            //取token值
            TokenReponse repository = new TokenReponse();
            Token        token      = repository.First(model.Token);

            if (token == null)
            {
                meta.ErrorCode = ErrorCode.LoginError.GetHashCode().ToString();
                meta.ErrorMsg  = EnumHelper.GetDescriptionFromEnumValue(ErrorCode.LoginError);
            }
            else
            {
                editNote = UserService.Edit(model, ref meta);
            }
            Base <object> result = new Base <object>
            {
                Meta = meta,
                Body = editNote
            };

            return(result);
        }
Exemplo n.º 6
0
        public static void Clear()
        {
            //удалить старых пользователей
            var  usersCleaner = new UsersCleaner();
            bool result       = usersCleaner.RemoveOld();

            IUsersQuery usersQuery = new UsersQuery();
            List <long> userIds    = usersQuery.GetAllUserIds();

            var userKnowledgeCleaner = new UsersKnowledgeCleaner();

            result &= userKnowledgeCleaner.RemoveDeleted(userIds);

            var usersRepetitionIntervalCleaner = new UsersRepetitionIntervalCleaner();

            result &= usersRepetitionIntervalCleaner.RemoveWithoutData(userIds);

            if (result)
            {
                Console.WriteLine("Все что хотели удалить - все удалили!");
            }
            else
            {
                Console.WriteLine("Не все удалили! При удалении что-то пошло не так:(");
            }
            Console.ReadLine();
        }
Exemplo n.º 7
0
        public async Task <IEnumerable <UserQueryResponse> > Handle(UsersQuery request, CancellationToken cancellationToken)
        {
            var users = await this.userRepository.GetAsync();

            var usersMapped = users.Select(u => this.MapToResponse(u.Id, u.Name, u.Surname));

            return(usersMapped);
        }
Exemplo n.º 8
0
        // Method Login
        public UsersModel Login(string username, string password)
        {
            DataTable dt = DataProvider.Instance.Query(UsersQuery.Login(username, password));

            List <UsersModel> users = HelperDao.GenerateList <UsersModel>(dt);

            return(users.FirstOrDefault());
        }
Exemplo n.º 9
0
        public async Task <User> GetAsync(Guid id)
        {
            var query = new UsersQuery {
                FilterIds = id.Collect()
            };

            return((await _queryInvoker.Execute <UsersQuery, User>(query)).SingleOrDefault());
        }
Exemplo n.º 10
0
        public async Task <IActionResult> DeleteAll()
        {
            await Db.Connection.OpenAsync();

            var query = new UsersQuery(Db);
            await query.DeleteAllAsync();

            return(new OkResult());
        }
Exemplo n.º 11
0
        public async Task <IActionResult> GetLatest()
        {
            await Db.Connection.OpenAsync();

            var query  = new UsersQuery(Db);
            var result = await query.LatestUserAsync();

            return(new OkObjectResult(result));
        }
Exemplo n.º 12
0
        public async Task <IActionResult> GetAll([FromQuery] UsersQuery query)
        {
            var users = await _usersService.GetAll(query, null);

            return(Ok(new PagedResult <UserOverviewViewModel>
            {
                Data = users.Data.Select(d => d.Map()),
                Count = users.Count
            }));
        }
Exemplo n.º 13
0
        public static DbQuery <UserBriefModel> ToDbQuery(this UsersQuery query)
        {
            var spec = LinqSpec.For <UserBriefModel>(x => true);

            if (query.Roles != null && query.Roles.Length > 0)
            {
                spec = spec && Specs.HasAtLeastOneRoleFrom(query.Roles);
            }
            return(DbQuery.PagedFor <UserBriefModel>().FromClientQuery(query).AndFilterBy(spec));
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {

            var result = Microsoft.VisualBasic.Webservices.Bing.SearchEngineProvider.Search("GCModeller");
            // Microsoft.VisualBasic.Webservices.Bing.SearchResult nextr = result.NextPage();

            var query = new UsersQuery { term ="guigang" };
            var queryResult = Search.Users(query.Build(), UserSorts.joined);

            Pause();
        }
Exemplo n.º 15
0
        public Base <object> Del(UsersQuery model)
        {
            Meta          meta    = new Meta();
            bool          delNote = UserService.Delete(model, ref meta);
            Base <object> result  = new Base <object>
            {
                Meta = meta,
                Body = delNote
            };

            return(result);
        }
Exemplo n.º 16
0
        public IActionResult Get(int startIndex, int numberOfUsers)
        {
            var query = new UsersQuery
            {
                StartIndex    = startIndex,
                NumberOfUsers = numberOfUsers
            };

            var model = _userService.GetUsersViewModel(query);

            return(Ok(model));
        }
Exemplo n.º 17
0
        private string GetCacheKeyForUsersQuery(UsersQuery query)
        {
            string key = CacheKeys.UsersList.ToString();

            if (query.MovieId.HasValue && query.MovieId > 0)
            {
                key = string.Concat(key, "_", query.MovieId.Value);
            }

            key = string.Concat(key, "_", query.Page, "_", query.ItemsPerPage);
            return(key);
        }
Exemplo n.º 18
0
 public static UserProfileModel GetProfileModel(int userID)
 {
     using (CallDB db = new CallDB())
     {
         var profile = new UsersQuery(db).GetProfile(userID);
         if (profile == null)
         {
             return(new UserProfileModel());
         }
         return(profile);
     }
 }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            var result = Microsoft.VisualBasic.Webservices.Bing.SearchEngineProvider.Search("GCModeller");
            // Microsoft.VisualBasic.Webservices.Bing.SearchResult nextr = result.NextPage();

            var query = new UsersQuery {
                term = "guigang"
            };
            var queryResult = Search.Users(query.Build(), UserSorts.joined);

            Pause();
        }
Exemplo n.º 20
0
        public async Task <QueryResult <User> > ListAsync(UsersQuery query)
        {
            // Here I list the query result from cache if they exist, but now the data can vary according to the Movie ID, page and amount of
            // items per page. I have to compose a cache to avoid returning wrong data.
            string cacheKey = GetCacheKeyForUsersQuery(query);

            var users = await _cache.GetOrCreateAsync(cacheKey, (entry) => {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
                return(_userRepository.ListAsync(query));
            });

            return(users);
        }
Exemplo n.º 21
0
        public async Task TestUserAdd()
        {
            var query = new UsersQuery()
            {
                UserName = "******"
            };
            var data = await _usersService.RetrieveAsync(query);

            if (data.FirstOrDefault() != null)
            {
                Assert.True(data.First().UserName == "测试");
            }
        }
Exemplo n.º 22
0
        // Method ListDataByColumn
        public List <string> ListDataByColumn(string column)
        {
            DataTable dt = DataProvider.Instance.Query(UsersQuery.ListDataByColumn(column));

            List <string> data = new List <string>();

            foreach (DataRow row in dt.Rows)
            {
                data.Add(row[column].ToString());
            }

            return(data);
        }
Exemplo n.º 23
0
        public bool RemoveOld()
        {
            IUsersQuery usersQuery      = new UsersQuery();
            DateTime    maxLastActivity = DateTime.Today.AddDays(-CommonConstants.COUNT_DAYS_TO_HOLD_DATA);

            if (!usersQuery.RemoveByLastActivity(maxLastActivity))
            {
                Console.WriteLine("Не удалось удалить пользователей, которые последний раз заходили ранее {0}!",
                                  maxLastActivity);
                return(false);
            }
            return(true);
        }
Exemplo n.º 24
0
        public async Task <IActionResult> GetOne(int id)
        {
            await Db.Connection.OpenAsync();

            var query  = new UsersQuery(Db);
            var result = await query.FindOneAsync(id);

            if (result is null)
            {
                return(new NotFoundResult());
            }
            return(new OkObjectResult(result));
        }
Exemplo n.º 25
0
        public ActionResult GetUsersList()
        {
            try
            {
                var queryParams = new NameValueCollection();
                if (!ParamHelper.CheckParaQ(ref queryParams))
                {
                    return(Json(new ResponseEntity <int>(RegularFunction.RegularSqlRegexText), JsonRequestBehavior.AllowGet));
                }

                var query = new UsersQuery(queryParams);

                var sqlCondition = new StringBuilder();
                sqlCondition.Append("ISNULL(IsDelete,0)!=1");

                if (!string.IsNullOrEmpty(query.Name))
                {
                    sqlCondition.Append($" and (Name like '%{query.Name}%'  or UserName like '%{query.Name}%')");
                }

                PageRequest preq = new PageRequest
                {
                    TableName      = " [Users] ",
                    Where          = sqlCondition.ToString(),
                    Order          = " Id DESC ",
                    IsSelect       = true,
                    IsReturnRecord = true,
                    PageSize       = query.PageSize,
                    PageIndex      = query.PageIndex,
                    FieldStr       = "*"
                };

                var result = new UsersBLL().GetDataByPage(preq);

                var response = new ResponseEntity <object>(true, string.Empty,
                                                           new DataGridResultEntity <Users>
                {
                    TotalRecords   = preq.Out_AllRecordCount,
                    DisplayRecords = preq.Out_PageCount,
                    ResultData     = result
                });

                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new ResponseEntity <object>(-999, string.Empty, ""), JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 26
0
Arquivo: User.cs Projeto: HTheng/Teage
 //我的邀请人
 public PageModel <Users> Inviter(UsersQuery queryInfo, ref Meta meta)
 {
     return(Try(context =>
     {
         string sql = "SELECT * FROM Users WHERE 1=1  ";
         List <SqlParameter> paramList = new List <SqlParameter>();
         //查询
         if (!string.IsNullOrEmpty(queryInfo.ParentID))
         {
             sql += " AND ParentID= @ParentID";
             paramList.Add(new SqlParameter("@ParentID", queryInfo.ParentID));
         }
         return context.QuerySql <Users>(sql, queryInfo, paramList.ToArray());
     }));
 }
Exemplo n.º 27
0
 public IPagedList <UserBriefModel> GetUsers(UsersQuery query)
 {
     EnsureIsValid(query);
     try
     {
         var usersPage = _deps.Users.PartialProjectThenQueryPage <UserBriefModel>(
             User.Spec.Active,
             query.ToDbQuery());
         return(usersPage);
     }
     catch (Exception ex)
     {
         throw new ServiceException("Can't get users.", ex);
     }
 }
Exemplo n.º 28
0
        public async Task <IActionResult> DeleteOne(int id)
        {
            await Db.Connection.OpenAsync();

            var query  = new UsersQuery(Db);
            var result = await query.FindOneAsync(id);

            if (result is null)
            {
                return(new NotFoundResult());
            }
            await result.DeleteAsync();

            return(new OkResult());
        }
        public async Task <IEnumerable <UserDto> > Handle(UsersQuery request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var users = await _context.Users
                        .Include(u => u.Team)
                        .Include(u => u.Tasks)
                        .Include(u => u.Projects)
                        .ToListAsync();

            return(_mapper.Map <IEnumerable <UserDto> >(users));
        }
Exemplo n.º 30
0
 public static RegisterModel GetDadosFaturamento(int userID)
 {
     using (CallDB db = new CallDB())
     {
         if (FaturamentoExist(userID))
         {
             var dadosFaturamento = new UsersQuery(db).GetFaturamento(userID);
             return(dadosFaturamento);
         }
         else
         {
             var dadosFaturamento = new RegisterModel();
             return(dadosFaturamento);
         }
     }
 }
Exemplo n.º 31
0
        public JsonResult SendToMail(long userId, string email)
        {
            if (IdValidator.IsInvalid(userId) || string.IsNullOrWhiteSpace(email))
            {
                return(JsonResultHelper.Error());
            }

            string uniqueUserId = GetUserUniqueId();

            if (string.IsNullOrEmpty(uniqueUserId))
            {
                return(JsonResultHelper.Error());
            }

            string domain = WebSettingsConfig.Instance.Domain;

            //TODO: вынести в конфиг
            var mailerConfig = new MailerConfig {
                IsHtmlBody  = true,
                DisplayName = "Сайт " + domain
            };

            const string SUBJECT = "Ваш уникальный идентификатор";
            string       body    = string.Format("Здравствуйте, Уважаемый пользователь!<br />"
                                                 + "Ваш уникальный идентификатор на сайте {0}:<br /><b>{1}</b><br /><br />"
                                                 + "<span style='font-size:12px;'><b>" + Message + "</b></span><br />"
                                                 +
                                                 "<span style='font-size: 11px;'>Если Вы не указывали этот адрес почты на сайте {0}, то просто удалите это письмо.<br />" +
                                                 "Данное письмо не требует ответа.</span>",
                                                 domain, uniqueUserId);

            var  mailer    = new Mailer();
            bool isSuccess = mailer.SendMail(MailAddresses.SUPPORT, email, SUBJECT, body, mailerConfig);

            if (isSuccess)
            {
                var usersQuery = new UsersQuery();
                if (!usersQuery.UpdateEmail(userId, email))
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "ProfileController.SendToMail для пользователя с идентификатором {0}, не смогли обновить адрес электронной почты на {1}",
                        userId, email);
                }
            }

            return(JsonResultHelper.Success(isSuccess));
        }
Exemplo n.º 32
0
 public IPagedList<UserBriefModel> GetUsers(UsersQuery query)
 {
     EnsureIsValid(query);
     try
     {
         var usersPage = _deps.Users.PartialProjectThenQueryPage<UserBriefModel>(
             User.Spec.Active,
             query.ToDbQuery());
         return usersPage;
     }
     catch (Exception ex)
     {
         throw new ServiceException("Can't get users.", ex);
     }
 }
Exemplo n.º 33
0
 public IHttpActionResult Get(UsersQuery query)
 {
     var page = _userService.GetUsers(query);
     return Ok(page);
 }