Ejemplo n.º 1
0
        protected override BangoCommand GetSearchCommandTemplate(string selectClause, bool count = false, string tableAlias = null)
        {
            System.Text.StringBuilder Sql = new System.Text.StringBuilder();
            string       alias            = DbServiceUtility.GetTableAliasForTable(tableAlias);
            BangoCommand cmd = new BangoCommand(MyroCommandTypes.SqlBuilder);

            if (count)
            {
                return(base.GetSearchCommandTemplate(selectClause, count, tableAlias));
            }
            else
            {
                cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format(@"
SELECT u.first_name || ' ' || u.last_name as full_name,u.contact_number,u.email from donation_details c
INNER  JOIN donation_request_links r on r.donation_id = c.id
INNER JOIN rbac_user u on u.id=r.requested_user_id 
        /**where**/
        "
                                                                        , selectClause, _model.GetTableName(), alias));
            }
            return(cmd);
        }
Ejemplo n.º 2
0
        public static BangoCommand AppendQueryAsOr(BangoCommand cmd, string query_data, string[] fields)
        {
            string or_query = string.Empty;

            Dapper.DynamicParameters param = new Dapper.DynamicParameters();
            query_data = query_data.ToLower();
            query_data = $"%{query_data}%";
            if (query_data?.Length > 0)
            {
                string[] arr = new string[fields.Length];
                string   tmp = string.Empty;
                for (int i = 0; i < fields.Length; i++)
                {
                    arr[i] = $"LOWER({fields[i]}) like @query";
                }
                or_query = "( " + string.Join(" OR ", arr) + " )";
                //or_query = @LOWER(code) like @query OR LOWER(name_np) like @query OR LOWER(name_en) like @query)";
                param.Add("@query", query_data, System.Data.DbType.AnsiString);
                cmd.SqlBuilder.Where(or_query, param);
            }
            return(cmd);
        }
Ejemplo n.º 3
0
        public override BangoCommand GetItemCommand(DynamicDictionary data_param, string tableAlias = null)
        {
            CheckClientID = false;

            BangoCommand cmd = new BangoCommand();
            UserModel    mdl = new UserModel();

            tableAlias   = tableAlias ?? MainTableAlias;
            cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format(@"select c.*,t1.photo_url name_photo_url,t1.id photo_id,t1.file_name userfilename
                                 from rbac_user c
                                LEFT JOIN tax_photos_files  t1 on (c.id = t1.ref_id)
/**where**/
AND t1.ref_id = @id 
/**orderby**/"
                                                                    , mdl.GetTableName(), tableAlias));

            //PropertyInfo prop = mdl.GetKeyPropertyInfo();
            //cmd.SqlBuilder.Where(string.Format("{0}=@{0}", prop.Name), DbServiceUtility.ToDynamicParameter(prop.Name, data_param.GetValueAsInt("id"), DbServiceUtility.TypeMap[prop.PropertyType]));
            DbServiceUtility.BindDeleteParameter(cmd, mdl, tableAlias);
            DbServiceUtility.BindParameters(cmd, mdl, data_param, tableAlias, SearchTypes.Equal);

            if (CheckClientID)
            {
                PropertyInfo client_id = mdl.GetType().GetProperty("client_id");
                if (client_id != null)
                {
                    DbServiceUtility.BindClientIdParameter(cmd, mdl, tableAlias, DisplayMasterDataFromSystem);
                    //string col = DbServiceUtility.SetColumnAlias(tableAlias, "client_id");
                    //cmd.SqlBuilder.Where("(client_id = 1 OR client_id = @client_id)");
                    //DynamicParameters param = new DynamicParameters();
                    //param.Add("@client_id", SessionData.client_id, DbType.Int32);
                    //cmd.SqlBuilder.AddParameters(param);
                }
            }
            return(cmd);
        }
Ejemplo n.º 4
0
 public override BangoCommand AfterBindingParameter(SearchScenario searchFor, DbConnect con, BangoCommand cmd, DynamicDictionary data_param, bool count = false, string tableAlias = null)
 {
     cmd = base.AfterBindingParameter(searchFor, con, cmd, data_param, count, tableAlias);
     cmd = DbServiceUtility.BindParameters(cmd, new donation_request_links(), data_param, "r");
     return(cmd);
 }
Ejemplo n.º 5
0
 public virtual BangoCommand AfterBindingOrderBy(SearchScenario searchFor, DbConnect con, BangoCommand cmd, DynamicDictionary data_param, bool count = false, string tableAlias = null)
 {
     return(cmd);
 }
Ejemplo n.º 6
0
        public virtual BangoCommand GetSearchCommand(SearchScenario scenario, DbConnect con, BangoCommand cmd, DynamicDictionary data_param, string selectClause, string orderByClause, int page = -1, int pageSize = 20, bool count = false, string tableAlias = null, string scenarioOthers = null)
        {
            TableDetailAttribute tableDetail = _model.GetTableDetail();
            //clear the params whic are empty or null
            List <string> keys = new List <string>(data_param.KeyList.Cast <String>());

            foreach (string key in keys)
            {
                object value = data_param.GetValue(key);
                if (value == null || data_param.GetValueAsString(key).Length == 0)
                {
                    data_param.Remove(key);
                }
            }

            //BangoCommand cmd = GetSearchCommandTemplate(selectClause, count, tableAlias);
            //cmd.Sql.AppendLine("FROM " + model.GetTableName());
            IDbExpression dbExp = App.Container.GetInstance <IDbExpression>();

            if (data_param.GetCount() == 0)
            {
                return(cmd);
            }

            string append = DbServiceUtility.GetTableAliasForColumn(tableAlias);

            if (!(scenario == SearchScenario.TreeNode && count == false))
            {
                //check & adding delete flag check sql
                DbServiceUtility.BindDeleteParameter(cmd, _model, tableAlias);

                if (CheckClientID)
                {
                    DbServiceUtility.BindClientIdParameter(cmd, _model, tableAlias, DisplayMasterDataFromSystem);
                }

                //add remaining default search criteria

                cmd = BeforeBindingParameter(scenario, con, cmd, data_param, count, tableAlias);
                cmd = DbServiceUtility.BindParameters(cmd, _model, data_param, tableAlias);
                cmd = AfterBindingParameter(scenario, con, cmd, data_param, count, tableAlias);

                //check & adding order by clause
                if (count == false)
                {
                    cmd = BeforeBindingOrderBy(scenario, con, cmd, data_param, count, tableAlias);
                    cmd = DbServiceUtility.BindOrderBy(cmd, orderByClause);
                    cmd = AfterBindingOrderBy(scenario, con, cmd, data_param, count, tableAlias);
                    cmd = DbServiceUtility.BindPagination(cmd, page, pageSize);
                }
            }
            return(cmd);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Performs validation of unique-constraints. Detail on the failure are stored in UniqueErrors Property
        /// It will use the help of TModel for performing the unique-constraint check.
        /// </summary>
        /// <param name="item"></param>
        /// <returns>Returns the status of the validation.</returns>
        public virtual bool ValidateUniqueValue(DbConnect con, DynamicDictionary item, IModel validatorModel, bool skipFieldsNotProvided = false)
        {
            /**
             * TODO
             * 1) disable null check or check if unique constraint is not composite constraint
             * 2) check unique constraint in edit mode, load all data
             **/
            PropertyInfo key = validatorModel.GetKeyPropertyInfo();
            TKey         id  = item.GetValue <TKey>(key.Name);

            //if (Conversion.ToInt32(id.ToString()) > 0)
            //    skipFieldsNotProvided = false; //if edit mode checke

            if (validatorModel.GetType().GetProperty("deleted_uq_code") != null) //tod not equal..
            {
                item["deleted_uq_code"] = 1;
            }
            BangoCommand cmd   = new BangoCommand(commandType: MyroCommandTypes.StringBuilder);
            string       union = string.Empty;
            //List<PropertyInfo> uniqueFields = new List<PropertyInfo>();
            DictionaryFx <string, PropertyInfo> uniqueFields = new DictionaryFx <string, PropertyInfo>();
            //preparing sql
            DynamicDictionary data_param = null;

            Bango.Models.Attributes.TableDetailAttribute tabelDetail = validatorModel.GetTableDetail();

            foreach (KeyValuePair <string, UniqueConstraint> unique in validatorModel.UniqueFields)
            {
                if (unique.Value.Fields.Count == 0)
                {
                    continue;
                }

                bool value_not_provided = false;

                foreach (string fld in unique.Value.Fields)
                {
                    if (!item.ContainsKey(fld))
                    {
                        //1) disable null check or check if unique constraint is not composite constraint
                        ///if (unique.Value.Fields.Count <= 1)
                        if (unique.Value.Fields.Count <= 1) //TODO:Shivashwor modify... for client duplicate data insert OFF...
                        {
                            value_not_provided = true;
                            break;
                        }

                        if (!skipFieldsNotProvided)
                        {
                            //If fld name not exists in validatorModel then
                            if (validatorModel.GetValue(fld) == null)
                            {
                                ///item.Add(fld, null);
                                value_not_provided = true;
                            }
                            else
                            {
                                Type t = validatorModel.GetType().GetProperty(fld).PropertyType;

                                if (t.IsValueType)
                                {
                                    item.Add(fld, Activator.CreateInstance(t));
                                }
                                else
                                {
                                    item.Add(fld, null);
                                }
                            }
                        }
                        else
                        {
                            //TODO:Shivashwor modify... for client duplicate data insert OFF...
                            value_not_provided = true;
                        }
                        break;
                    }
                }
                if (value_not_provided)
                {
                    continue;
                }

                data_param = (DynamicDictionary)item.Clone();
                ///TODO:SHIVASHWOR 15 nov 2015 for Unique value is empty or not...
                object data_val = data_param.GetValue(unique.Key);
                if (data_val != null)
                {
                    if (data_val.ToString().Trim().Length == 0)
                    {
                        continue;
                    }
                }

                if (union.Length > 0)
                {
                    cmd.SqlString.AppendLine(union);
                }
                string and = string.Empty;
                cmd.SqlString.AppendLine(String.Format("SELECT distinct '{0}' unique_constraint, '{2}' error_message FROM {1} {3} WHERE 1=1 "
                                                       , DbServiceUtility.SafeDBString(unique.Value.Name), tabelDetail.Name
                                                       , DbServiceUtility.SafeDBString(unique.Value.ErrorMessage)
                                                       , tabelDetail.Alias));
                //CHECKING In if client_id exists in the model for adding the client_id in unique contraint check if the developer has forgot to added
                PropertyInfo prop_client_id = validatorModel.GetType().GetProperty("client_id");
                if (prop_client_id != null)
                {
                    if (!unique.Value.Fields.Contains("client_id"))
                    {
                        unique.Value.Fields.Add("client_id");
                    }
                }
                foreach (string fld in unique.Value.Fields)
                {
                    if (validatorModel.GetType().GetProperty(fld) != null)
                    {
                        DbServiceUtility.BindParameter(cmd, fld, data_param, validatorModel.GetType().GetProperty(fld).PropertyType, tabelDetail.Alias, SearchTypes.Equal | SearchTypes.CaseSensetive, string.Empty, true, validatorModel.GetType().GetProperty(fld));
                    }
                    //cmd.SqlString.AppendFormat(" {1} {0} = @{0}", fld, and);//uniqueFields[fld] = validatorModel.GetType().GetProperty(fld);
                }


                if (key.Name.Trim().Length > 0)//PRIMARY KEY Check if n
                {
                    if (id != null)
                    {
                        //var obj_updateBy = data_param.GetValue("updated_by");

                        //if (obj_updateBy!= null)
                        DbServiceUtility.BindParameter(cmd, key.Name, data_param, System.Data.DbType.Int32, tabelDetail.Alias, SearchTypes.NotEqual, string.Empty, true, key);
                    }
                }

                union = " UNION ALL";
            }

            string finalSql           = cmd.FinalSql;
            IEnumerable <dynamic> lst = null;

            if (finalSql.Length > 0)
            {
                try
                {
                    lst = con.DB.Query <dynamic>(finalSql, cmd.FinalParameters);
                }
                catch (NpgsqlException ex)
                {
                    Errors.Add(ex.ToString());
                    LogTrace.WriteErrorLog(ex.ToString());
                    LogTrace.WriteDebugLog(string.Format("sql which gave exception:\r{0}", ex.Routine));
                    return(false);
                }
                catch (Exception ex)
                {
                }



                //checking for the unique constraint
                if (lst.Count() > 0)
                {
                    foreach (DapperRow dr in lst)
                    {
                        DynamicDictionary dic = Conversion.ToDynamicDictionary(dr);
                        DynamicDictionary err = new DynamicDictionary();
                        err.Add(dic.GetValueAsString("unique_constraint"), dic.GetValue("error_message"));
                        ModelService.PushValidationErros(err, ValidationErrors);
                    }
                    return(false);
                }
            }
            else
            {
                //TODO:Shivashwor 01 Nov 2015/
                //if edit mode nothing changed after save data occurs
                //  throw new NoSqlStringProvidedException();
            }
            return(true);
        }
Ejemplo n.º 8
0
        //public override MyroCommand AfterBindingParameter(SearchScenario searchFor, DbConnect con, MyroCommand cmd, DynamicDictionary data_param, bool count = false, string tableAlias = null)
        //{
        //    //Myro.Base.List.DynamicDictionary sessionData = MyApp.LoadSessionDataForClient();
        //    //string role_id = sessionData.GetValueAsString("assigned_role_ids").Replace("[", "").Replace("]", "").Replace(@"""", "");
        //    User.UserService srvc = new User.UserService();
        //    string role_id = Newtonsoft.Json.JsonConvert.SerializeObject(srvc.LoadAssignedRoles(con, (int)SessionData.user_id)); ;
        //    role_id = role_id.Replace("[", "").Replace("]", "").Replace(@"""", "");

        //    string[] lst_rols = role_id.Split(',');
        //    bool rol_exists = lst_rols.Contains("1"); //not "Administrator"


        //    if (rol_exists==false) //not "Administrator"
        //    {
        //        if (role_id.Trim().Length > 0)
        //            data_param.Add("id", role_id);
        //    }

        //    MyroCommand cmd1 = cmd;

        //    if (data_param.ContainsKey("id"))
        //    {
        //        MyroCommand test = new MyroCommand(MyroCommandTypes.SqlBuilder);

        //        cmd1.Template = test.SqlBuilder.AddTemplate(string.Format(@"
        //                    {0}
        //                    AND c.id IN (WITH RECURSIVE roles(role_id) as (
        //                      SELECT assigned_role_id role_id
        //                            FROM RBAC_USER_ROLES
        //                            where is_deleted = false AND status = true AND user_id = {1}
        //                     UNION ALL
        //                      SELECT c.assigned_role_id role_id
        //                      FROM rbac_role_roles as  c
        //                       JOIN roles nd ON c.role_id = nd.role_id
        //                                    AND c.is_deleted = false AND c.status = true
        //                    )
        //                    SELECT DISTINCT role_id FROM roles ) ", cmd.FinalSql.Replace("@status", "true"),  SessionData.user_id ));
        //    }

        //    //Todo:Pending Task 01 Jun 2016 Shivashwor ...
        //    //cmd1 = DbServiceUtility.BindParameter(cmd, _model.GetType().GetProperty("id"), data_param, "c", SearchTypes.IN_Search); //IS NOT NULL
        //    return cmd1;
        //}

        public override BangoCommand AfterBindingParameter(SearchScenario searchFor, DbConnect con, BangoCommand cmd, DynamicDictionary data_param, bool count = false, string tableAlias = null)
        {
            //Myro.Base.List.DynamicDictionary sessionData = MyApp.LoadSessionDataForClient();
            //string role_id = sessionData.GetValueAsString("assigned_role_ids").Replace("[", "").Replace("]", "").Replace(@"""", "");
            User.UserService srvc    = new User.UserService();
            string           role_id = Newtonsoft.Json.JsonConvert.SerializeObject(srvc.LoadAssignedRoles(con, (int)SessionData.user_id));;

            role_id = role_id.Replace("[", "").Replace("]", "").Replace(@"""", "");

            string[] lst_rols   = role_id.Split(',');
            bool     rol_exists = lst_rols.Contains("1"); //not "Administrator"


            if (rol_exists == false) //not "Administrator"
            {
                if (role_id.Trim().Length > 0)
                {
                    data_param.SetValue("id", role_id);
                }
            }

            BangoCommand cmd1 = cmd;

            if (data_param.ContainsKey("id"))
            {
                // data_param.Remove("id");
                BangoCommand test = new BangoCommand(MyroCommandTypes.SqlBuilder);
                cmd1.Template = cmd1.SqlBuilder.AddTemplate(string.Format(@"  
                            {0} 
                            AND c.id >= (WITH RECURSIVE roles(role_id) as (
		                            SELECT assigned_role_id role_id 
                                    FROM RBAC_USER_ROLES 
                                    where is_deleted = false AND status = true AND user_id = {1}
	                            UNION ALL
		                            SELECT c.assigned_role_id role_id
		                            FROM rbac_role_roles as  c			
			                            JOIN roles nd ON c.role_id = nd.role_id
                                            AND c.is_deleted = false AND c.status = true
                            )
                            SELECT DISTINCT role_id FROM roles ) ", cmd.FinalSql.Replace("@status", "true"), SessionData.user_id));


                ///  cmd1.FinalParameters.AddDynamicParams(cmd.FinalParameters.ParameterNames);
            }

            //Todo:Pending Task 01 Jun 2016 Shivashwor ...
            //cmd1 = DbServiceUtility.BindParameter(cmd, _model.GetType().GetProperty("id"), data_param, "c", SearchTypes.IN_Search); //IS NOT NULL
            return(cmd1);
        }
 public override BangoCommand GetSearchCommand(SearchScenario scenario, DbConnect con, BangoCommand cmd, DynamicDictionary data_param, string selectClause, string orderByClause, int page = -1, int pageSize = 20, bool count = false, string tableAlias = null, string scenarioOthers = null)
 {
     if (SessionData.client_id == 1)
     {
         CheckClientID = false;
     }
     return(base.GetSearchCommand(scenario, con, cmd, data_param, selectClause, orderByClause, page, pageSize, count, tableAlias, scenarioOthers));
 }
Ejemplo n.º 10
0
 public override BangoCommand BeforeBindingParameter(SearchScenario searchFor, DbConnect con, BangoCommand cmd,
                                                     DynamicDictionary data_param, bool count = false, string tableAlias = null)
 {
     return(base.BeforeBindingParameter(searchFor, con, cmd, data_param, count, tableAlias));
 }
Ejemplo n.º 11
0
        public override BangoCommand GetSearchCommand(SearchScenario scenario, DbConnect con, BangoCommand cmd,
                                                      DynamicDictionary data_param, string selectClause, string orderByClause, int page = -1, int pageSize = 20,
                                                      bool count = false, string tableAlias = null, string scenarioOthers = null)
        {
            if (SessionData.client_id == 1)
            {
                CheckClientID = false;
            }
            var cmd1 = base.GetSearchCommand(scenario, con, cmd, data_param, selectClause, orderByClause, page, pageSize,
                                             count, tableAlias, scenarioOthers);

            //assigned_roles_id1
            if (data_param.ContainsKey("assigned_roles_id1"))
            {
                var SQLl = string.Format(@"
                    SELECT  distinct  r.user_id FROM RBAC_USER_ROLES r
                    left join rbac_role_roles rr on r.assigned_role_id = rr.role_id
                    LEFT JOIN RBAC_USER_ROLES rs on rs.id = rr.assigned_role_id
                    where r.assigned_role_id={0} ", data_param.GetValueAsInt("assigned_roles_id1"));

                cmd1.SqlBuilder.Where(string.Format("  c.ID NOT IN ({0}) ", SQLl));
            }
            else if (data_param.ContainsKey("assigned_roles_id"))
            {
                var SQLl = string.Format(@"
                    SELECT  distinct  r.user_id FROM RBAC_USER_ROLES r
                    left join rbac_role_roles rr on r.assigned_role_id = rr.role_id
                    LEFT JOIN RBAC_USER_ROLES rs on rs.id = rr.assigned_role_id
                    where r.assigned_role_id={0} ", data_param.GetValueAsInt("assigned_roles_id"));

                cmd1.SqlBuilder.Where(string.Format("  c.ID IN ({0}) ", SQLl));
            }
            //assigned_rights_id1
            if (data_param.ContainsKey("assigned_rights_id1"))
            {
                var SQLl = string.Format(@"
            SELECT distinct  ur.user_id
            FROM RBAC_USER_RIGHTS ur 
	            INNER JOIN RBAC_RIGHTS_MASTER rm ON ur.ASSIGNED_RIGHT_ID = rm.id
            WHERE  ur.is_deleted = false 
            AND ur.status = true and ur.ASSIGNED_RIGHT_ID = {0} ", data_param.GetValueAsInt("assigned_rights_id1"));

                cmd1.SqlBuilder.Where(string.Format("  c.ID NOT IN ({0}) ", SQLl));
            }
            else if (data_param.ContainsKey("assigned_right_id"))
            {
                var SQLl = string.Format(@"
            SELECT distinct  ur.user_id
            FROM RBAC_USER_RIGHTS ur 
	            INNER JOIN RBAC_RIGHTS_MASTER rm ON ur.ASSIGNED_RIGHT_ID = rm.id
            WHERE  ur.is_deleted = false 
            AND ur.status = true and ur.ASSIGNED_RIGHT_ID = {0} ", data_param.GetValueAsInt("assigned_right_id"));

                cmd1.SqlBuilder.Where(string.Format("  c.ID IN ({0}) ", SQLl));
            }

            return(cmd1);
        }
Ejemplo n.º 12
0
        public override BangoCommand AfterBindingParameter(SearchScenario searchFor, DbConnect con, BangoCommand cmd,
                                                           DynamicDictionary data_param, bool count = false, string tableAlias = null)
        {
            //MyroCommand cm = null; // base.AfterBindingParameter(searchFor, con, cmd, data_param, count, tableAlias);
            //if (data_param.ContainsKey("assigned_roles_id1"))
            //    cm = DbServiceUtility.BindParameter(cmd, _model.GetType().GetProperty("assigned_roles_id"), data_param, "c", SearchTypes.NotEqual);

            return(base.AfterBindingParameter(searchFor, con, cmd, data_param, count, tableAlias));
        }
Ejemplo n.º 13
0
        public ResponseAuth AuthenticateUserNamePasword(DbConnect con, int client_id, string username, string password)
        {
            ResponseAuth resp     = new ResponseAuth();
            string       template = @"
                SELECT id, client_id, username, password, name_en, name_np,email, status
                FROM rbac_user u
                /**where**/
                AND u.status=true AND u.is_deleted=false";
            //creating command & preparing command
            string       alias = DbServiceUtility.GetTableAliasForTable("u");
            BangoCommand cmd   = new BangoCommand(MyroCommandTypes.SqlBuilder);

            cmd.Template = cmd.SqlBuilder.AddTemplate(template);
            UserModel mdl = new UserModel();

            DbServiceUtility.BindDeleteParameter(cmd, mdl, alias);
            DynamicDictionary data_param = new DynamicDictionary();

            data_param.Add("client_id", client_id);
            data_param.Add("username", username);
            DbServiceUtility.BindParameters(cmd, mdl, data_param, alias, SearchTypes.Equal);

            //executing the command
            string finalSql = cmd.FinalSql;

            if (finalSql.Length > 0)
            {
                IEnumerable <SqlMapper.DapperRow> items = null;
                try
                {
                    items = con.DB.Query <SqlMapper.DapperRow>(finalSql, cmd.FinalParameters, true);
                }
                catch (Npgsql.NpgsqlException ex)
                {
                    LogTrace.WriteErrorLog(ex.ToString());
                    LogTrace.WriteDebugLog(string.Format("Select SQL which gave exception:\r{0}", ex.Routine));
                }

                Errors = con.DB.GetErros();
                if (items != null && items.Count() > 0)
                {
                    DynamicDictionary data = Conversion.ToDynamicDictionary(items.FirstOrDefault());
                    if (data.GetValueAsString("password") == EncryptPassword(password))
                    {
                        resp.success = true;
                        resp.user_id = data.GetValueAsInt("id");
                        resp.email   = data.GetValueAsString("email");
                        resp.message = "Login successfull";
                    }
                    else
                    {
                        resp.message = "Username and/or Password is invalid.";
                    }
                }
                else
                {
                    if (Errors.Count > 0)
                    {
                        resp.message = "Technical Problem occurred.";
                    }
                    else
                    {
                        resp.message = "Please provide a valid Username.";
                    }
                }
            }

            return(resp);
        }
Ejemplo n.º 14
0
        public virtual BangoCommand GetTreeNodeCommandTemplate(int start_node_id, bool count = false, string tableAlias = null, string sort_by = null)
        {
            string alias                 = DbServiceUtility.GetTableAliasForTable(tableAlias),
                   columnAlias           = DbServiceUtility.GetTableAliasForColumn(tableAlias);
            BangoCommand cmd             = new BangoCommand(MyroCommandTypes.SqlBuilder);
            string       start_condition = string.Empty;

            TModel       model = new TModel();
            string       secondary_condition = string.Empty;
            PropertyInfo delFlag             = Models.ModelService.GetDeleteFieldProperty(model);

            if (delFlag != null)
            {
                start_condition = "c." + delFlag.Name + " = false";
            }

            PropertyInfo field_client_id = model.GetType().GetProperty("client_id");

            if (field_client_id != null)
            {
                start_condition += string.Format(" AND (c.client_id = 1 OR c.client_id = {0})", SessionData.client_id);
            }

            secondary_condition = start_condition;

            if (start_node_id == 0)
            {
                start_condition += string.Format(" AND COALESCE(c.parent_id,0) = {0}", start_node_id);
            }
            else
            {
                start_condition += string.Format(" AND c.id = {0}", start_node_id);
            }

            if (count)
            {
                cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format(@"
SELECT count(1) total_records 
FROM {0} {1}
/**where**/ "
                                                                        , _model.GetTableName(), alias));
            }
            else
            {
                cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format(@"
WITH RECURSIVE nodes(id, code, name_np, name_en, parent_id
        , node_path, parent_node_path, node_level) as(
	SELECT
		{3}id, {3}code, {3}name_np, {3}name_en, {3}parent_id
        --, null::text parent_code, null::text parent_name_np, null::text parent_name_en
		--, c.parent_id, p.code parent_code, p.name_np parent_name_np, p.name_en parent_name_en
		, ARRAY[{3}id], ARRAY[{3}id], 1
	FROM {0} {2}
	WHERE
		{1}
	UNION ALL

	SELECT
		{3}id, {3}code, {3}name_np, {3}name_en, {3}parent_id
        --, p.code parent_code, p.name_np parent_name_np, p.name_en parent_name_en
		, node_path || c.id, node_path, nd.node_level + 1
	FROM {0} {2}
		JOIN {0} p  ON c.parent_id = p.id
		JOIN nodes nd ON p.id = nd.id
    WHERE
        {4}
)

SELECT array_to_string(node_path , '-') node_path, array_to_string(parent_node_path , '-') parent_node_path, id node_id, code, name_np
    , name_en, parent_id, node_level , code || ' - ' || name_np || ' - ' || name_en as text
FROM nodes
order by node_path
/**where**/ 
/**orderby**/"
                                                                        , _model.GetTableName(), start_condition, alias, columnAlias, secondary_condition));
            }
            return(cmd);
        }