internal static bool TryHandle(JObject response, ISubject <OrderBookSnapshotResponse> subject)
        {
            /*
             *
             * if (stream == null)
             *  return false;
             *
             * if (!stream.Contains("depth"))
             *  return false;
             *
             * if (stream.EndsWith("depth"))
             * {
             *  // ignore, not partial, but diff response
             *  return false;
             * }*/
            //var stream = response?["stream"]?.Value<string>();

            if (response != null && (bool)!response?["channel"].HasValues)
            {
                var parsedSnapshot = response?.ToObject <OrderBookSnapshotResponse>(BitstampJsonSerializer.Serializer);
                //parsed.Symbol = response?["channel"].Value<string>().Split('_')[index];
                subject.OnNext(parsedSnapshot);
                return(true);
            }

            return(true);
        }
Example #2
0
        /// <summary>
        /// Post processes the content.
        /// </summary>
        /// <returns>The post processed content.</returns>
        /// <param name="content">Content.</param>
        /// <param name="meta">Meta.</param>
        /// <param name="format">Format.</param>
        internal static string PostProcessedContent(string content, dynamic meta, Enums.DocumentFormat format)
        {
            if (string.IsNullOrEmpty(content) ||
                meta == null)
            {
                return(content);
            }

            JObject metaObj = JObject.FromObject(meta);

            Dictionary <string, object> meta2 = metaObj?.ToObject <Dictionary <string, object> >();

            foreach (var key in meta2.Keys)
            {
                if (meta2[key] != null)
                {
                    content = content.Replace("{{" + key + "}}", meta2[key].ToString());
                }
            }

            if (format == Enums.DocumentFormat.Html)
            {
                content = content.ToHtml();
            }

            return(content);
        }
        private static void UpdateDotnetTemplatesToLatest(IDictionary <string, IDictionary <string, object> > workerRuntimes, int coreToolsMajor)
        {
            if (!workerRuntimes.TryGetValue("dotnet", out IDictionary <string, object> dotnetInfo))
            {
                throw new Exception("Could not find 'dotnet' worker runtime information in the feed.");
            }

            foreach (KeyValuePair <string, object> keyValInfo in dotnetInfo)
            {
                string  dotnetEntryLabel = keyValInfo.Key;
                JObject dotnetEntryToken = keyValInfo.Value as JObject;

                V4FormatDotnetEntry dotnetEntry = dotnetEntryToken?.ToObject <V4FormatDotnetEntry>() ?? throw new Exception($"Cannot parse 'dotnet' object in the feed with label '{dotnetEntryLabel}'");

                if (!_dotnetToTemplatesPrefix.TryGetValue(dotnetEntryLabel, out string templatePrefix))
                {
                    throw new Exception($"Cannot find the template package: Unidentified dotnet label '{dotnetEntryLabel}'.");
                }

                dotnetEntry.itemTemplates    = Helper.GetTemplateUrl($"{templatePrefix}.ItemTemplates", coreToolsMajor);
                dotnetEntry.projectTemplates = Helper.GetTemplateUrl($"{templatePrefix}.ProjectTemplates", coreToolsMajor);

                Helper.MergeObjectToJToken(dotnetEntryToken, dotnetEntry);
            }
        }
Example #4
0
        public T Transform <T>(Message message) where T : class
        {
            try
            {
                Type type = typeof(T);
                _logger.LogDebug($"Processing entity: {type.Name}", message);
                JObject jobject = message.JToken as JObject;

                JsonSerializer serializer = new JsonSerializer();
                serializer.Converters.Add(new IsoDateTimeConverter {
                    DateTimeFormat = "dd/MM/yyyy"
                });

                T entity = (T)jobject?.ToObject(type, serializer);
                if (entity != null)
                {
                    return(entity);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error deserializing object type: {typeof(T).Name}, {{message}}", message);
            }

            return(null);
        }
Example #5
0
        public User GetUserById(int id)
        {
            string  apiUrl     = $"{_config.UserApiUrl}Get/{id}";
            JObject jsonString = GetJSONString <JObject>(apiUrl);
            var     users      = jsonString?.ToObject <User>();

            return(users);
        }
Example #6
0
        public Task GetTaskById(int userId, int id)
        {
            string  apiUrl     = $"{String.Format(_config.TaskApiUrl, userId)}/Get/{id}";
            JObject jsonString = GetJSONString <JObject>(apiUrl);
            var     task       = jsonString?.ToObject <Task>();

            return(task);
        }
Example #7
0
        public User UpdateUser(User u)
        {
            string  apiUrl     = $"{_config.UserApiUrl}Update/{u.Id}";
            JObject jsonString = PutJSONString <JObject>(apiUrl, u);
            var     users      = jsonString?.ToObject <User>();

            return(users);
        }
Example #8
0
        public Task UpdateTask(int userId, Task u)
        {
            string apiUrl = $"{String.Format(_config.TaskApiUrl, userId)}/Update/{u.Id}";

            JObject jsonString = PutJSONString <JObject>(apiUrl, u);
            var     task       = jsonString?.ToObject <Task>();

            return(task);
        }
Example #9
0
        public User AddUser(string name)
        {
            string apiUrl  = $"{_config.UserApiUrl}Add";
            var    bodyObj = new
            {
                Name = name
            };
            JObject jsonString = PostJSONString <JObject>(apiUrl, bodyObj);
            var     users      = jsonString?.ToObject <User>();

            return(users);
        }
Example #10
0
        public SpeechRecRes SpeechRec(byte[] data)
        {
            SpeechRecRes res = null;

            if (data != null)
            {
                JObject result = _asr.Recognize(data, _speechFormat, 16000);

                res = result?.ToObject <SpeechRecRes>();
            }

            return(res);
        }
Example #11
0
        Settings GetSettings()
        {
            Settings settings = null;

            if (File.Exists(@"Startup\settings.json"))
            {
                var settingsFile = File.ReadAllText(@"Startup\settings.json");

                JObject jobj = (JObject)JsonConvert.DeserializeObject(settingsFile);
                settings = jobj?.ToObject <Settings>();
            }

            return(settings);
        }
Example #12
0
        public Task AddTask(int userId, string description, int state)
        {
            string apiUrl  = $"{String.Format(_config.TaskApiUrl, userId)}/Add";
            var    bodyObj = new
            {
                Description = description,
                State       = state,
                UserId      = userId
            };
            JObject jsonString = PostJSONString <JObject>(apiUrl, bodyObj);
            var     task       = jsonString?.ToObject <Task>();

            return(task);
        }
Example #13
0
        public object JsonDeserialize(Type dataType, string filePath)
        {
            JObject        obj            = null;
            JsonSerializer jsonSerializer = new JsonSerializer();

            if (File.Exists(filePath))
            {
                StreamReader sr         = new StreamReader(filePath);
                JsonReader   jsonReader = new JsonTextReader(sr);
                obj = jsonSerializer.Deserialize(jsonReader) as JObject;
                jsonReader.Close();
                sr.Close();
            }
            return(obj?.ToObject(dataType));
        }
        internal static bool TryHandle(JObject response, ISubject <OrderBookDiffResponse> subject)
        {
            var channelName = response?["channel"];

            if (channelName == null || !channelName.Value <string>().StartsWith("diff_order_book"))
            {
                return(false);
            }

            var parsed = response?.ToObject <OrderBookDiffResponse>(BitstampJsonSerializer.Serializer);

            if (parsed != null)
            {
                parsed.Symbol = channelName.Value <string>().Split('_').LastOrDefault();
                subject.OnNext(parsed);
            }

            return(true);
        }
Example #15
0
        internal static bool TryHandle(JObject response, ISubject <OrderBookDiffResponse> subject)
        {
            if (response != null && (bool)!response?["channel"].Value <string>().StartsWith("diff_order_book"))
            {
                return(false);
            }

            var parsed = response?.ToObject <OrderBookDiffResponse>(BitstampJsonSerializer.Serializer);

            if (parsed != null)
            {
                var index   = 3;
                var channel = response?["channel"].Value <string>();
                parsed.Symbol = response?["channel"].Value <string>().Split('_')[index];
                subject.OnNext(parsed);
            }

            return(true);
        }
Example #16
0
        internal static bool TryHandle(JObject response, ISubject <OrderBookDetailResponse> subject)
        {
            if (response != null && (bool)!response?["channel"].Value <string>().StartsWith("detail_order_book") &&
                response?["event"].Value <string>() != "bts:unsubscription_succeeded")
            {
                return(false);
            }

            var parsed = response?.ToObject <OrderBookDetailResponse>(BitstampJsonSerializer.Serializer);

            if (parsed != null)
            {
                var index   = 3;
                var channel = response?["channel"].Value <string>();

                parsed.Symbol = response?["channel"].Value <string>().Split('_')[index];
                subject.OnNext(parsed);
            }

            return(true);
        }
Example #17
0
        /// <summary>
        /// Cleans up meta.
        /// </summary>
        /// <returns>The cleaned up meta.</returns>
        /// <param name="meta">Meta.</param>
        internal static dynamic CleanUpMeta(dynamic meta)
        {
            if (meta == null)
            {
                return(new Dictionary <string, object>());
            }

            JObject metaObj = JObject.FromObject(meta);

            Dictionary <string, object> meta2     = metaObj?.ToObject <Dictionary <string, object> >();
            Dictionary <string, object> metaFinal = new Dictionary <string, object>();

            foreach (var key in meta2.Keys)
            {
                if (meta2[key] != null)
                {
                    metaFinal.Add(key, meta2[key]);
                }
            }

            return(metaFinal);
        }
Example #18
0
        TryHandle(JObject response, ISubject <OrderResponse> subject)
        {
            //if (response?["channel"].Value<string>() != "order_created" ||
            //response?["channel"].Value<string>() != "order_changed" ||
            //response?["channel"].Value<string>() != "order_deleted") return false;

            if (response != null && (bool)!response?["channel"].Value <string>().Contains("live_orders"))
            {
                return(false);
            }

            var parsed = response?.ToObject <OrderResponse>(BitstampJsonSerializer.Serializer);

            if (parsed != null)
            {
                parsed.Symbol = response?["channel"].Value <string>().Split('_')[2];

                subject.OnNext(parsed);
            }

            subject.OnNext(parsed);
            return(true);
        }
Example #19
0
        /// <inheritdoc />
        public IWidgetModel Resolve(JObject parsedWidgetData, Type type)
        {
            var codename = parsedWidgetData.Property("name").Value.ToString();

            var beforeAction = WidgetRegistry.GetBeforeAction(codename);

            if (beforeAction != null)
            {
                parsedWidgetData = (JObject)beforeAction.DynamicInvoke(parsedWidgetData);
            }

            var obj = parsedWidgetData?.ToObject(type, JsonSerializer.Create(new JsonSerializerSettings {
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
            }));

            var afterAction = WidgetRegistry.GetAfterAction(codename);

            if (afterAction != null)
            {
                obj = afterAction.DynamicInvoke(obj);
            }

            return((IWidgetModel)obj);
        }
 public StartOrchestrationArgs JObjectToStartOrchestrationArgs(JObject input, DurableClientAttribute attr)
 {
     return(input?.ToObject <StartOrchestrationArgs>());
 }
Example #21
0
        public JObject Get([FromQuery] string query = null,
                           [FromQuery] string order = null,
                           [FromQuery] int page     = 1)
        {
            IQueryable <Channels> channels = _dbContext.Channels
                                             .Include("Subscribers")
                                             .Where(q => q.Type == (byte)Channels.Types.App)
                                             .Where(q => q.DeletedAt == null);

            if (query != null)
            {
                try
                {
                    JObject objQuery = JObject.Parse(query);

                    Dictionary <string, string> dictQuery = objQuery.ToObject <Dictionary <string, string> >();
                    foreach (string key in dictQuery.Keys)
                    {
                        string value = dictQuery[key];

                        switch (key)
                        {
                        case "name":
                            _logger.LogError(key);
                            _logger.LogError(value);
                            channels = channels.Where(q => q.Name.Contains(value));
                            break;
                        }
                    }
                }
                catch (Newtonsoft.Json.JsonReaderException ex)
                {
                    _logger.LogWarning(ex.StackTrace);
                }
            }
            if (order != null)
            {
                JObject objOrder = JObject.Parse(order);
                Dictionary <string, string> dictOrder = objOrder.ToObject <Dictionary <string, string> >();
                foreach (string key in dictOrder.Keys)
                {
                    string value = dictOrder[key];
                    switch (key)
                    {
                    case "number":
                        channels = value == "desc" ?
                                   channels.OrderByDescending(q => q.Id) :
                                   channels.OrderBy(q => q.Id);
                        break;

                    case "name":
                        channels = value == "desc" ?
                                   channels.OrderByDescending(q => q.Name) :
                                   channels.OrderBy(q => q.Name);
                        break;

                    case "members":
                        channels = value == "desc" ?
                                   channels.OrderByDescending(q => q.Subscribers.Count) :
                                   channels.OrderBy(q => q.Subscribers.Count);
                        break;

                    case "push":
                    case "status":
                        channels = value == "desc" ?
                                   channels.OrderByDescending(q => q.Status) :
                                   channels.OrderBy(q => q.Status);
                        break;
                    }
                }
            }
            else
            {
                channels = channels.OrderByDescending(q => q.CreatedAt);
            }

            var total = channels.Count();

            if (page != 1)
            {
                _logger.LogError("" + page);
                int skip = (page - 1) * PAGE_SIZE;
                channels = channels.Skip(skip);
            }

            //var url = _accessor.HttpContext.Request.Host.Host;
            var url          = _config["ImgUrl"];
            var channelsData = channels.Select(q => new Channels {
                Id              = q.Id,
                Name            = q.Name,
                Type            = (byte)Channels.Types.App,
                Status          = q.Status,
                CreatedAt       = q.CreatedAt,
                UpdatedAt       = q.UpdatedAt,
                Image           = (q.Image != null ? $@"{url}{q.Image}" : null),
                SubscriberCount = q.Subscribers.Count()
            })
                               .Take(PAGE_SIZE).ToList();

            JArray data = new JArray();

            foreach (Channels channelItem in channelsData)
            {
                dynamic item = new JObject();
                item["id"]         = channelItem.Id;
                item["members"]    = channelItem.SubscriberCount;
                item["icon"]       = channelItem.Image;
                item["name"]       = channelItem.Name;
                item["available"]  = true;
                item["status"]     = channelItem.Status;
                item["created_at"] = channelItem.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss");
                item["updated_at"] = channelItem.UpdatedAt.ToString("yyyy-MM-dd HH:mm:ss");

                data.Add(item);
            }

            dynamic output = new JObject();

            output["current_page"] = page;
            output["data"]         = data;
            output["per_page"]     = PAGE_SIZE;
            output["total"]        = total;

            dynamic res = new JObject();

            res.code   = 200;
            res.reason = "success";
            res.data   = output;

            return(res);
        }
Example #22
0
 public void Execute(JObject config, string lifecycleEvent, IMinecraftInstance instance)
 {
     Execute((TConfig)config?.ToObject(typeof(TConfig)), lifecycleEvent, instance);
 }
 protected internal virtual StartProjectionOrchestrationArgs JObjectToStartProjectionArgs(JObject input)
 {
     return(input?.ToObject <StartProjectionOrchestrationArgs>());
 }
 protected internal virtual StartIdentifierGroupOrchestrationArgs JObjectToStartIdentifierGroupArgs(JObject input)
 {
     return(input?.ToObject <StartIdentifierGroupOrchestrationArgs>());
 }
Example #25
0
        static void Main(string[] args)
        {
            Member member1 = new Member("1", "park", "*****@*****.**", "abcd");
            Member member2 = new Member("2", "lee", "*****@*****.**", "abcde");


            // JObject
            JObject jobj1 = new JObject();

            jobj1.Add("Id", "1");
            jobj1.Add("Name", "park");
            jobj1.Add("Email", "*****@*****.**");
            jobj1.Add("Password", "abcd");

            JObject jobj2 = new JObject();

            jobj2.Add("Id", "2");
            jobj2.Add("Name", "lee");
            jobj2.Add("Email", "*****@*****.**");
            jobj2.Add("Password", "abcde");

            JObject jobj3 = JObject.FromObject(member1);

            Console.WriteLine(jobj1.ToString());
            Console.WriteLine(jobj3.ToString());
            Console.WriteLine("jobj1 == jobj3 : {0}", jobj1.ToString() == jobj3.ToString());
            Console.WriteLine();


            // JArray
            JArray jarray1 = new JArray();

            jarray1.Add(jobj1);
            jarray1.Add(jobj2);

            List <Member> members = new List <Member>();

            members.Add(member1);
            members.Add(member2);
            JArray jarray2 = JArray.FromObject(members);

            Console.WriteLine(jarray1.ToString());
            Console.WriteLine(jarray2.ToString());
            Console.WriteLine("jarray1 == jarray2 : {0}", jarray1.ToString() == jarray2.ToString());
            Console.WriteLine();


            // JObject with JArray
            JObject jobj4 = new JObject();

            jobj4.Add("Id", "1");
            jobj4.Add("Name", "development");
            jobj4.Add("Description", "software development");
            jobj4.Add("Members", jarray1);

            Department department = new Department("1", "development", "software development");

            department.Members.Add(member1);
            department.Members.Add(member2);
            JObject jobj5 = JObject.FromObject(department);

            Console.WriteLine(jobj4.ToString());
            Console.WriteLine(jobj5.ToString());
            Console.WriteLine("jobj4 == jobj5 : {0}", jobj4.ToString() == jobj5.ToString());
            Console.WriteLine();


            // JObject, JArray to ClassObject
            department = jobj5.ToObject(typeof(Department)) as Department;
            member1    = ((JArray)jobj5["Members"])[0].ToObject(typeof(Member)) as Member;
            member2    = ((List <Member>)jobj5["Members"].ToObject(typeof(List <Member>)))[1];


            // JsonString to JObject
            string  jsonString = "{ \"Id\":\"1\", \"Name\":\"park\", \"Email\":\"[email protected]\", \"Password\":\"abcd\", }";
            JObject jobj6      = JObject.Parse(jsonString);

            member1 = jobj6.ToObject(typeof(Member)) as Member;


            Console.ReadLine();
        }
 public static Dictionary <string, string> BodyToDictionary(this JObject value)
 {
     return(value?.ToObject <Dictionary <string, string> >());
 }
Example #27
0
        public IHttpActionResult Live(JObject value) {
            var authInfo = value.ToObject<ExternalAuthInfo>();
            if (authInfo == null || String.IsNullOrEmpty(authInfo.Code))
                return NotFound();

            if (String.IsNullOrEmpty(Settings.Current.MicrosoftAppId) || String.IsNullOrEmpty(Settings.Current.MicrosoftAppSecret))
                return NotFound();

            var client = new WindowsLiveClient(new RequestFactory(), new RuntimeClientConfiguration {
                ClientId = Settings.Current.MicrosoftAppId,
                ClientSecret = Settings.Current.MicrosoftAppSecret,
                RedirectUri = authInfo.RedirectUri
            });

            UserInfo userInfo;
            try {
                userInfo = client.GetUserInfo(authInfo.Code);
            } catch (Exception ex) {
                Log.Error().Exception(ex).Message("Unable to get user info.").Write();
                return BadRequest("Unable to get user info.");
            }

            User user;
            try {
                user = AddExternalLogin(userInfo);
            } catch (Exception ex) {
                Log.Error().Exception(ex).Message("Unable to get user info.").Write();
                return BadRequest("An error occurred while processing user info.");
            }

            if (user == null)
                return BadRequest("Unable to process user info.");

            if (!String.IsNullOrEmpty(authInfo.InviteToken))
                AddInvitedUserToOrganization(authInfo.InviteToken, user);

            return Ok(new { Token = GetToken(user) });
        }
Example #28
0
 // Work out how bind
 public StartCommandOrchestrationArgs JObjectToStartCommandtOrchestrationArgs(JObject input,
                                                                              OrchestrationClientAttribute attr)
 {
     return(input?.ToObject <StartCommandOrchestrationArgs>());
 }
Example #29
0
 protected override T MaterializeValue <T>() => _serializedState?.ToObject <T>();
Example #30
0
 public static Dictionary <string, Example> FromJObject(JObject obj) =>
 obj?.ToObject <Dictionary <string, Example> >() ?? new Dictionary <string, Example>();
Example #31
0
 public ISearchIndexEntry Convert(JObject entry) => entry?.ToObject <SearchIndexEntry>();
Example #32
0
        public static object Invoke(MethodInfo methodInfo, JObject json)
        {
            ParameterInfo[] paramterInfos = methodInfo.GetParameters();
            var type = methodInfo.DeclaringType;

            object[] paramters = new object[paramterInfos.Length];
            try
            {
                for (int i = 0; i < paramterInfos.Length; i++)
                {
                    Type parameterType = paramterInfos[i].ParameterType;
                    string parameterName = paramterInfos[i].Name;
                    object value = null;
                    JToken jvalue = null;

                    if (json.TryGetValue(parameterName, StringComparison.OrdinalIgnoreCase, out jvalue))
                    {
                        if (parameterType == typeof(string))
                            value = jvalue.ToString();
                        else
                            value = jvalue.ToObject(parameterType);

                    }
                    else
                    {
                        if (parameterType == typeof(string))
                            value = json.ToString();
                        else
                            value = json.ToObject(parameterType);

                    }
                    paramters[i] = value;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("解析方法'" + type.FullName + "." + methodInfo.Name + "'参数出错,请检查传入参数!\n出错信息:" + ex.Message, ex);
            }
            try
            {
                object instance = null;
                if (!methodInfo.IsStatic)
                    instance = Activator.CreateInstance(type, new object[] { });
                return methodInfo.Invoke(instance, paramters);
            }
            catch (Exception ex)
            {
                throw new Exception("调用方法'" + type.FullName + "." + methodInfo.Name + "'失败\n出错信息:" + ex.Message, ex);
            }
        }