示例#1
0
        static void Main(string[] args)
        {
            Dictionary <string, object> dictionary = new Dictionary <string, object>();

            DynamicDictionary <int, string> myDictionary = new DynamicDictionary <int, string>();

            myDictionary.Add(37, "Kastamonu");
            Console.WriteLine(myDictionary.Count);

            myDictionary.Add(37, "Kastamonu");

            Console.WriteLine(myDictionary.Count);

            myDictionary.Add(01, "Adana");
            myDictionary.Add(34, "Istanbul");

            Console.WriteLine(myDictionary.Count);
            foreach (var kvp in myDictionary.MyKeyandValuePairs)
            {
                Console.WriteLine(kvp.Key + "-->" + kvp.Value);
            }

            foreach (var key in myDictionary.GetKeys)
            {
                Console.WriteLine($"Key --> {key}");
            }
            foreach (var values in myDictionary.GetValues)
            {
                Console.WriteLine($"Value --> {values}");
            }
        }
示例#2
0
        public override ResponseModel Insert(DbConnect con, DynamicDictionary item)
        {
            AssignedUserRightsModel model = new AssignedUserRightsModel();

            if (model.GetType().GetProperty("client_id") != null)
            {
                object      rights_user = item.GetValue("assigned_right_ids");
                IEnumerable enumerable  = rights_user as IEnumerable;
                if (enumerable != null)
                {
                    foreach (object element in enumerable)
                    {
                        object aa = element;
                        if (item.GetValueAsInt("client_id") == null)
                        {
                            item.Add("client_id", SessionData.client_id);
                        }
                        else
                        {
                            item.Add("client_id", item.GetValueAsInt("client_id"));
                        }
                        item.Add("assigned_right_id", aa);
                        base.Insert(con, item);
                    }
                }
            }
            ResponseModel Assigned_right_user = new ResponseModel();

            Assigned_right_user.success = true;
            Assigned_right_user.message = "Data Successfully Added.";
            return(Assigned_right_user);
        }
示例#3
0
        public HomeModule(ITransient transient, IRequestScoped requestScoped) : base("/home")
        {
            _transient     = transient;
            _requestScoped = requestScoped;
            Debug.Assert(_requestScoped == _transient.RequestScoped);

            Get["/"] = _ =>
            {
                var viewBag = new DynamicDictionary();
                viewBag.Add("Transient", _transient);
                viewBag.Add("RequestScoped", _requestScoped);
                return(View["home/index", viewBag]);
            };

            Get["/index", runAsync : true] = async(_, token) =>
            {
                await Task.Delay(1000);

                return("123");
            };

            Get["/list", runAsync : true] = async(_, token) =>
            {
                await Task.Delay(1);

                return(500);
            };

            Get["/edit", runAsync : true] = async(_, token) =>
            {
                await Task.Delay(1);

                return(404);
            };
        }
        // GET: TotalCount
        public ResponseModel Get()
        {
            ResponseModel resp = new ResponseModel();
            BangoCommand  cmd  = new BangoCommand(MyroCommandTypes.SqlBuilder);

            cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format($@"                     
                 select count(id) as total_donation_details from donation_details"));
            BangoCommand cmd_total_charities = new BangoCommand(MyroCommandTypes.SqlBuilder);

            cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format($@"                     
                 select count(id) as total_charities_events  from charities_events_details"));
            //BangoCommand cmd_total_volunters = new BangoCommand(MyroCommandTypes.SqlBuilder);
            //cmd.Template = cmd.SqlBuilder.AddTemplate(string.Format($@"
            //     select count(id) as total_donation_details from donation_details"));
            IEnumerable <dynamic> total_donation_details = null;
            IEnumerable <dynamic> total_charities_event  = null;

            using (DbConnect con = new DbConnect())
            {
                total_donation_details = con.DB.Query(cmd.FinalSql.ToString(), null);
                total_charities_event  = con.DB.Query(cmd_total_charities.FinalSql.ToString(), null);
            }
            DynamicDictionary dic = new DynamicDictionary();

            dic.Add("total_donation_details", total_donation_details);
            dic.Add("total_donation_details", total_charities_event);
            resp.data = dic;
            return(resp);
        }
示例#5
0
        public HomeModule(ITransient transient, IRequestScoped requestScoped)
            : base("/home")
        {
            _transient = transient;
            _requestScoped = requestScoped;
            Debug.Assert(_requestScoped == _transient.RequestScoped);

            Get["/"] = _ =>
            {
                var viewBag = new DynamicDictionary();
                viewBag.Add("Transient", _transient);
                viewBag.Add("RequestScoped", _requestScoped);
                return View["home/index", viewBag];
            };

            Get["/index", runAsync: true] = async (_, token) =>
            {
                await Task.Delay(1000);
                return "123";
            };

            Get["/list", runAsync: true] = async (_, token) =>
            {
                await Task.Delay(1);
                return 500;
            };

            Get["/edit", runAsync: true] = async (_, token) =>
            {
                await Task.Delay(1);
                return 404;
            };
        }
示例#6
0
        public override ResponseModel Insert(DbConnect con, DynamicDictionary item)
        {
            UserModel model = new UserModel();

                        //setting the client_id before inserting record if client_id field exists.
                        if(model.GetType().GetProperty("client_id") != null)
            {
                if (item.GetValueAsInt("client_id") == null)
                {
                    item.Add("client_id", SessionData.client_id);
                }
                else
                {
                    item.Add("client_id", item.GetValueAsInt("client_id"));
                }
            }

            string new_file_name = item.GetValueAsString("new_file_name");

            if (new_file_name != "")
            {
                string reltive_path = "temp/";
                item.SetValue("photo_path", reltive_path + new_file_name);
            }
            ResponseModel resp = base.Insert(con, item);

            if (resp.success)
            {
                int user_id = (int)((DynamicDictionary)resp.data).GetValueAsInt("id");
                resp.data = user_id;
                return(resp);
            }
            return(resp);
        }
        public DynamicDictionary PushErrors(List <string> errorList)
        {
            int cnt = 1;

            foreach (string s in errorList)
            {
                errors.Add(cnt.ToString(), s);
            }
            return(errors);
        }
示例#8
0
        public void AddNotNullItems()
        {
            const string VALUE = "Hello";
            const string NAME  = "Joe";

            _dictionary.Add(VALUE, nameof(VALUE));
            Assert.Contains(_dictionary.ToDictionary(), kvp => kvp.Key == nameof(VALUE) && (string)kvp.Value == "Hello");

            _dictionary.Add(NAME, nameof(NAME), NAME);
            Assert.Contains(_dictionary.ToDictionary(), kvp => kvp.Key == nameof(NAME) && (string)kvp.Value == "Joe");
        }
示例#9
0
        public DynamicDictionary ValidateToken(DbConnect con, string token, int user_id)
        {
            DynamicDictionary data        = new DynamicDictionary();
            SessionLogService sessionSrvc = new SessionLogService();

            DynamicDictionary data_param = new DynamicDictionary();

            data_param.Add("token", token);
            data_param.Add("user_id", user_id);
            data = sessionSrvc.CrudRepo.Get(con, data_param);

            return(data);
        }
示例#10
0
        public virtual ResponseAuth Authenticate(int client_id, string username, string password)
        {
            //validate if data is passed with all 3 parameters.
            ResponseAuth resp = new ResponseAuth();

            if (client_id < 1)
            {
                resp.message = "Please select a Client.";
                return(resp);
            }
            if (username.Trim().Length == 0)
            {
                resp.message = "Please enter a Username.";
                return(resp);
            }
            if (password.Trim().Length == 0)
            {
                resp.message = "Please enter a Password.";
                return(resp);
            }
            //var usermodel = Bango.Container.GetInstance<IUserModel>();
            //UserService<UserModel, int?> userSrvc = (UserService<UserModel, int?>)Bango.Container.GetInstance(typeof(IUserService<UserModel, int?>));
            var userSrvc = GetUserServiceInstance();

            using (DbConnect con = new DbConnect())
            {
                resp = userSrvc.AuthenticateUserNamePasword(con, client_id, username, password);
                //generate token
                string token = string.Empty;
                if (resp.success)
                {
                    token = GenerateToken();
                }
                resp.token = token;
                //save data in session & generate
                SessionLogService sessionSrvc = new SessionLogService();
                DynamicDictionary data_param  = new DynamicDictionary();
                data_param.Add("client_id", client_id);
                data_param.Add("user_id", resp.user_id);
                DateTime login_datetime = DateTime.Now;
                data_param.Add("login_datetime", login_datetime);
                data_param.Add("expire_datetime", GetExpirtyDateTime(login_datetime));
                data_param.Add("token", token);

                sessionSrvc.Insert(con, data_param);
                //SessionLogModel
            }

            return(resp);
        }
示例#11
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);
        }
示例#12
0
        public override 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();
            return(cmd);
        }
示例#13
0
        public HttpResponseMessage GetFile()
        {
            int?   client_id = SessionData.client_id;
            object filePaths = "";

            if (Directory.Exists($@"D:\ERP\ERP\ERP-MunTax\ERP-MunTax\ERP.Tax.EndPoint\filebox\CommonInput\logo\{client_id}") == true)
            {
                filePaths = Directory.GetFiles($@"D:\ERP\ERP\ERP-MunTax\ERP-MunTax\ERP.Tax.EndPoint\filebox\CommonInput\logo\{client_id}");
            }
            DynamicDictionary data = new DynamicDictionary();
            ResponseModel     resp = new ResponseModel(false, data);

            data.Add("temp_file_url", filePaths);
            try
            {
                resp.success = true;
                resp.message = "Files successfully loaded.";
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(resp))
                });
            }
            catch (System.Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
示例#14
0
        public virtual DynamicDictionary Get(DbConnect con, TKey id)
        {
            DynamicDictionary data_param = new DynamicDictionary();
            TModel            mdl        = new TModel();

            data_param.Add(mdl.GetKeyPropertyName(), id);
            dynamic item = Get(con, data_param);

            if (item != null)
            {
                return(item);
            }
            else
            {
                TModel itm = GetAsModel(con, id);
                if (itm == null)
                {
                    return(null);
                }
                else
                {
                    return(Models.ModelService.ToDictionary(itm));
                }
            }
        }
示例#15
0
        public static List <DynamicDictionary> ToDictionaryListFromJson(string jsonString)
        {
            List <DynamicDictionary> paraList = new List <DynamicDictionary>();

            if (jsonString != string.Empty)
            {
                Object obj = JsonConvert.DeserializeObject(jsonString);
                if (obj is JArray)
                {
                    JArray arr = ((JArray)obj);
                    for (int i = 0, len = arr.Count; i < len; i++)//JObject o in arr)
                    {
                        DynamicDictionary dic = new DynamicDictionary();
                        JObject           o   = (JObject)arr[i];

                        if (o.HasValues)
                        {
                            JToken item = o.First;
                            do
                            {
                                string key = ((Newtonsoft.Json.Linq.JProperty)item).Name;
                                //dic.Add(item.Path, o.Value<object>(item.Path).ToString());
                                dic.Add(key, o.GetValue(key).ToString());
                                //Console.WriteLine(item.Path + " => " + item.ToString());
                                item = item.Next;
                            } while (item != null);
                        }
                        paraList.Add(dic);
                    }
                }
            }
            return(paraList);
        }
        public void TestAddKeyValuePair()
        {
            var d = new DynamicDictionary();

            d.Add(new KeyValuePair <string, object>("foo", "bar"));

            Assert.AreEqual("bar", d["foo"]);
        }
示例#17
0
        public void Test_get_cards_by_filter()
        {
            DynamicDictionary query = new DynamicDictionary();

            query.Add("name", "Ankh of Mishra");
            Card[] cards = repository.GetCards(query).Result;
            Assert.Greater(cards.Length, 1);
        }
 public WebConfiguration()
 {
     _settings = new DynamicDictionary();
     foreach (string k in ConfigurationManager.AppSettings.AllKeys)
     {
         _settings.Add(k, ConfigurationManager.AppSettings[k]);
     }
 }
        public void TestContainsKeyValuePairThatDoesNotExists()
        {
            var d = new DynamicDictionary();

            d.Add("foo", "bar");

            Assert.IsFalse(d.Contains(new KeyValuePair <string, object>("key", "value")));
        }
        public void TestAdd()
        {
            var d = new DynamicDictionary();

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

            Assert.AreEqual("value", d["key"]);
        }
        public void TestContainsKey()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.ContainsKey("key"), "Did not contain key: \"key\"");
        }
示例#22
0
        public void Test_get_cards_by_filter ()
        {
            DynamicDictionary query = new DynamicDictionary(); 

            query.Add ("name", "Ankh of Mishra");
            Card[] cards = repository.GetCards (query).Result;
            Assert.Greater (cards.Length,1);
        }
        public void TestRemove()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.Remove("key"), "Did not remove key: \"key\"");
        }
        public void TestContainsKey()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.ContainsKey("key"), "Did not contain key: \"key\"");
        }
        public void TestAdd()
        {
            var d = new DynamicDictionary();

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

            Assert.AreEqual("value", d["key"]);
        }
        public void DynamicDictionary_EventsTests()
        {
            DynamicDictionary d = new DynamicDictionary();

            int countAdd     = 0;
            int countRemove  = 0;
            int countChanged = 0;
            int countClear   = 0;
            int countOther   = 0;

            d.OnChange += (sender, e) =>
            {
                switch (e.EventType)
                {
                case DynamicDictionaryChangedType.AddedValue:
                    countAdd++;
                    break;

                case DynamicDictionaryChangedType.RemovedValue:
                    countRemove++;
                    break;

                case DynamicDictionaryChangedType.ChangedValue:
                    countChanged++;
                    break;

                case DynamicDictionaryChangedType.Clear:
                    countClear++;
                    break;

                default:
                    countOther++;
                    break;
                }
            };

            d["1"] = "Main";
            Assert.AreEqual(1, countAdd);

            d["1"] = "Main";
            Assert.AreEqual(0, countChanged);

            d["2"] = "New";
            Assert.AreEqual(2, countAdd);

            d["2"] = "Test";
            Assert.AreEqual(1, countChanged);

            d.Add("3", "Name");
            Assert.AreEqual(3, countAdd);

            d.Remove("3");
            Assert.AreEqual(1, countRemove);

            d.Clear();
            Assert.AreEqual(1, countClear);
            Assert.AreEqual(0, countOther);
        }
示例#27
0
        public static DynamicDictionary ToDictionary(DataRow dr)
        {
            DynamicDictionary row = new DynamicDictionary();

            foreach (DataColumn col in dr.Table.Columns)
            {
                row.Add(col.ColumnName.ToLower(), dr[col]);
            }
            return(row);
        }
        public void BaseArticleRevaluationServiceTest_UpdateByDeltasDictionary_And_EmptyExistingIndicatorList_Must_Add_All_From_DeltasDictionary()
        {
            // Assign
            var d0101 = new DateTime(DateTime.Now.Year, 1, 1);
            var d0201 = new DateTime(DateTime.Now.Year, 1, 2);
            var d0301 = new DateTime(DateTime.Now.Year, 1, 3);

            var deltasInfo = new DynamicDictionary <DateTime, decimal>();

            deltasInfo.Add(d0101, 100.15M);
            deltasInfo.Add(d0201, 150.25M);
            deltasInfo.Add(d0301, 500.45M);

            exactArticleRevaluationIndicatorRepository.Setup(x => x.GetFrom(d0101, storageId, accountOrganizationId))
            .Returns(new List <ExactArticleRevaluationIndicator>());

            // для проверки созданных показателей
            var createdIndicators = new List <ExactArticleRevaluationIndicator>();

            // получение созданных показателей
            GetCreatedIndicators(createdIndicators);

            // Act
            baseArticleRevaluationIndicatorService.Update(deltasInfo, storageId, accountOrganizationId);

            // Assert
            Assert.AreEqual(3, createdIndicators.Count);

            var firstIndicator = createdIndicators.FirstOrDefault(x => x.StartDate == d0101 && x.EndDate == d0201 && x.RevaluationSum == 100.15M &&
                                                                  x.StorageId == storageId && x.AccountOrganizationId == accountOrganizationId && x.PreviousId == null);

            Assert.IsNotNull(firstIndicator);

            var secondIndicator = createdIndicators.FirstOrDefault(x => x.StartDate == d0201 && x.EndDate == d0301 && x.RevaluationSum == 250.40M &&
                                                                   x.StorageId == storageId && x.AccountOrganizationId == accountOrganizationId && x.PreviousId == firstIndicator.Id);

            Assert.IsNotNull(secondIndicator);

            var thirdIndicator = createdIndicators.FirstOrDefault(x => x.StartDate == d0301 && x.EndDate == null && x.RevaluationSum == 750.85M &&
                                                                  x.StorageId == storageId && x.AccountOrganizationId == accountOrganizationId && x.PreviousId == secondIndicator.Id);

            Assert.IsNotNull(thirdIndicator);
        }
        public void TestClearNonEmptyList()
        {
            var d = new DynamicDictionary();

            d.Add(new KeyValuePair <string, object>("foo", "bar"));

            d.Clear();

            Assert.AreEqual(0, d.Count);
        }
        public void TestRemoveKeyValuePair()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.Remove(new KeyValuePair <string, object>("key", "value")));

            Assert.AreEqual(0, d.Count);
        }
        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);
        }
示例#32
0
        protected virtual DynamicDictionary GetQueryAsDictionary()
        {
            DynamicDictionary dic = new DynamicDictionary();

            foreach (KeyValuePair <string, string> item in Request.GetQueryNameValuePairs())
            {
                dic.Add(item.Key, (object)item.Value);
            }
            return(dic);
        }
示例#33
0
        public static DynamicDictionary ToDynamic <T>(this T @object, bool inherit = true)
        {
            var dynDic = new DynamicDictionary();

            foreach (var property in @object.GetType().GetInstanceProperties(inherit))
            {
                dynDic.Add(property.Name, property.GetValue(@object, null));
            }
            return(dynDic);
        }
示例#34
0
        /// <summary>
        /// Proxy ile mevcut dictionary i istediğimiz kurallarca veriyoruz.
        /// </summary>
        /// <returns></returns>
        public override DynamicDictionary GetDictionary()
        {
            var proxyDictionary = new DynamicDictionary();

            foreach (var item in DynamicProperties)
            {
                proxyDictionary.Add(GetKeyNameProxy(item.Key), GetValue(item.Key));
            }

            return(Sort(proxyDictionary));
        }
        public void Should_add_value_when_invoking_keyvaluepair_overload_of_add_method()
        {
            // Given
            var input = new DynamicDictionary();

            // When
            input.Add(new KeyValuePair<string, dynamic>("test", 10));
            var value = (int)input["test"];

            // Then
            value.ShouldEqual(10);
        }
        public void Should_add_value_when_invoking_string_dynamic_overload_of_add_method()
        {
            // Given
            var input = new DynamicDictionary();

            // When
            input.Add("test", 10);
            var value = (int)input["test"];

            // Then
            value.ShouldEqual(10);
        }
        public object Deserialize( BsonDeserializationContext context, BsonDeserializationArgs args )
        {
            var bsonReader = context.Reader;
            BsonType bsonType = bsonReader.CurrentBsonType;

            object result;

            if( bsonType == BsonType.Null )
            {
                bsonReader.ReadNull();
                result = null;
            }
            else
            {
                if( bsonType == BsonType.Document )
                {
                    var dictionary = new DynamicDictionary();

                    bsonReader.ReadStartDocument();

                    IDiscriminatorConvention valueDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention( typeof( object ) );

                    while( bsonReader.ReadBsonType() != BsonType.EndOfDocument )
                    {
                        string key = bsonReader.ReadName();
                        Type valueType = valueDiscriminatorConvention.GetActualType( bsonReader, typeof( object ) );
                        IBsonSerializer valueSerializer = BsonSerializer.LookupSerializer( valueType );
                        object value = valueSerializer.Deserialize( context );

                        if( key != "_t" )
                        {
                            dictionary.Add( key.Replace( '\x03', '.' ), value );
                        }
                    }
                    bsonReader.ReadEndDocument();
                    result = dictionary;
                }
                else
                {
                    string message = string.Format( "Can't deserialize a {0} from BsonType {1}.", context.Reader.CurrentBsonType, bsonType );
                    throw new BsonException( message );
                }
            }

            return result;
        }
示例#38
0
        private dynamic DownloadReportResults(dynamic args)
        {
            var requestId = new Guid(args.id);

            var allResults = reportResultService.GetAllResults(requestId);
            var colNameLookup = allResults.FieldColumns.ToDictionary(x => x.FieldId, x => String.Format(FieldNameFormat, x.FieldName, x.UnitName));

            return allResults.Rows.Select(x =>
            {
                var row = new DynamicDictionary();
                row.Add("Date Recorded", x.RowDateTime.ToString(RowDateFormat));
                row.Add("Site Name", x.SiteName);

                foreach (var field in x.Fields)
                {
                    row.Add(colNameLookup[field.FieldId], field.Value);
                }

                return row;
            });
        }
        public void TestClearNonEmptyList()
        {
            var d = new DynamicDictionary();

            d.Add(new KeyValuePair<string, object>("foo", "bar"));

            d.Clear();

            Assert.AreEqual(0, d.Count);
        }
        public void TestAddKeyValuePair()
        {
            var d = new DynamicDictionary();

            d.Add(new KeyValuePair<string, object>("foo", "bar"));

            Assert.AreEqual("bar", d["foo"]);
        }
        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_return_dynamic_objects_as_objects()
        {
            //Given
            var input = new DynamicDictionary();
            input.Add("Test", new { Title = "Fred", Number = 123 });

            //When
            var result = input.ToDictionary();

            //Then
            Assert.Equal("Fred", ((dynamic)result["Test"]).Title);
            Assert.Equal(123, ((dynamic)result["Test"]).Number);
        }
示例#43
0
        /// <summary>
        /// Renders the view.
        /// </summary>
        /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance, containing information on how to get the view template.</param>
        /// <param name="model">The model that should be passed into the view</param>
        /// <param name="renderContext"></param>
        /// <returns>A response</returns>
        public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext)
        {
            Template parsed;
            Hash hashedModel;
            HttpStatusCode status;

            try
            {
                // Set the parsed template
                parsed = renderContext.ViewCache.GetOrAdd(
                    viewLocationResult,
                    x => Template.Parse(viewLocationResult.Contents.Invoke().ReadToEnd()));

                hashedModel = Hash.FromAnonymousObject(new
                {
                    Model = new DynamicDrop(model),
                    ViewBag = new DynamicDrop(renderContext.Context.ViewBag)
                });

                // If we got past that, we have a good response
                status = HttpStatusCode.OK;

            }
            catch (SyntaxException syntaxException)
            {
                // Syntax Exceptions cause a 500
                status = HttpStatusCode.InternalServerError;

                // Build the error message
                String errorMessage = String.Format("Syntax error in liquid view '{0}':\r\n\r\n{1}",
                    String.Format("{0}/{1}.{2}", viewLocationResult.Location, viewLocationResult.Name, viewLocationResult.Extension),
                    syntaxException.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair<string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                    {
                        Model = new DynamicDrop(errorModel)
                    });

                // Grab the error HTML from the embedded resource and build up the DotLiquid template.
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }
            catch (Exception ex)
            {
                status = HttpStatusCode.InternalServerError;
                // Build the error message
                String errorMessage = String.Format("Error: {0}", ex.Message);

                // Create the error model with a Nancy DynamicDictionary because i can ;)
                DynamicDictionary errorModel = new DynamicDictionary();
                errorModel.Add(new KeyValuePair<string, dynamic>("ErrorMessage", errorMessage));

                // Hash up the Error model so DotLiquid will understand it
                hashedModel =
                    Hash.FromAnonymousObject(new
                    {
                        Model = new DynamicDrop(errorModel)
                    });

                // Grab the error HTML from the embedded resource
                String errorHtml = LoadResource(@"500.liquid");
                parsed = Template.Parse(errorHtml);
            }

            // Build the response
            return new HtmlResponse(statusCode: status, contents: stream =>
            {
                parsed.Render(stream, new RenderParameters
                {
                    LocalVariables = hashedModel,
                    Registers = Hash.FromAnonymousObject(new { nancy = renderContext })
                });
            });
        }
        public void TestTryGetValueKeyExists()
        {
            var d = new DynamicDictionary();

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

            object value;

            Assert.IsTrue(
                d.TryGetValue("key", out value), 
                "Expected true to trying to get a value for an existing key.");

            Assert.AreEqual("value", value);
        }
        public void TestGetEnumerator()
        {
            var d = new DynamicDictionary();

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

            IEnumerator enumerator = d.GetEnumerator();

            int count = 0;
            while (enumerator.MoveNext())
            {
                var pair = (KeyValuePair<string, object>) enumerator.Current;

                Assert.AreEqual("key", pair.Key);
                Assert.AreEqual("value", pair.Value);

                count += 1;
            }

            Assert.AreEqual(1, count, "Enumerator did not move through the right number of items.");
        }
        public void TestRemoveKeyValuePair()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.Remove(new KeyValuePair<string, object>("key", "value")));

            Assert.AreEqual(0, d.Count);
        }
        public void TestCount()
        {
            var d = new DynamicDictionary();

            Assert.AreEqual(0, d.Count);

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

            Assert.AreEqual(1, d.Count);

            d.Remove("key");

            Assert.AreEqual(0, d.Count);
        }
        public void TestCopyToKeyValuePair()
        {
            var d = new DynamicDictionary();

            d.Add("foo", "bar");

            var array = new KeyValuePair<string, object>[d.Count];

            d.CopyTo(array, 0);

            KeyValuePair<string, object> pair = array[0];

            Assert.AreEqual("foo", pair.Key);
            Assert.AreEqual("bar", pair.Value);
        }
        public void TestContainsKeyValuePairThatDoesNotExists()
        {
            var d = new DynamicDictionary();

            d.Add("foo", "bar");

            Assert.IsFalse(d.Contains(new KeyValuePair<string, object>("key", "value")));
        }
示例#50
0
        private dynamic ViewReportResults(dynamic args)
        {
            var requestId = new Guid(args.id);

            var results = reportResultService.GetResultsPage(requestId, Context.RequestedPage());

            var columns = results.FieldColumns.Select(x => new { name = String.Format(FieldNameFormat, x.FieldName, x.UnitName), id = x.FieldId }).ToList();
            columns.Insert(0, new { name = "Date Recorded", id = "DateRecorded" });
            columns.Insert(1, new { name = "Site Name", id = "SiteName" });

            var pagedResult = new
            {
                ReportName = results.ReportName,
                Count = results.Count,
                Pages = results.Pages,
                Columns = columns,
                Rows = results.Rows.Select(x =>
                {
                    var row = new DynamicDictionary();
                    row.Add("DateRecorded", x.RowDateTime.ToString(RowDateFormat));
                    row.Add("SiteName", x.SiteName);

                    foreach (var field in x.Fields)
                    {
                        row.Add(field.FieldId, field.Value);
                    }

                    return row;
                })
            };

            return pagedResult;
        }
        public void TestRemove()
        {
            var d = new DynamicDictionary();

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

            Assert.IsTrue(d.Remove("key"), "Did not remove key: \"key\"");
        }