Esempio n. 1
0
        public virtual BangoCommand GetGridFilterItemsCommand(DbConnect con, DynamicDictionary data_param, int page = -1, int pageSize = 20, string sort_by = null, bool count = false)
        {
            sort_by = sort_by == null ? string.Empty : sort_by;
            ComboFieldsAttribute comboAttrib = _model.GetComoFields();

            if (sort_by.Trim().Length == 0 && comboAttrib.OrderBy.Length > 0)
            {
                sort_by = DbServiceUtility.SetColumnAlias(TableDetail.Alias, comboAttrib.OrderBy);
            }
            BangoCommand cmd = GetGridFilterItemsCommandTemplate(comboAttrib.ToString(), count, TableDetail.Alias);

            cmd = GetSearchCommand(SearchScenario.GridFilter, con, cmd, data_param, comboAttrib.ToString()
                                   , sort_by, page, pageSize, count, TableDetail.Alias);
            //adding the query clause
            string or_query = string.Empty;

            Dapper.DynamicParameters param = new Dapper.DynamicParameters();
            if (data_param.ContainsKey("q") || data_param.ContainsKey("query"))
            {
                string query = data_param.GetValueAsString("q");
                if (query.Trim().Length == 0)
                {
                    query = data_param.GetValueAsString("query");
                }
                AppendQueryAsOr(cmd, query, new string[] { "code", "name_np", "name_en" });
            }
            return(cmd);
        }
        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);
        }
Esempio n. 3
0
        public bool IsValidSession(DbConnect con, string token, int user_id)
        {
            if (!App.CheckToken)
            {
                return(true);
            }
            DynamicDictionary tokenDetail = GetTokenDetail(token, user_id);

            if (tokenDetail == null || tokenDetail.GetCount() == 0)
            {
                return(false);
            }
            if (tokenDetail.ContainsKey("expire_datetime"))
            {
                if (!String.IsNullOrEmpty(tokenDetail["expire_datetime"].ToString()))
                {
                    DateTime expiryDate   = Convert.ToDateTime(tokenDetail["expire_datetime"]);
                    DateTime current_date = DateTime.Now;
                    TimeSpan difference   = expiryDate - current_date;
                    if (difference.TotalMinutes < 0)
                    {
                        Status = AuthorizationStatus.SessionExpired;
                        return(false);
                    }
                    else
                    {
                        SessionData.client_id = tokenDetail.GetValueAsInt("client_id");
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 4
0
        public void LoadFromDynamicDictionary(DynamicDictionary item)
        {
            ModelBase           model = this;
            PropertyInfo        prop;
            List <PropertyInfo> FieldList = model.GetFieldList();

            for (int i = 0, len = FieldList.Count; i < len; i++)
            {
                prop = FieldList[i];
                if (item.ContainsKey(prop.Name.Trim().ToLower()))
                {
                    if (item[prop.Name.Trim().ToLower()] == null)
                    {
                        prop.SetValue(model, null);
                    }
                    else
                    {
                        try
                        {
                            //prop.SetValue(model, ModelService.ChangeType(item[prop.Name.Trim().ToLower()], prop.PropertyType));
                            prop.SetValue(model, ModelService.ChangeType(item.GetValue(prop.Name.Trim().ToLower()), prop.PropertyType));
                        }
                        catch (Exception ex)
                        {
                            prop.SetValue(model, null);
                        }
                    }
                }
            }
        }
Esempio n. 5
0
        public static DynamicDictionary PushValidationErros(DynamicDictionary soruce, DynamicDictionary destination)
        {
            foreach (string s in soruce.KeyList)
            {
                if (destination.ContainsKey(s))
                {
                    List <string> msgs = new List <string>();
                    if (destination.GetValue(s).GetType() == typeof(List <string>))
                    {
                        msgs = (List <string>)destination.GetValue(s); //soruce
                    }
                    else
                    {
                        msgs.Add(destination.GetValue(s).ToString());
                    }

                    if (soruce.GetValue(s).GetType() == typeof(List <string>))
                    {
                        List <string> n = (List <string>)soruce.GetValue(s);
                        msgs.AddRange(n);
                    }
                    else
                    {
                        msgs.Add(soruce.GetValue(s).ToString());
                    }
                    destination.SetValue(s, msgs);
                }
                else
                {
                    destination.Add(s, soruce.GetValue(s));
                }
            }
            return(destination);
        }
        public void TestContainsKey()
        {
            var d = new DynamicDictionary();

            d.Add("key", "value");

            Assert.IsTrue(d.ContainsKey("key"), "Did not contain key: \"key\"");
        }
Esempio n. 7
0
        public void Should_remove_item_when_string_overload_of_remove_method_is_invoked()
        {
            // Given
            var input = new DynamicDictionary();

            input["test"] = 10;

            // When
            input.Remove("test");

            // Then
            input.ContainsKey("test").ShouldBeFalse();
        }
Esempio n. 8
0
        public void Should_remove_item_when_keyvaluepair_overload_of_remove_method_is_invoked()
        {
            // Given
            var input = new DynamicDictionary();

            input["test"] = 10;

            // When
            input.Remove(new KeyValuePair <string, dynamic>("test", 10));

            // Then
            input.ContainsKey("test").ShouldBeFalse();
        }
Esempio n. 9
0
        public void Should_remove_natural_key()
        {
            // Given
            var input = new DynamicDictionary();

            input.Add("a-b-c", "hello");

            //when
            input.Remove("a-b-c");

            //then
            input.ContainsKey("abc").ShouldBeFalse();
        }
Esempio n. 10
0
        public void Should_return_correct_value_for_containskey(string key, bool expectedResult)
        {
            // Given
            var input = new DynamicDictionary();

            input["test1"] = 10;

            // When
            var result = input.ContainsKey(key);

            // Then
            result.ShouldEqual(expectedResult);
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
        public BaseResponse HangleGetHydrantsByGeobox(DynamicDictionary _parameters)
        {
            var response = new BaseResponse {
                Success = false
            };
            User user;

            if (AuthHelper.IsAuthorized(Request, out user))
            {
                HydrantWikiManager hwm = new HydrantWikiManager();

                double east  = Convert.ToDouble((string)_parameters["east"]);
                double west  = Convert.ToDouble((string)_parameters["west"]);
                double north = Convert.ToDouble((string)_parameters["north"]);
                double south = Convert.ToDouble((string)_parameters["south"]);

                int quantity = 250;
                if (_parameters.ContainsKey("quantity"))
                {
                    quantity = Convert.ToInt32((string)_parameters["quantity"]);
                }
                if (quantity > 500)
                {
                    quantity = 500;
                }

                GeoBox geobox = new GeoBox(east, west, north, south);

                List <Hydrant> hydrants = hwm.GetHydrants(geobox, quantity);

                List <HydrantHeader> headers = ProcessHydrants(hydrants);

                response = new HydrantQueryResponse {
                    Success = true, Hydrants = headers
                };

                hwm.LogInfo(user.Guid, "Retrieved Hydrants by Geobox");

                return(response);
            }
            else
            {
                LogUnauthorized(Request);
            }

            return(response);
        }
Esempio n. 13
0
        public virtual BangoCommand GetComboItemsCommand(DbConnect con, DynamicDictionary data_param, int page = -1, int pageSize = 20, string sort_by = null, bool count = false)
        {
            sort_by = sort_by == null ? string.Empty : sort_by;

            ComboFieldsAttribute comboAttrib = _model.GetComoFields();

            if (sort_by.Trim().Length == 0 && comboAttrib.OrderBy.Length > 0)
            {
                sort_by = DbServiceUtility.SetColumnAlias(TableDetail.Alias, comboAttrib.OrderBy);
            }

            BangoCommand cmd = GetCombotItemsCommandTemplate(comboAttrib.ToString(), count, TableDetail.Alias);

            if (comboAttrib.Status != null || comboAttrib.Status.Length > 0)
            {
                data_param.Add(comboAttrib.Status, true); //for Combo Status=True mains Active Recors load in ComboBOx
            }
            cmd = GetSearchCommand(SearchScenario.Combo, con, cmd, data_param, comboAttrib.ToString()
                                   , sort_by, page, pageSize, count, TableDetail.Alias);


            //adding the query clause
            string or_query = string.Empty;

            Dapper.DynamicParameters param = new Dapper.DynamicParameters();
            if (data_param.ContainsKey("query"))
            {
                string query = data_param.GetValueAsString("query");
                if (query != null && query.Trim().Length > 0)
                {
                    var      q            = query;
                    string[] arr          = q.Split('-');
                    string   searchParams = arr[0].ToString().Trim();
                    //string name = arr[1].ToString();
                    AppendQueryAsOr(cmd, searchParams, new string[] { "code", "name_np", "name_en" });
                }
                else
                {
                    AppendQueryAsOr(cmd, query, new string[] { "code", "name_np", "name_en" });
                }
                //query = data_param.GetValueAsString("query");
            }

            return(cmd);
        }
        protected bool AuthenticationFromDB(HttpActionContext actionContext, string token, int user_id)
        {
            if (!App.CheckToken)
            {
                return(true);
            }
            IAuthService      authSrvc    = App.Container.GetInstance <Rbac.IAuthService>();
            DynamicDictionary tokenDetail = authSrvc.GetTokenDetail(token, user_id);

            if (tokenDetail == null || tokenDetail.GetCount() == 0)
            {
                Status = AuthorizationStatus.NotLoggedIn;
                return(false);
            }
            if (tokenDetail.ContainsKey("expire_datetime"))
            {
                if (!String.IsNullOrEmpty(tokenDetail["expire_datetime"].ToString()))
                {
                    DateTime expiryDate   = Convert.ToDateTime(tokenDetail["expire_datetime"]);
                    DateTime current_date = DateTime.Now;
                    TimeSpan difference   = expiryDate - current_date;
                    if (difference.TotalMinutes < 0)
                    {
                        Status = AuthorizationStatus.SessionExpired;
                        return(false);
                    }
                    else
                    {
                        int?session_id = tokenDetail.GetValueAsInt("id");
                        _client_id            = (int)tokenDetail.GetValueAsInt("client_id");
                        SessionData.client_id = _client_id;
                        DynamicDictionary data_param = new DynamicDictionary();
                        data_param.Add("expire_datetime", AuthService.GetExpirtyDateTime(DateTime.Now));
                        data_param.Add("id", session_id);
                        SessionLogService logSrvc = new SessionLogService();
                        logSrvc.Update(session_id, data_param);
                        Status = AuthorizationStatus.Authorized;
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 15
0
        private Negotiator GetTagMap(DynamicDictionary _parameters)
        {
            if (_parameters != null &&
                _parameters.ContainsKey("Guid") &&
                GuidHelper.IsValidGuidString(_parameters["Guid"]))
            {
                Context.ViewBag.MapBoxMap = Config.GetSettingValue("MapBoxMap");
                Context.ViewBag.MapBoxKey = Config.GetSettingValue("MapBoxKey");

                Guid tagGuid = new Guid(_parameters["Guid"]);

                HydrantWikiManager hwm = new HydrantWikiManager();

                Tag tag = hwm.GetTag(tagGuid);

                return(View["popupmap.sshtml", tag]);
            }

            return(null);
        }
Esempio n. 16
0
        public string GetLang(string file, string key)
        {
            string            val  = "";
            DynamicDictionary temp = null;

            try
            {
                temp = (DynamicDictionary)Lang.GetValue(file);
                if (temp != null)
                {
                    if (temp.ContainsKey(key.ToLower()))
                    {
                        val = temp.GetValue(key.ToLower()).ToString();
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return(val);
        }
Esempio n. 17
0
        /// <summary>
        /// Performs validation on the data passed in item based on the model passed in validatorModel. The developer can use the third parameter ony fields passed need to be validated.
        /// </summary>
        /// <param name="item">Dictionary with data which needed to be validated.</param>
        /// <param name="validatorModel">The model based on which the data validation is performed.</param>
        /// <param name="skipFieldsNotProvided">if only fields which are passed in [item] dictionary has to be validated then set it to true else all fields in model is validated. Default is false.</param>
        /// <returns>Returns true if validation is ok else false</returns>
        public virtual bool Validate(DynamicDictionary item, IModel validatorModel, bool skipFieldsNotProvided = false)
        {
            validatorModel.LoadFromDynamicDictionary(item);
            var context = new ValidationContext(validatorModel, serviceProvider: null, items: null);

            validatorModel.ValidationResult = new List <ValidationResult>();

            var isValid = Validator.TryValidateObject(validatorModel, context, validatorModel.ValidationResult, validateAllProperties: true);

            if (!isValid)
            {
                if (skipFieldsNotProvided)
                {
                    for (int vCnt = validatorModel.ValidationResult.Count - 1; vCnt >= 0; vCnt--)
                    {
                        List <string> members = validatorModel.ValidationResult[vCnt].MemberNames.ToList();
                        for (int mCnt = members.Count - 1; mCnt >= 0; mCnt--)
                        {
                            if (!item.ContainsKey(members[mCnt].Trim().ToLower()))
                            {
                                members.RemoveAt(mCnt);
                            }
                        }
                        if (members.Count == 0)
                        {
                            validatorModel.ValidationResult.RemoveAt(vCnt);
                        }
                    }
                    if (validatorModel.ValidationResult.Count == 0)
                    {
                        isValid = true;
                    }
                }
            }
            return(isValid);
        }
        public List <DynamicDictionary> PivotTheData(List <DynamicDictionary> sourceData)
        {
            DynamicDictionary disc = sourceData[0];
            string            mov  = disc.GetValueAsString("mov").ToUpper().Trim();

            try
            {
                SummaryOfData.Clear();
                //manage or prepare distict of the values
                double val = 0;
                string valx = string.Empty, valy = string.Empty;
                for (int i = 0, len = sourceData.Count; i < len; i++)
                {
                    valx = sourceData[i].GetValueAsString(ColumnX.Name1);
                    valy = sourceData[i].GetValueAsString(ColumnY.Name2) + sourceData[i].GetValueAsString(ColumnY.Name1);
                    val  = sourceData[i].GetValue <Double>(ColumnValue);

                    PivotData pd = GetPivotData(valx, valy);
                    pd.Value = CalculateSummary(pd.Value, val);
                }
                List <DynamicDictionary> dt = FinalPivotDictionary;
                double tot = 0;
                //now put the data in DataTable
                foreach (string y in yKeys)
                {
                    if (y.Trim().Length == 0)
                    {
                        continue;
                    }
                    IEnumerable <PivotData> yRows = SummaryOfData.Where(d => d.ValueY == y);
                    DynamicDictionary       dr    = new DynamicDictionary();
                    //prepare the row/record
                    dr[ColumnY.Name1] = y;
                    PivotValue pv_y = SummaryOfY[y];
                    foreach (PivotData pd in yRows)
                    {
                        val           = GetCellData(pd.Value, ColumnY.SummaryGroupFunction);
                        dr[pd.ValueX] = val;
                        //calculate summary of Y
                        pv_y = CalculateSummary(pv_y, val);
                    }
                    foreach (string x in xKeys)
                    {
                        if (!dr.ContainsKey(x))
                        {
                            dr[x] = string.Empty;
                        }
                    }
                    tot = GetCellData(pv_y, ColumnY.SummaryGroupFunction);
                    dr[ColumnY.SummaryLabel] = tot;
                    //
                    dt.Add(dr);
                    //also calculating the grand total
                    GrandTotal += tot;

                    //Calculate total for arr and dep
                    if (mov == "DEP")
                    {
                        DepTotal = GrandTotal;
                    }
                    else
                    {
                        ArrTotal = GrandTotal - DepTotal;
                    }
                }
                DepTotal = GrandTotal;
                //calculate the summary of X
                if (ColumnY.CalculateSummary)
                {
                    DynamicDictionary dr = new DynamicDictionary();
                    dr[ColumnY.Name1] = ColumnX.SummaryLabel;
                    foreach (string x in xKeys)
                    {
                        IEnumerable <PivotData> xRows = SummaryOfData.Where(d => d.ValueX == x);
                        PivotValue pv_x = SummaryOfX[x];
                        foreach (PivotData pd in xRows)
                        {
                            pv_x = CalculateSummary(pv_x, GetCellData(pd.Value, ColumnX.SummaryGroupFunction));
                        }
                        dr[x] = GetCellData(pv_x, ColumnX.SummaryGroupFunction);
                    }
                    if (ColumnX.CalculateSummary)
                    {
                        dr[ColumnX.SummaryLabel] = mov == "ARR" ? ArrTotal : DepTotal;
                    }
                    dt.Add(dr);
                }
                return(dt);
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
        public bool CheckChangeChanges(TModel oldData, DynamicDictionary newData)
        {
            HasChanges = false;
            var s = Snapshotter.Start(oldData);

            //start observer
            Diff          = new DynamicParameters();
            ChangedValues = new ExpandoObject();
            //merge new data into old data
            ModelService srvc         = new ModelService();
            TModel       oldDataClone = new TModel();

            srvc.CopyProperty(oldData, oldDataClone);
            List <string> ignoreFields = GetIgnoreFields(ActivityType);
            //bool status = srvc.Merge<TModel>(newData, oldData, GetIgnoreFields(ActivityType));
            //changes
            //Diff = s.Diff();
            List <Dictionary <string, object> > changed_values = new List <Dictionary <string, object> >();

            try
            {
                foreach (PropertyInfo prop in oldData.GetType().GetProperties())
                {
                    if (ignoreFields.Contains <string>(prop.Name))
                    {
                        continue;
                    }
                    if (!newData.ContainsKey(prop.Name))
                    {
                        continue;
                    }
                    string newValue = newData.GetValue(prop.Name) == null ? string.Empty : newData.GetValue(prop.Name).ToString();
                    string oldValue = prop.GetValue(oldData) == null ? string.Empty : prop.GetValue(oldData).ToString();

                    if (newValue != oldValue)
                    {
                        //setting the changed value in property for saving
                        //storing data for saving in change history.
                        HasChanges = true;
                        Dictionary <string, object> row = new Dictionary <string, object>();
                        row.Add("field_name", prop.Name);
                        row.Add("old_value", oldDataClone.GetType().GetProperty(prop.Name).GetValue(oldDataClone));
                        //row.Add("new_value", newData.GetType().GetProperty(prop.Name).GetValue(newData));
                        row.Add("new_value", newData.GetValue(prop.Name));
                        changed_values.Add(row);
                        prop.SetValue(oldData, ModelService.ChangeType(newData.GetValue(prop.Name), prop.PropertyType));
                    }
                }
            }
            catch (Exception ex)
            {
                Bango.Base.Log.LogTrace.WriteErrorLog(ex.ToString());
                throw new Exception("Error while tracking changes.");
            }

            if (HasChanges)
            {
                Changes.table_name        = ModelService.GetTableName(oldData);
                Changes.changed_values    = JsonConvert.SerializeObject(changed_values);
                Changes.activity_datetime = DateTime.Now;
                Changes.user_id           = SessionData.user_id;
                Changes.activity_type     = ActivityType.ToString();
                Changes.os_computer_name  = HttpRequestHelper.GetClientHostName();
                Changes.os_ipaddress      = HttpRequestHelper.GetClientIpAddress();
                Changes.os_useragent      = HttpRequestHelper.GetClientBrowser();
                // Changes.pkey_name = Changes.GetKeyPropertyInfo().Name;
            }
            Diff = s.Diff();
            return(HasChanges);
        }
Esempio n. 20
0
        public virtual bool Insert(DbConnect con, DynamicDictionary data)
        {
            //create empty object
            TModel empty = new TModel();
            ChangeHistoryHelper <TModel> chngHlpr = null;

            chngHlpr = new ChangeHistoryHelper <TModel>(AuditActivityTypes.INSERT);
            PropertyInfo key = Models.ModelService.GetKeyPropertyInfo(empty);

            if (data.ContainsKey(key.Name))
            {
                data.Remove(key.Name);
            }
            //if CREATED_BY, CREATED_on field exists then update those fields
            PropertyInfo by = empty.GetType().GetProperty("created_by");

            if (by != null)
            {
                data.SetValue("created_by", SessionData.user_id);
            }
            PropertyInfo on = empty.GetType().GetProperty("created_on");

            if (on != null)
            {
                data.SetValue("created_on", DateTime.Now);
            }
            if (CheckClientID)
            {
                PropertyInfo client_id = empty.GetType().GetProperty("client_id");
                if (client_id != null)
                {
                    if (!data.ContainsKey("client_id"))
                    {
                        data.SetValue("client_id", SessionData.client_id);
                    }
                }
            }

            chngHlpr.CheckChangeChanges(new TModel(), data);
            ITable <TModel, int?> tbl = con.GetModelTable <TModel>();
            int?id = null;

            try
            {
                id = tbl.Insert(chngHlpr.Diff);
                //set the primary key in the object

                if (key != null)
                {
                    data.SetValue(key.Name, id);
                }

                if (TrackChanges)
                {
                    // chngHlpr.Changes.pkey_value = Convert.ToString(id);
                    //save the changes
                    chngHlpr.LogChanges(con);
                }
            }
            catch (Npgsql.NpgsqlException ex)
            {
                LogTrace.WriteErrorLog(ex.ToString());
                LogTrace.WriteDebugLog(string.Format("sql which gave exception:\r{0}", ex.Routine));
                throw ex;
            }
            if (id > 0)
            {
                return(true);
            }
            return(false);
        }
Esempio n. 21
0
        public async Task <HttpResponseMessage> PostFile()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string temp_root = FileBox.GetWebAppRoot() + "temp\\" + SessionData.client_id + "\\";
            string temp_url  = "//temp//" + SessionData.client_id + "//";

            if (!System.IO.Directory.Exists(temp_root))
            {
                System.IO.Directory.CreateDirectory(temp_root);
            }

            MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(temp_root);
            DynamicDictionary data = new DynamicDictionary();
            ResponseModel     resp = new ResponseModel(false, data);

            try
            {
                StringBuilder sb = new StringBuilder(); // Holds the response body
                // Read the form data and return an async task.
                var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);

                //rename the file to proper-name

                // This illustrates how to get the form data.
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        data.Add(key, val);
                    }
                }

                //for logo upload
                string logo_name = data.GetValueAsString("logo_name");
                string extension = string.Empty;

                if (logo_name != "")
                {
                    #region for logo upload
                    string basePath = FileBox.GetWebAppRoot() + "filebox\\CommonInput\\logo\\" + SessionData.client_id + "\\";
                    if (!System.IO.Directory.Exists(basePath))
                    {
                        System.IO.Directory.CreateDirectory(basePath);
                    }

                    //check if file already exist and delete if exist
                    string[] Logo_path = Directory.GetFiles(basePath, logo_name + ".*");
                    string[] filepath  = Directory.GetFiles(basePath, "*.*");
                    if (Logo_path.Length > 0)
                    {
                        System.IO.File.Delete(Logo_path[0]);
                    }
                    //check if file already exist and delete if exist

                    foreach (var file in provider.FileData)
                    {
                        string[] arr = file.Headers.ContentDisposition.FileName.Trim('"').Split('.');
                        if (arr.Length >= 1)
                        {
                            extension = "." + arr[arr.Length - 1];
                        }

                        System.IO.File.Move(file.LocalFileName, basePath + logo_name + extension);
                        data.Add("temp_file_url", basePath + logo_name + extension);
                    }
                    #endregion
                }
                else
                {
                    string url = HttpContext.Current.Request.Url.ToString().Substring(0, HttpContext.Current.Request.Url.ToString().IndexOf("/api/"));
                    // This illustrates how to get the file names for uploaded files.
                    string new_file_name = "";  // System.DateTime.Today.ToString("yyyymmddhhmmss") + "_" + getRandomID() + "_" + SessionData.user_id;
                    foreach (var file in provider.FileData)
                    {
                        FileInfo fileInfo = new FileInfo(file.LocalFileName);
                        string[] arr      = file.Headers.ContentDisposition.FileName.Trim('"').Split('.');

                        if (arr.Length >= 1)
                        {
                            extension = "." + arr[arr.Length - 1];
                        }

                        new_file_name = fileInfo.Name;

                        if (data.ContainsKey("temp_file_path"))
                        {
                            data.SetValue("temp_file_path", temp_root + new_file_name + extension);
                        }
                        else
                        {
                            data.Add("temp_file_path", temp_root + new_file_name + extension);
                        }

                        if (data.ContainsKey("file_name"))
                        {
                            data.SetValue("file_name", new_file_name + extension);
                        }
                        else
                        {
                            data.Add("file_name", new_file_name + extension);
                        }

                        //mime_type_id
                        if (data.ContainsKey("mime_type_id"))
                        {
                            data.SetValue("mime_type_id", extension);
                        }
                        else
                        {
                            data.Add("mime_type_id", extension);
                        }

                        if (data.ContainsKey("file_size_bytes"))
                        {
                            data.SetValue("file_size_bytes", fileInfo.Length);
                        }
                        else
                        {
                            data.Add("file_size_bytes", fileInfo.Length);
                        }

                        data.Add("temp_file_url", url + temp_url + new_file_name + extension);
                        data.Add("temp_file_url", temp_url + new_file_name + extension);

                        System.IO.File.Move(file.LocalFileName, temp_root + new_file_name + extension);
                    }
                }
                resp.success = true;
                resp.message = "File uploaded successfully";
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(resp))
                });
            }
            catch (System.Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
        public void Should_return_correct_value_for_containskey(string key, bool expectedResult)
        {
            // Given
            var input = new DynamicDictionary();
            input["test1"] = 10;

            // When
            var result = input.ContainsKey(key);

            // Then
            result.ShouldEqual(expectedResult);
        }
        public void Should_remove_natural_key()
        {
            // Given
            var input = new DynamicDictionary();
            input.Add("a-b-c", "hello");

            //when
            input.Remove("a-b-c");

            //then
            input.ContainsKey("abc").ShouldBeFalse();
        }
        public void Should_remove_item_when_string_overload_of_remove_method_is_invoked()
        {
            // Given
            var input = new DynamicDictionary();
            input["test"] = 10;

            // When
            input.Remove("test");

            // Then
            input.ContainsKey("test").ShouldBeFalse();
        }
        public void Should_remove_item_when_keyvaluepair_overload_of_remove_method_is_invoked()
        {
            // Given
            var input = new DynamicDictionary();
            input["test"] = 10;

            // When
            input.Remove(new KeyValuePair<string, dynamic>("test", 10));

            // Then
            input.ContainsKey("test").ShouldBeFalse();
        }
Esempio n. 26
0
        private static IEnumerable <Production <SYMBOL_ENUM, TREE_NODE> > unfoldErrorProductions_NOT_USED(StringRep <SYMBOL_ENUM> symbolsRep,
                                                                                                          IEnumerable <Production <SYMBOL_ENUM, TREE_NODE> > productions,
                                                                                                          SYMBOL_ENUM eofSymbol, SYMBOL_ENUM syntaxErrorSymbol)
        {
            var result          = new Productions <SYMBOL_ENUM, TREE_NODE>(symbolsRep, productions, eofSymbol, syntaxErrorSymbol, s => { });
            var new_productions = new List <Production <SYMBOL_ENUM, TREE_NODE> >();

            // compute all non-terminals that serve as aliases for terminals
            // alias is a symbol that can be substituted by single terminal, for example
            // a := A | B (this is alias)
            // a := A B (this is not an alias)
            // we start with terminals, because they serve as aliases too (to themselves)
            DynamicDictionary <SYMBOL_ENUM, HashSet <SYMBOL_ENUM> > term_aliases = result.Terminals
                                                                                   .Select(it => Tuple.Create(it, new HashSet <SYMBOL_ENUM>(new[] { it })))
                                                                                   .ToDefaultDynamicDictionary();

            // this is not cover set algorithm!
            while (true)
            {
                int count = term_aliases.Count;

                foreach (SYMBOL_ENUM non_term in result.NonTerminals.Where(it => !term_aliases.ContainsKey(it)))
                {
                    bool found = true;

                    foreach (Production <SYMBOL_ENUM, TREE_NODE> prod in result.FilterByLhs(non_term))
                    {
                        if (prod.RhsSymbols.Count != 1 || !term_aliases.ContainsKey(prod.RhsSymbols.Single()))
                        {
                            found = false;
                            break;
                        }
                    }

                    if (found)
                    {
                        term_aliases[non_term].AddRange(result.FilterByLhs(non_term).Select(it => term_aliases[it.RhsSymbols.Single()]).Flatten());
                    }
                }

                if (count == term_aliases.Count)
                {
                    break;
                }
            }

            // check the placement of error token in every error production
            foreach (Production <SYMBOL_ENUM, TREE_NODE> prod in productions)
            {
                IEnumerable <SYMBOL_ENUM> error_symbols = prod.RhsSymbols.Where(it => it.Equals(result.SyntaxErrorSymbol));
                if (error_symbols.Any())
                {
                    new_productions.Add(prod);
                }
                else if (error_symbols.Count() > 1)
                {
                    throw new ArgumentException("Only one syntax error token per production: " + prod.PositionDescription);
                }
                else
                {
                    int idx = prod.RhsSymbols.IndexOf(result.SyntaxErrorSymbol);
                    if (idx != prod.RhsSymbols.Count - 2)
                    {
                        throw new ArgumentException("Syntax error token has to be next to last: " + prod.PositionDescription);
                    }
                    SYMBOL_ENUM recovery_symbol = prod.RhsSymbols[idx + 1];
                    if (!term_aliases.ContainsKey(recovery_symbol))
                    {
                        throw new ArgumentException("There has to be a terminal or alias non-terminal after syntax error token: " + prod.PositionDescription);
                    }
                    else if (result.NonTerminals.Contains(recovery_symbol))
                    {
                        foreach (SYMBOL_ENUM term in term_aliases[recovery_symbol])
                        {
                            new_productions.Add(new Production <SYMBOL_ENUM, TREE_NODE>(
                                                    symbolsRep,
                                                    prod.LhsNonTerminal,
                                                    prod.Recursive,
                                                    prod.RhsSymbols.SkipTail(1).Concat(term), // replacing aliased terminal
                                                    prod.UserAction,
                                                    prod.IdentityOuterFunctionParamIndex));
                        }
                    }
                    else
                    {
                        new_productions.Add(prod);
                    }
                }
            }

            return(new_productions);
        }
        public void TestContainsKey()
        {
            var d = new DynamicDictionary();

            d.Add("key", "value");

            Assert.IsTrue(d.ContainsKey("key"), "Did not contain key: \"key\"");
        }
Esempio n. 28
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);
        }