コード例 #1
0
        /// <summary>
        /// Fetches all ds data using ds.search.
        /// FetchDSCompleted event will not be fired.
        /// </summary>
        /// <param name="uid">The user Id.</param>
        public ExpandoObject SearchAll(string uid)
        {
            if (_dsSettings == null)
            {
                return(null);
            }

            var model = new Dictionary <string, object>();

            foreach (var mappingType in _dsSettings.MappingsByType)
            {
                var fields = mappingType.Value.Select(i => i.GigyaFieldName).Distinct();
                var data   = Search(uid, mappingType.Key, fields);
                if (data != null)
                {
                    // do some merge of the data
                    Dictionary <string, object> mappedDsResult = MapDataToDsType(mappingType.Key, data);
                    model = DynamicUtils.MergeToDictionary(model, mappedDsResult);
                }
            }

            if (!model.Any())
            {
                return(null);
            }

            return(model.ToExpando());
        }
コード例 #2
0
        /// <summary>
        /// Fetches ds data using ds.get
        /// FetchDSCompleted event will not be fired.
        /// </summary>
        /// <param name="uid">The user Id.</param>
        /// <param name="settings">The mapping settings.</param>
        /// <returns></returns>
        public ExpandoObject GetAll(string uid)
        {
            if (_dsSettings == null)
            {
                return(null);
            }

            var model = new Dictionary <string, object>();

            foreach (var mappingType in _dsSettings.MappingsByType)
            {
                var dsType = mappingType.Key;
                foreach (var mapping in mappingType.Value.GroupBy(i => i.Custom.Oid))
                {
                    var fields = mapping.Select(i => i.GigyaFieldName).Distinct();
                    var data   = Get(uid, mapping.Key, dsType, fields);

                    if (data != null)
                    {
                        Dictionary <string, object> mappedDsResult = MapDataToDsType(mappingType.Key, data);
                        model = DynamicUtils.MergeToDictionary(model, mappedDsResult);
                    }
                }
            }

            if (!model.Any())
            {
                return(null);
            }

            return(model.ToExpando());
        }
コード例 #3
0
        public void ToExpando_can_convert_dictionary_containing_collection_properties()
        {
            // Arrange
            var dict = new Dictionary <string, object>()
            {
                { "Key1", Guid.NewGuid() },
                {
                    "Key2", new Collection <string>()
                    {
                        Guid.NewGuid().ToString(),
                Guid.NewGuid().ToString(),
                    }
                },
                { "Key3", Guid.NewGuid() },
            };

            // Act
            dynamic expando = dict.ToExpando();

            // Assert
            ((object)expando).ShouldNotBeNull();
            ((object)expando.Key1).ShouldBe(dict["Key1"]);
            ((object)expando.Key2).ShouldBe(dict["Key2"]);
            ((object)expando.Key3).ShouldBe(dict["Key3"]);
            ((object)expando.Key2[0]).ShouldBe(((Collection <string>)dict["Key2"])[0]);
            ((object)expando.Key2[1]).ShouldBe(((Collection <string>)dict["Key2"])[1]);
        }
コード例 #4
0
        public void ToExpando()
        {
            var @this = new Dictionary <string, object> {
                { "Fizz", "Buzz" }
            };

            dynamic result = @this.ToExpando();

            Assert.AreEqual("Buzz", result.Fizz);
        }
        public void ToExpando()
        {
            // Type
            var @this = new Dictionary<string, object> {{"Fizz", "Buzz"}};

            // Exemples
            dynamic result = @this.ToExpando(); // return an expando object;

            // Unit Test
            Assert.AreEqual("Buzz", result.Fizz);
        }
コード例 #6
0
        public static async Task <List <T> > ExecuteQueryAsync <T>(DbConnection conn, string commandText
                                                                   , Func <Dictionary <string, object>, T> bind = null
                                                                   , CommandType commandType = CommandType.Text
                                                                   , IEnumerable <DbParameter> parameters = null
                                                                   , Action <DbCommand> onCreateCommand   = null)
        {
            if (conn == null)
            {
                throw new ArgumentNullException("conn");
            }
            if (string.IsNullOrEmpty(commandText))
            {
                throw new ArgumentNullException("commandText");
            }

            var result = new List <T>();

            using (var reader = (DbDataReader)await ExecuteCommandAsync(conn
                                                                        , commandText: commandText
                                                                        , commandResultType: CommandResultTypeEnum.Reader
                                                                        , parameters: parameters
                                                                        , onCreateCommand: onCreateCommand
                                                                        ))
            {
                var columnsDictionary = new Dictionary <string, object>();

                while (await reader.ReadAsync())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        var key = reader.GetName(i);

                        columnsDictionary[key] = (await reader.GetFieldValueAsync <object>(i)).IgnoreDBNull();
                    }

                    T obj = default(T);

                    if (bind != null)
                    {
                        obj = bind(columnsDictionary);
                    }
                    else
                    {
                        obj = (dynamic)columnsDictionary.ToExpando();
                    }

                    result.Add(obj);
                }
            }

            return(result);
        }
コード例 #7
0
        public void ToExpando()
        {
            // Type
            var @this = new Dictionary <string, object> {
                { "Fizz", "Buzz" }
            };

            // Exemples
            dynamic result = @this.ToExpando(); // return an expando object;

            // Unit Test
            Assert.AreEqual("Buzz", result.Fizz);
        }
コード例 #8
0
        /// <summary>
        /// Extension method that turns a dictionary of string and object to an ExpandoObject
        /// </summary>
        /// <param name="dictionary">The ResourceDictionary to bind.</param>
        /// <returns>An ExpandoObject with dictionary data as properties.</returns>
        /// <see href="http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/">theburningmonk.com</see>
        public static ExpandoObject ToExpando(this ResourceDictionary dictionary)
        {
            Dictionary <string, object> d = new Dictionary <string, object>();

            if (dictionary != null)
            {
                foreach (string key in dictionary.Keys)
                {
                    d.Add(key, dictionary[key]);
                }
            }

            return(d.ToExpando());
        }
コード例 #9
0
        public void IDictionaryTest_ToExpando_001()
        {
            var d  = new Dictionary <string, object>();
            var id = Guid.NewGuid();

            d.Add("ID", id);
            d.Add("FirstName", "Chris");
            d.Add("LastName", "Pietschmann");

            var expando = d.ToExpando();
            var dyn     = (dynamic)expando;

            Assert.AreEqual(3, expando.Count());
            Assert.AreEqual(id, (Guid)dyn.ID);
            Assert.AreEqual("Chris", (string)dyn.FirstName);
            Assert.AreEqual("Pietschmann", (string)dyn.LastName);
        }
コード例 #10
0
        public void IDictionaryExtensionsTest()
        {
            var dic = new Dictionary <string, object>();

            dic["A"] = 1;
            dic["B"] = "2";
            dic["C"] = new TestCustomObject()
            {
                Id = 666
            };

            dynamic result = dic.ToExpando();

            Assert.AreEqual(1, result.A);
            Assert.AreEqual("2", result.B);
            Assert.IsInstanceOfType(result.C, typeof(TestCustomObject));
            Assert.AreEqual(666, (result.C as TestCustomObject).Id);
        }
コード例 #11
0
        public UploadedFile GetFileFromRequest(HttpRequestBase Request)
        {
            string filename = null;
            string fileType = null;
            string fileData = null;

            byte[] fileContents = null;

            if (Request.Files.Count > 0)
            { //we are uploading the old way
                var file = Request.Files[0];
                fileContents = new byte[file.ContentLength];
                file.InputStream.Read(fileContents, 0, file.ContentLength);
                fileType = file.ContentType;
                filename = file.FileName;

                IDictionary <string, object> dict = new Dictionary <string, object>();
                foreach (string key in Request.Form.Keys)
                {
                    dict.Add(key, Request.Form.GetValues(key).FirstOrDefault());
                }
                dynamic dobj = dict.ToExpando();

                fileData = Newtonsoft.Json.JsonConvert.SerializeObject(dobj);
            }
            else if (Request.ContentLength > 0)
            {
                // Using FileAPI the content is in Request.InputStream!!!!
                fileContents = new byte[Request.ContentLength];
                Request.InputStream.Read(fileContents, 0, Request.ContentLength);
                filename = Request.Headers["X-File-Name"];
                fileType = Request.Headers["X-File-Type"];
                fileData = Request.Headers["X-File-Data"];
            }

            return(new UploadedFile()
            {
                Filename = filename,
                ContentType = fileType,
                FileSize = fileContents != null ? fileContents.Length : 0,
                Contents = fileContents,
                FileData = fileData
            });
        }
コード例 #12
0
        public void ToExpando_can_convert_simple_dictionary()
        {
            // Arrange
            var dict = new Dictionary <string, object>()
            {
                { "Key1", Guid.NewGuid() },
                { "Key2", Guid.NewGuid() },
                { "Key3", Guid.NewGuid() },
            };

            // Act
            dynamic expando = dict.ToExpando();

            // Assert
            ((object)expando).ShouldNotBeNull();
            ((object)expando.Key1).ShouldBe(dict["Key1"]);
            ((object)expando.Key2).ShouldBe(dict["Key2"]);
            ((object)expando.Key3).ShouldBe(dict["Key3"]);
        }
コード例 #13
0
ファイル: HelloHub.cs プロジェクト: maleowy/ScrapTheWorld
        private static Node PrepareRequest(string[] arr, Node node, string connectionId)
        {
            var tmp = arr[0].Split('/');

            var flow = tmp[0];

            node.Name = tmp[1];

            var args = new Dictionary <string, object> {
                { "Frontend", $"{Program.IP}:{Program.Port}" },
                { "Guid", connectionId }
            };

            for (int i = 1; i < arr.Length - 1; i = i + 2)
            {
                args.Add(arr[i], arr[i + 1]);
            }

            node.Data = args.ToExpando();

            var client = new RestClient($"http://{Program.PersistenceIP}:{Program.PersistencePort}");
            var req    = new RestRequest("/api/Persistence?table=scripts");

            node.Scripts = new Dictionary <string, string>();

            foreach (var item in client.Execute <dynamic>(req).Data)
            {
                node.Scripts.Add(item["Key"], item["Value"]);
            }

            req = new RestRequest("/api/Persistence?table=flows&key=" + flow);

            var data = client.Execute <dynamic>(req).Data;
            var json = data?["Value"] ?? "{}";

            node.Nodes = GetNodes(json);

            var flowScripts = node.Nodes.Select(n => n.Script).ToArray();

            node.Scripts = node.Scripts.Where(kvp => flowScripts.Contains(kvp.Key)).ToDictionary(i => i.Key, i => i.Value);

            return(node);
        }
コード例 #14
0
        private static async Task <DATCommandResult> RunSqlQuery(string query, string connectionString, CancellationToken cancellationToken)
        {
            var result = new DATCommandResult
            {
                QueryStatistics = new List <object>(),
                ResultSets      = new List <List <ExpandoObject> >()
            };

            using (var dbConnectionWrapper = new SqlConnectionWrapper(connectionString))
                using (var dbCommandWrapper = dbConnectionWrapper.CreateCommand())
                {
                    dbCommandWrapper.CommandType = CommandType.Text;
                    dbCommandWrapper.CommandText = query;

                    await dbConnectionWrapper.OpenAsync(cancellationToken : cancellationToken);

                    using (DbDataReader reader = await dbCommandWrapper.ExecuteReaderAsync(cancellationToken: cancellationToken))
                    {
                        do
                        {
                            var resultSet = new List <ExpandoObject>();
                            while (await reader.ReadAsync(cancellationToken: cancellationToken))
                            {
                                var record = new Dictionary <string, object>();
                                for (var i = 0; i < reader.FieldCount; i++)
                                {
                                    var fieldName  = reader.GetName(i);
                                    var fieldValue = reader.GetValue(i);
                                    record.Add(fieldName, fieldValue);
                                }

                                resultSet.Add(record.ToExpando());
                            }
                            result.ResultSets.Add(resultSet);
                        }while (await reader.NextResultAsync(cancellationToken: cancellationToken));
                    }

                    result.QueryStatistics = dbCommandWrapper.RetrieveStats().ToList();
                }

            return(result);
        }
コード例 #15
0
        public void IDictionaryTest_ToExpando_002()
        {
            var id = Guid.NewGuid();
            var dt = DateTime.Now;

            var d = new Dictionary <string, object>();

            d.Add("ID", id);
            d.Add("FirstName", "Chris");
            d.Add("LastName", "Pietschmann");

            d.Add("Obj", new Dictionary <string, object>
            {
                { "ID", 1 },
                { "Company", "ExpandoCom" },
                { "Date", dt },
                { "YearFounded", 2012 }
            });


            var expando = d.ToExpando();
            var dyn     = (dynamic)expando;

            Assert.AreEqual(4, expando.Count());
            Assert.AreEqual(id, (Guid)dyn.ID);
            Assert.AreEqual("Chris", (string)dyn.FirstName);
            Assert.AreEqual("Pietschmann", (string)dyn.LastName);

            var dyn2 = dyn.Obj;

            Assert.AreEqual(4, ((ExpandoObject)dyn2).Count());
            Assert.AreEqual(1, (int)dyn2.ID);
            Assert.AreEqual("ExpandoCom", (string)dyn2.Company);
            Assert.AreEqual(dt, (DateTime)dyn2.Date);
            Assert.AreEqual(2012, (int)dyn2.YearFounded);
        }
コード例 #16
0
ファイル: Runner.cs プロジェクト: jen20/Jubilee
 public void Initialise(Dictionary<string, object> parameters)
 {
     this.parameters = parameters.ToExpando();
 }
コード例 #17
0
        public async Task<ActionResult> GetTemplateModelAsync(int companyId, string stateId)
        {
            try
            {
                var company = await _dbContext.Companies.FirstOrDefaultAsync(c => c.Id == companyId);
                if (company == null)
                {
                    throw new InvalidOperationException("Company not found");
                }

                var workflowDef = _workflowDefinition.GetWorkflowDefinition(company.Name);
                if (!workflowDef.States.Keys.Any(k => k == stateId))
                {
                    throw new InvalidOperationException($"Workfloew state '{stateId}' not found");
                }

                IDictionary<string, object> dictionaryModel = new Dictionary<string, object>();
                foreach (var state in workflowDef.States.Values)
                {
                    if (state.GetModel().GetType() != typeof(ExternalActionState))
                    {
                        var modelName = state.GetModel().GetType().Name;
                        if (!dictionaryModel.ContainsKey(modelName))
                        {
                            dictionaryModel.Add(modelName, state.GetModel());
                        }
                    }
                    if (state.Id == stateId)
                    {
                        break;
                    }
                }
                ExpandoObject model = dictionaryModel.ToExpando();

                var result = new Dictionary<string, List<string>>();
                foreach (var key in model.Select(k => k.Key))
                {
                    var list = new List<string>();
                    object obj = model.First(k => k.Key == key).Value;
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        if (prop.PropertyType.GetInterfaces().Any(i => i.Name == typeof(IEntity).Name) 
                            || prop.PropertyType.GetInterfaces().Any(i => i.Name == typeof(IChildEntity).Name))
                        {                            
                            foreach (var objprop in prop.PropertyType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
                            {
                                if (objprop.GetCustomAttribute<JsonIgnoreAttribute>() != null)
                                {
                                    continue;
                                }
                                list.Add($"@Model.{key}.{prop.Name}.{objprop.Name}");
                            }
                        }
                        else
                        {
                            list.Add($"@Model.{key}.{prop.Name}");
                        }
                    }
                    result.Add(key, list);
                }
                return ActionResult.Success(result);
            }
            catch(Exception ex)
            {
                return ActionResult.Failed(ex);
            }
        }
コード例 #18
0
        public IHttpActionResult Get()
        {
            string key, name;
            Guid guid;

            try
            {
                key = this.Request.Headers.GetValues("X-Secret-Key").FirstOrDefault();
                name = this.Request.Headers.GetValues("X-Table-Name").FirstOrDefault();
                guid = new Guid(key);
            }
            catch (FormatException ex)
            {
                return this.BadRequest("Ivalid Secret Key format!");
            }
            catch (Exception ex)
            {
                return this.BadRequest("Not all headers provided!");
            }

            var app = this.apps.All().Where(x => x.UniqueKey == guid);
            var table = this.tables.All().FirstOrDefault(x => x.App.UniqueKey == guid && x.Name.ToLower() == name.ToLower());

            if (table == null || app == null)
            {
                return this.BadRequest("Invalid table name / secret key!");
            }

            foreach (var item in app)
            {
                item.RequestsCount++;
            }

            this.apps.Save();

            var respone = new List<ExpandoObject>();
            var count = 0;

            if (table.Fields.Any())
            {
                var members = table.Fields.FirstOrDefault(x => x.Name == "Id").Members;
                count = members.Count;

                for (int i = 0; i < count; i++)
                {
                    var row = new Dictionary<string, object>();
                    foreach (var field in table.Fields.OrderBy(x => x.Id))
                    {
                        var type = Type.GetType(field.Type);
                        var data = field.Members.OrderBy(x => x.Id).ToList()[i].Data;
                        object converted;

                        if (string.IsNullOrEmpty(data))
                        {
                            converted = "null";
                        }
                        else
                        {
                            converted = field.Type == "System.Guid" ? data : Convert.ChangeType(data, type);
                        }

                        row.Add(field.Name, converted);
                    }

                    respone.Add(row.ToExpando());
                }
            }

            return this.Ok(respone.AsQueryable());
        }