Exemplo n.º 1
0
        /// <summary>
        /// Applies sort to the query
        /// </summary>
        /// <param name="parameters">Parameters to use</param>
        /// <param name="sql">Query where apply the sort</param>
        /// <returns>Query with sort</returns>
        protected string ApplySort(string sql, RestParameters parameters)
        {
            if (string.IsNullOrEmpty(sql))
            {
                throw new ArgumentNullException(nameof(sql));
            }
            if ((parameters?.Sort?.Fields?.Any()).GetValueOrDefault(false) == false)
            {
                return($"{sql} ORDER BY 1");
            }

            var result = new StringBuilder();

            // Order by
            result.Append($"{sql} ORDER BY");
            bool isFirst = true;

            foreach (var clause in parameters.Sort.Fields)
            {
                if (!isFirst)
                {
                    result.Append(",");
                }
                isFirst = false;
                var direction = clause.Direction == SortDirections.Ascending ? "ASC" : "DESC";
                result.Append($" [{clause.Field}] {direction}");
            }
            // if no fields, order by first column
            if (isFirst)
            {
                result.Append(" 1");
            }
            return(result.ToString());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Fetch all entities that match the given parameters
        /// </summary>
        /// <param name="parameters">Parameters to filter data</param>
        /// <returns>Entities that match the given parameters</returns>
        public async Task <FetchEntitiesResponse> FetchEntitiesAsync(RestParameters parameters)
        {
            // Base query
            var sql = $"SELECT {string.Join(", ", GetColumnNames())} FROM {GetDbOjectName()}";

            // Query for count
            string countSql = null;

            // Sql parameters
            var sqlParameters = new List <SqlParameter>();

            if (parameters != null)
            {
                // Apply filters
                var filteredSql = ApplyFilters(sql, parameters, out sqlParameters);

                // Apply sort
                var sortedSql = ApplySort(filteredSql, parameters);

                // Pagination
                sql = ApplyPagination(sortedSql, parameters);

                // Check if count is required (if so, the query for count is the filtered one)
                countSql = parameters.WithCount ? filteredSql : null;
            }
            // Execute the query
            var result = await ExecuteQueryAsync(sql, sqlParameters, countSql);

            // Return response
            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Applies filters to a sql select
        /// </summary>
        /// <param name="parameters">Parameters where take filters</param>
        /// <param name="sql">Select where to apply filters</param>
        /// <param name="sqlParameters">Added parameter for filter</param>
        /// <returns>Query with filters</returns>
        protected string ApplyFilters(string sql, RestParameters parameters, out List <SqlParameter> sqlParameters)
        {
            if (string.IsNullOrEmpty(sql))
            {
                throw new ArgumentNullException(nameof(sql));
            }
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            sqlParameters = new List <SqlParameter>();

            // Filters to apply
            var filterToApply = ComposeFilter(parameters);

            if (filterToApply == null)
            {
                return(sql);
            }

            // Get the where clause
            var whereClause = GetWhereClauseForFilter(filterToApply, sqlParameters);

            if (!string.IsNullOrEmpty(whereClause))
            {
                sql += $" WHERE ({whereClause})";
            }
            return(sql);
        }
        public string GetAliveTokens()
        {
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token);
            SimpleEntity simpleEntity = tokensResource.HttpGetAsObject(urlParameters, null);

            return(simpleEntity.content);
        }
Exemplo n.º 5
0
        public IEnumerable <ThreadReply> GetThreadReplies(Guid threadId,
                                                          Action <IEnumerable <ThreadReply> > pageResult = null, int?maxPages = null)
        {
            var par = new RestParameters();
            var res = GetAllPages(string.Format(CultureInfo.InvariantCulture, "threads/{0}/replies", threadId), par, pageResult);

            return(res);
        }
        public GuestService TryUpdateTokenlifetime(Lifetime lifetime, UserService admin)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, admin.GetToken())
                                            .AddParameters(RestParametersKeys.Time, lifetime.Time);
            SimpleEntity simpleEntity = tokenLifetimeResource.HttpPutAsObject(null, null, bodyParameters);

            return(this);
        }
        public AdminService UpdateTokenlifetime(Lifetime lifetime)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, user.Token)
                                            .AddParameters(RestParametersKeys.Time, lifetime.Time);
            SimpleEntity simpleEntity = tokenLifetimeResource.HttpPutAsObject(null, null, bodyParameters);

            return(this);
        }
Exemplo n.º 8
0
        public IEnumerable <Thread> GetThreads(IEnumerable <Guid> threadIds, Action <IEnumerable <Thread> > pageResult = null)
        {
            var par = new RestParameters();

            par.Add("id", string.Join(",", threadIds));
            var res = GetAllPages("threads/", par, pageResult);

            return(res);
        }
        public AdminService SuccessfulAdminLogin(IUser adminUser)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Name, adminUser.Name)
                                            .AddParameters(RestParametersKeys.Password, adminUser.Password);
            SimpleEntity simpleEntity = adminAuthorizedResource.HttpPostAsObject(null, null, bodyParameters);

            adminUser.Token = simpleEntity.content;
            return(new AdminService(adminUser));
        }
        public string GetCoolDownTime()
        {
            CoolDownTime   coolDownTime  = new CoolDownTime();
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token);
            SimpleEntity simpleEntity = cooldowntimeResource.HttpGetAsObject(urlParameters, null);

            coolDownTime.Time = simpleEntity.content;
            return(simpleEntity.content);
        }
        public UserService SuccessfulUserLogin(IUser user)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Name, user.Name)
                                            .AddParameters(RestParametersKeys.Password, user.Password);
            SimpleEntity simpleEntity = userAuthorizedResource.HttpPostAsObject(null, null, bodyParameters);

            user.Token = simpleEntity.content;
            return(new UserService(user));
        }
        public ItemTemplate GetItem(ItemTemplate itemTemplate)
        {
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token);
            RestParameters pathParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Index, itemTemplate.Index);
            SimpleEntity simpleEntity = itemResource.HttpGetAsObject(urlParameters, pathParameters);

            return(new ItemTemplate(simpleEntity.content, itemTemplate.Index));
        }
        public UserService ChangePassw(IUser userD, IUser newpassw)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, userD.Token)
                                            .AddParameters(RestParametersKeys.OldPassword, userD.Password)
                                            .AddParameters(RestParametersKeys.NewPassword, newpassw.Password);
            SimpleEntity simpleEntity = userpasswresource.HttpPutAsObject(null, null, bodyParameters);

            //logger.Info("ChangePassw = " + simpleEntity.content);
            return(this);
        }
        public GuestService Logout(IUser loggerOut)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, loggerOut.Token)
                                            .AddParameters(RestParametersKeys.Name, loggerOut.Name);
            SimpleEntity simpleEntity = logoutResource.HttpPostAsObject(null, null, bodyParameters);

            CheckService(!simpleEntity.Equals(true), "Logout Unsuccessful.");
            loggerOut.Token = string.Empty;
            return(new GuestService());
        }
Exemplo n.º 15
0
 private RestRequest prepareRequestBody(RestRequest request, RestParameters bodyParameters)
 {
     if (bodyParameters != null)
     {
         foreach (KeyValuePair <string, string> current in bodyParameters.Parameters)
         {
             request.AddParameter(current.Key, current.Value);
         }
     }
     return(request);
 }
Exemplo n.º 16
0
 private RestRequest PreparePathVariables(RestRequest request, RestParameters pathVariables)
 {
     if (pathVariables != null)
     {
         foreach (KeyValuePair <string, string> current in pathVariables.Parameters)
         {
             request.AddUrlSegment(current.Key, current.Value);
         }
     }
     return(request);
 }
        public AdminService UpdateCoolDowntime(CoolDownTime cooldowntime)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, user.Token)
                                            .AddParameters(RestParametersKeys.Time, cooldowntime.Time);
            SimpleEntity simpleEntity = cooldowntimeResource.HttpPutAsObject(null, null, bodyParameters);

            CheckService(!simpleEntity.Equals(true),
                         "CoolDownTime " + cooldowntime.ToString() + "was not Updated.");
            return(this);
        }
Exemplo n.º 18
0
        private RestRequest CreateRestRequest(RestUrlKeys restUrlKeys, RestParameters urlParameters,
                                              RestParameters pathVariables, RestParameters bodyParameters)
        {
            CheckImplementation(restUrlKeys);
            string      url     = PrepareUrlParameters(restUrl.ReadBaseUrl() + restUrl.GetUrl(restUrlKeys), urlParameters);
            RestRequest request = new RestRequest(url, dictionaryMethods[restUrlKeys]);

            request = PreparePathVariables(request, pathVariables);
            request = prepareRequestBody(request, bodyParameters);
            return(request);
        }
        public AdminService LockUser(IUser user1)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, user.Token);
            RestParameters pathVariables = new RestParameters()
                                           .AddParameters(RestParametersKeys.Name, user1.Name);

            SimpleEntity simpleEntity = lockeduserResource
                                        .HttpPostAsObject(null, pathVariables, bodyParameters);

            return(this);
        }
        public UserService UpdateItem(ItemTemplate item, ItemTemplate updateItem)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Token, user.Token)
                                            .AddParameters(RestParametersKeys.Item, updateItem.Item);
            RestParameters pathParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Index, item.Index);
            SimpleEntity simpleEntity = itemResource.HttpPutAsObject(null, pathParameters, bodyParameters);

            CheckService(!simpleEntity.Equals(true),
                         "Item " + item.ToString() + "was not Added.");
            return(this);
        }
        public UserService CreateUser(IUser newUser)
        {
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token)
                                           .AddParameters(RestParametersKeys.Name, newUser.Name)
                                           .AddParameters(RestParametersKeys.Password, newUser.Password)
                                           .AddParameters(RestParametersKeys.Rights, ParamFalse);
            SimpleEntity simpleEntity = userResource
                                        .HttpPostAsObject(urlParameters, null, null);

            //logger.Info("CreateUser = " + simpleEntity.content);
            return(this);
        }
        public UserService RemoveUser(IUser newAdmin)
        {
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token)
                                           .AddParameters(RestParametersKeys.Name, newAdmin.Name);
            SimpleEntity simpleEntity = userResource
                                        .HttpDeleteAsObject(urlParameters, null, null);

            CheckService(!simpleEntity.Equals(true),
                         "User " + newAdmin.ToString() + "was not Removed.");
            //logger.Info("RemoveUser = " + simpleEntity.content);
            return(this);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Returns the data of one forum
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Forum GetForum(Guid id)
        {
            var par = new RestParameters();

            par.Add("name", id.ToString());
            var f = DoRequest <Response <Forum> >("forums/", par);

            if (f.Values.Count > 0)
            {
                return(f.Values[0]);
            }
            return(null);
        }
        public UserService AddAdmin(IUser newAdmin)
        {
            RestParameters urlParameters = new RestParameters()
                                           .AddParameters(RestParametersKeys.Token, user.Token)
                                           .AddParameters(RestParametersKeys.Name, newAdmin.Name)
                                           .AddParameters(RestParametersKeys.Password, newAdmin.Password)
                                           .AddParameters(RestParametersKeys.Rights, ParamTrue);
            SimpleEntity simpleEntity = userResource
                                        .HttpPostAsObject(urlParameters, null, null);

            CheckService(!simpleEntity.Equals(true),
                         "Admin " + newAdmin.ToString() + "was not Added.");
            return(this);
        }
Exemplo n.º 25
0
        public Forum GetForum(string name, string locale)
        {
            var par = new RestParameters();

            par.Add("name", name);
            par.Add("locale", locale);
            var f = DoRequest <Response <Forum> >("forums/", par);

            if (f.Values.Count > 0)
            {
                return(f.Values[0]);
            }
            return(null);
        }
 public UserService AddItems(List <ItemTemplate> itemsTemplate)
 {
     foreach (ItemTemplate item in itemsTemplate)
     {
         RestParameters pathParameters = new RestParameters()
                                         .AddParameters(RestParametersKeys.Index, item.Index);
         RestParameters bodyParameters = new RestParameters()
                                         .AddParameters(RestParametersKeys.Token, user.Token)
                                         .AddParameters(RestParametersKeys.Item, item.Item);
         SimpleEntity simpleEntity = itemResource.HttpPostAsObject(null, pathParameters, bodyParameters);
         CheckService(!simpleEntity.Equals(true),
                      "Item " + item.ToString() + "was not Added.");
     }
     return(this);
 }
        // Entity - - - - - - - - - - - - - - - - - - - -

        public virtual TGET HttpGetAsObject(RestParameters urlParameters, RestParameters pathVariables)
        {
            TGET result = default(TGET);

            try
            {
                result = deserial.Deserialize <TGET>(HttpGetAsResponse(urlParameters, pathVariables));
            }
            catch (Exception ex)
            {
                logger.Error(string.Format(ConvertObjectError, ex.Message, ex.StackTrace));
                throw new Exception(string.Format(ConvertObjectError, ex.Message, ex.StackTrace));
            }
            return(result);
        }
        public virtual TDELETE HttpDeleteAsObject(RestParameters urlParameters,
                                                  RestParameters pathVariables, RestParameters bodyParameters)
        {
            TDELETE result = default(TDELETE);

            try
            {
                result = deserial.Deserialize <TDELETE>(HttpDeleteAsResponse(urlParameters, pathVariables, bodyParameters));
            }
            catch (Exception ex)
            {
                logger.Error(string.Format(ConvertObjectError, ex.Message, ex.StackTrace));
                throw new Exception(string.Format(ConvertObjectError, ex.Message, ex.StackTrace));
            }
            return(result);
        }
        // Business

        public GuestService UnsuccessfulLogin(IUser user)
        {
            RestParameters bodyParameters = new RestParameters()
                                            .AddParameters(RestParametersKeys.Name, user.Name)
                                            .AddParameters(RestParametersKeys.Password, user.Password);

            SimpleEntity simpleEntity = userAuthorizedResource.HttpPostAsObject(null, null, bodyParameters);

            if (simpleEntity.content.Length == LengthToken)
            {
                //logger.Error("Custom exception: entered valid login in UnsuccessfulLogin method");
                throw new Exception("Valid login");
            }
            ResultStatus = "true";
            return(this);
        }
Exemplo n.º 30
0
        public IEnumerable <Thread> GetThreads(Guid forumId, DateTime?from, bool ascending = true, Action <IEnumerable <Thread> > pageResult = null, int?maxPages = null)
        {
            var par = new RestParameters();

            par.Add("forumId", forumId.ToString());
            par.Add("sort", "createdDate");
            par.Add("order", ascending ? "asc" : "desc");
            if (from != null)
            {
                // TODO: Richtiges format!
                var dt = new DateTime(from.Value.Ticks, DateTimeKind.Utc);
                par.Add("contentChangeOrActionFrom", dt.ToString("o"));
            }
            var res = GetAllPages("threads/", par, pageResult, maxPages);

            return(res);
        }