public void ProcessMrefWithTocShouldSucceed() { var files = new FileCollection(Directory.GetCurrentDirectory()); files.Add(DocumentType.Article, new[] { "TestData/mref/CatLibrary.Cat`2.yml" }, "TestData/"); files.Add(DocumentType.Article, new[] { "TestData/mref/toc.yml" }, "TestData/"); BuildDocument(files); { var outputRawModelPath = GetRawModelFilePath("CatLibrary.Cat`2.yml"); Assert.True(File.Exists(outputRawModelPath)); var model = JsonUtility.Deserialize <ApiBuildOutput>(outputRawModelPath); Assert.NotNull(model); Assert.Equal("Hello world!", model.Metadata["meta"]); Assert.Equal(true, model.Metadata["_splitReference"]); Assert.Equal(20, model.Children.Count); } { var outputRawModelPath = GetRawModelFilePath("CatLibrary.Cat-2.-ctor.yml"); Assert.True(File.Exists(outputRawModelPath)); var model = JsonUtility.Deserialize <ApiBuildOutput>(outputRawModelPath); Assert.NotNull(model); Assert.Equal("Hello world!", model.Metadata["meta"]); Assert.Equal(true, model.Metadata["_splitReference"]); Assert.Equal(MemberType.Constructor, model.Type); Assert.Equal(3, model.Children.Count); Assert.Equal(new List <string> { "net2", "net46" }, model.Platform); Assert.Equal("<p sourcefile=\"TestData/mref/CatLibrary.Cat`2.yml\" sourcestartlinenumber=\"1\" sourceendlinenumber=\"1\">Overload summary</p>\n", model.Summary); Assert.Equal("<p sourcefile=\"TestData/mref/CatLibrary.Cat`2.yml\" sourcestartlinenumber=\"1\" sourceendlinenumber=\"1\">Overload <em>remarks</em></p>\n", model.Remarks); Assert.Equal(new List <string> { "<p sourcefile=\"TestData/mref/CatLibrary.Cat`2.yml\" sourcestartlinenumber=\"1\" sourceendlinenumber=\"1\">Overload example 1</p>\n", "<p sourcefile=\"TestData/mref/CatLibrary.Cat`2.yml\" sourcestartlinenumber=\"1\" sourceendlinenumber=\"1\">Overload <strong>example 2</strong></p>\n" }, model.Examples); Assert.Equal("Not defined Property", model.Metadata["not-defined"]); Assert.NotNull(model.Source); Assert.Equal("net46", JArray.FromObject(model.Children[0].Metadata[Constants.MetadataName.Version])[0].ToString()); Assert.Equal("net2", JArray.FromObject(model.Children[1].Metadata[Constants.MetadataName.Version])[0].ToString()); } { var outputRawModelPath = GetRawModelFilePath("toc.yml"); Assert.True(File.Exists(outputRawModelPath)); var model = JsonUtility.Deserialize <TocItemViewModel>(outputRawModelPath); Assert.NotNull(model); Assert.Single(model.Items); Assert.Equal("CatLibrary.Cat%602.html", model.Items[0].TopicHref); Assert.Equal(16, model.Items[0].Items.Count); Assert.Equal("CatLibrary.Cat-2.op_Addition.html", model.Items[0].Items[0].TopicHref); Assert.Equal("Addition", model.Items[0].Items[0].Name); Assert.Equal("CatLibrary.Cat-2.op_Subtraction.html", model.Items[0].Items[15].TopicHref); Assert.Equal("Subtraction", model.Items[0].Items[15].Name); var ctor = model.Items[0].Items.FirstOrDefault(s => s.Name == "Cat"); Assert.NotNull(ctor); Assert.Equal("CatLibrary.Cat`2.#ctor*", ctor.TopicUid); Assert.Equal("Constructor", ctor.Metadata["type"].ToString()); Assert.Equal(new List <string> { "net2", "net46" }, JArray.FromObject(ctor.Metadata[Constants.PropertyName.Platform]).Select(s => s.ToString()).ToList()); Assert.Equal(new List <string> { "net2", "net46" }, JArray.FromObject(ctor.Metadata[Constants.MetadataName.Version]).Select(s => s.ToString()).ToList()); } { var manifestFile = Path.GetFullPath(Path.Combine(_outputFolder, "manifest.json")); var manifest = JsonUtility.Deserialize <Manifest>(manifestFile); Assert.Equal(17, manifest.Files.Count); // NOTE: split output files have the same source file path var groups = manifest.Files.GroupBy(s => s.SourceRelativePath).ToList().OrderByDescending(s => s.Count()).ToList(); Assert.Single(groups); } }
private void UpdateConfig(ZentCloud.BLLJIMP.Model.Component item) { //item.ComponentConfig = "{\"pageinfo\":{\"title\":\"MixBlu\",\"bg_img\":\"\",\"bg_color\":\"#FFFFFF\"},\"shareinfo\":{\"title\":\"首页\",\"desc\":\"首页——MixBlu服装\",\"img_url\":\"http://open-files.comeoncloud.net/www/xikaiye/jubit/image/20160706/A30528B3DA394312B8E8A4DAE8C3D797.png\",\"link\":\"\"},\"head_bar\":{\"show\":\"1\",\"title\":\"首页\",\"left_btn\":\"javascript:history.go(-1);\",\"right_btn\":\"http://m.mixblu.com/customize/mixblu/index.aspx?ngroute=/shoppingBasket#/shoppingBasket\",\"right_btn_ico\":\"iconfont icon-shangchengicon25\",\"left_btn_ico\":\"iconfont icon-shangchengicon26\",\"sidemenu_button\":\"1\",\"left_btn_size\":\"40\",\"right_btn_num\":\"1\",\"right_btn_size\":\"23\",\"color\":\"#FFFFFF\",\"bg_color\":\"#0A0A0A\",\"bd_color\":\"#0A0A0A\"},\"totop\":{\"style\":\"1\"},\"sidemenubox\":{\"show\":\"0\",\"type\":\"4\",\"data_key\":\"商城左侧导航\",\"head_bgcolor\":\"#6BD3FF\",\"item_bgcolor\":\"#F563FF\",\"style\":\"2\",\"search_url\":\"http://m.mixblu.com/customize/mixblu/index.aspx?ngroute=/productList///{search_key}///time_desc/#/productList///{search_key}///time_desc/\",\"search_placeholder\":\"输入货号或关键词,如:连衣裙\"},\"notice_1\":[{\"text\":\"7.18秋款上新 全场满减\",\"color\":\"#FFFFFF\",\"bg_color\":\"#FF5C48\",\"link\":\"\",\"line_height\":\"28\",\"mg_top\":\"0\",\"mg_bottom\":\"0\",\"font_size\":\"12\",\"letter_spacing\":\"2\",\"scroll_amount\":\"20\"}],\"slides_1\":[{\"slide_list\":\"首页banner\",\"show_type\":\"3\",\"size_height\":\"0\",\"size_width\":\"0\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"0\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"slides_2\":[{\"slide_list\":\"首页满减\",\"show_type\":\"3\",\"size_height\":\"0\",\"size_width\":\"0\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FF5C48\",\"bd_width\":\"7\",\"mg_top\":\"5\",\"mg_bottom\":\"5\"}],\"slides_3\":[{\"slide_list\":\"包包\",\"show_type\":\"3\",\"size_height\":\"354\",\"size_width\":\"581\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"slides_4\":[{\"slide_list\":\"首页banner2\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"slides_5\":[{\"slide_list\":\"首页当季爆款\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"5\",\"mg_bottom\":\"0\"}],\"malls_1\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"sort_tag\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"\",\"tag\":\"hot\",\"style_child_1\":\"2\",\"sort_tag\":\"hot\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\"}],\"slides_6\":[{\"slide_list\":\"首页特卖爆款\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_2\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"sales_volume\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"sale\",\"tag\":\"sale\"}],\"slides_7\":[{\"slide_list\":\"首页分类-T恤\",\"show_type\":\"1\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_3\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"def\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"190\",\"tag\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"\"}],\"slides_8\":[{\"slide_list\":\"首页分类-连衣裙\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_4\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"def\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"192\",\"tag\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"\"}],\"slides_9\":[{\"slide_list\":\"首页分类-衬衫\",\"show_type\":\"1\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_5\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"def\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"191\",\"tag\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"\"}],\"slides_10\":[{\"slide_list\":\"首页分类-半裙\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_6\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"def\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"193\",\"tag\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"\"}],\"slides_11\":[{\"slide_list\":\"首页分类-裤装\",\"show_type\":\"2\",\"size_height\":\"300\",\"size_width\":\"640\",\"show_title\":\"0\",\"switch_class\":\"1\",\"bd_color\":\"#FFFFFF\",\"bd_width\":\"0\",\"mg_top\":\"0\",\"mg_bottom\":\"0\"}],\"malls_7\":[{\"count\":\"6\",\"style\":\"1\",\"is_group_buy\":\"0\",\"sort\":\"def\",\"auto_load\":\"0\",\"title_show\":\"0\",\"cate\":\"189\",\"tag\":\"\",\"style_child_1\":\"2\",\"link\":\"/customize/mixblu/index.aspx?ngroute=/productDetail/{id}#/productDetail/{id}\",\"top_sort\":\"\",\"sort_tag\":\"\"}],\"content_1\":[{\"thtml\":\"<div style=\\\"width:100%;height:100px;text-align:center;color:#646464;background:#010101;\\\">\\n\\t<div style=\\\"width:100%;height:45px;line-height:45px;\\\">\\n\\t\\t<a class=\\\"iconfont icon-xinlang\\\" style=\\\"margin:0 13px;color:#646464!important;text-decoration:none!important;font-size:24px;\\\" href=\\\"http://weibo.com/u/5592492372\\\"></a> <a class=\\\"iconfont icon-weixin\\\" style=\\\"margin:0 13px;color:#646464!important;text-decoration:none!important;font-size:24px;\\\" href=\\\"http://mp.weixin.qq.com/s?__biz=MjM5NzQ4MTc1Nw==&mid=208770866&idx=1&sn=d38dddf4a7b9e17c8ca3222036740616&scene=1&srcid=GhQQlEdHwdr7fDrIan4d&key=dffc561732c226510df4349b28f24ea5bc612bf796f35abf333275024093bed75b8e9f37347c5c79f57adbd6dea2c678&ascene=0&uin=MjE0NjUwNjE1&devicetype=iMac+MacBookAir6%2C2+OSX+OSX+10.10.5+build(14F27)&version=11020201&pass_ticket=6XZxybJhAq%2F7BtoA3zNntViYiwqNLOP8WoUJ0cRbKeI%3D\\\"></a> <a class=\\\"iconfont icon-taobao\\\" style=\\\"margin:0 13px;color:#646464!important;text-decoration:none!important;font-size:24px;\\\" href=\\\"http://msbfs.m.tmall.com\\\"></a> \\n\\t</div>\\n\\t<div class=\\\"font14\\\">\\n\\t\\t© 2015 Mixblu 沪ICP备14040036号 版权所有 <a href=\\\"https://www.sgs.gov.cn/lz/licenseLink.do?method=licenceView&entyId=dov73ne26zbqq0iswy128wh32k4nas6qky\\\"><img src=\\\"http://open-files.comeoncloud.net/www/mixblu/mixblu/image/20151117/2BBC9B9818764CE582FCF1F65DACE4F4.gif\\\" alt=\\\"\\\" style=\\\"width:14px;top:2px;position:relative;\\\" /></a><br />\\n<a href=\\\"#/articleList/572\\\" style=\\\"color:#646464;border-right:1px solid #646464;padding:0 8px;\\\">隐私政策</a> <a href=\\\"#/articleList/574\\\" style=\\\"color:#646464;border-right:1px solid #646464;padding:0 8px;\\\">买家条款与条件</a> <a href=\\\"#/articleList/573\\\" style=\\\"color:#646464;padding:0 8px;\\\">帮助中心</a> \\n\\t</div>\\n</div>\"}]}"; if (string.IsNullOrWhiteSpace(item.ComponentConfig)) { return; } //加载分类数据和文章首页数据 JObject jobject = JObject.Parse(item.ComponentConfig); //List<string> liT = new List<string>{"slide_list","slides","navs","tab_list","cards","malls","activitys"}; Dictionary <string, int> dicT = new Dictionary <string, int>(); dicT.Add("slides", 1); dicT.Add("navs", 1); dicT.Add("cards", 1); dicT.Add("malls", 1); dicT.Add("activitys", 1); //Dictionary<string, int> dicTn = new Dictionary<string, int>(); //dicTn.Add("slides", "slides"); //dicTn.Add("navs", "navs"); //dicTn.Add("cards", "cards"); //dicTn.Add("malls", "malls"); //dicTn.Add("activitys", "activitys"); List <string> liT = new List <string> { "slides", "navs", "cards", "malls", "activitys" }; List <JProperty> listProperty = jobject.Properties().ToList(); if (listProperty.Count == 0) { return; } JObject result = new JObject(); bool haArr = false; foreach (JProperty pro in listProperty) { string pName = pro.Name; string lio = liT.FirstOrDefault(p => pName.StartsWith(p)); if (jobject[pro.Name].Type == JTokenType.Array && !string.IsNullOrWhiteSpace(lio)) { haArr = true; JArray oChildJArray = JArray.FromObject(pro.Value); int n = dicT[lio]; if (oChildJArray.Count > 1) { foreach (JToken cio in oChildJArray) { JArray childJArray = new JArray(); childJArray.Add(cio); result[lio + "_" + n] = childJArray; n++; dicT[lio] = n; } } else { result[lio + "_" + n] = oChildJArray; n++; dicT[lio] = n; } } else { result[pro.Name] = pro.Value; } } item.ComponentConfig = JsonConvert.SerializeObject(result); if (haArr) { if (bll.UpdateByKey <ZentCloud.BLLJIMP.Model.Component>("AutoId", item.AutoId.ToString(), "ComponentConfig", item.ComponentConfig) > 0) { SetTextErrorMessage(item.WebsiteOwner + ":" + item.AutoId); } } }
/// <summary> /// 更新配置文件内容 /// </summary> /// <returns>成功写入配置文件的服务器的数量,0表示配置文件未修改</returns> private int UpdateFile() { if (ServerInfoFetcherCollection.Count() == 0) { throw new ApplicationException(Resources.NoFetcherEnabled); } // 获取服务器信息 ServerInfo[] serverInfoCollection = ( from fetcher in ServerInfoFetcherCollection.AsParallel() select fetcher.GetServers() ).Aggregate((x, y) => x.Concat(y)).ToArray <ServerInfo>(); serverInfoCollection = FilterByCountryAndUpdateCountryList(serverInfoCollection); if (serverInfoCollection.Count() == 0) { throw new ApplicationException(Resources.NoValidServer); } string str = (string)null; // 读取现有配置文件 JObject currentSettings; try { currentSettings = JObject.Parse(File.ReadAllText(OutputFileName())); str = ((object)currentSettings).ToString(); } catch (Exception) { currentSettings = new JObject(); } // 根据之前的服务器选择更新选择的服务器 int newIndex = -1; try { int oldIndex = currentSettings["index"].ToObject <int>(); if (oldIndex >= 0) { ServerInfo oldServer = ((JArray)currentSettings["configs"])[oldIndex].ToObject <ServerInfo>(); newIndex = BestMatchServer(serverInfoCollection, oldServer); } } catch (Exception) { } var hasSuccessCount = 0; List <ServerInfo> serverInfos = new List <ServerInfo>(); ServerInfo[] oldServers = ((JArray)currentSettings["configs"]).ToObject <ServerInfo[]>(); if (!(oldServers == null || oldServers.Length == 0)) { foreach (var serverInfo in oldServers) { var hasServerInfo = serverInfoCollection .Where(s => s.Host == serverInfo.Host && s.Method == serverInfo.Method && s.Port == serverInfo.Port) .SingleOrDefault <ServerInfo>(); if (hasServerInfo == null) { serverInfos.Add(serverInfo); continue; } // 如果新增在已有的配置中无法查到,则表示需要更新配置文件 if (hasServerInfo.Password != serverInfo.Password) { hasSuccessCount++; } } } serverInfoCollection = serverInfoCollection.Union(serverInfos.ToArray <ServerInfo>()).ToArray(); // 更新配置文件 currentSettings["configs"] = (JToken)JArray.FromObject((object)serverInfoCollection); currentSettings["index"] = (JToken) new JValue(newIndex); if (newIndex == -1 && ( currentSettings["strategy"] == null || currentSettings["strategy"].Type == JTokenType.Null)) { currentSettings["strategy"] = "com.shadowsocks.strategy.ha"; } if (hasSuccessCount > 0) { string contents = ((object)currentSettings).ToString(); File.WriteAllText(OutputFileName(), contents); } else { return(0); } return(serverInfoCollection.Length); }
private void SaveUsers() { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "data.json"); File.WriteAllText(filePath, JArray.FromObject(_users).ToString()); }
public Task <string> AddUri(string[] uris, Aria2Options options = null, long position = long.MaxValue) => Call <string>("aria2.addUri", JArray.FromObject(uris), SerializeOptions(options), position);
private static JToken ExtractEntityValue(EntityRecommendation entity) { if (entity.Resolution == null) { return(entity.Entity); } if (entity.Type.StartsWith("builtin.datetimeV2.")) { if (entity.Resolution?.Values == null || entity.Resolution.Values.Count == 0) { return(JArray.FromObject(entity.Resolution)); } var resolutionValues = (IEnumerable <object>)entity.Resolution["values"]; var type = ((IDictionary <string, object>)(resolutionValues.First()))["type"]; var timexes = resolutionValues.Select(val => ((IDictionary <string, object>)val)["timex"]); var distinctTimexes = timexes.Distinct(); return(new JObject(new JProperty("type", type), new JProperty("timex", JArray.FromObject(distinctTimexes)))); } else { var resolution = entity.Resolution; switch (entity.Type) { case "builtin.number": case "builtin.ordinal": return(Number(resolution["value"])); case "builtin.percentage": { var svalue = (string)resolution["value"]; if (svalue.EndsWith("%")) { svalue = svalue.Substring(0, svalue.Length - 1); } return(Number(svalue)); } case "builtin.age": case "builtin.dimension": case "builtin.currency": case "builtin.temperature": { var units = (string)resolution["unit"]; var val = Number(resolution["value"]); var obj = new JObject(); if (val != null) { obj.Add("number", val); } obj.Add("units", units); return(obj); } default: return(entity.Resolution.Count > 1 ? JObject.FromObject(entity.Resolution) : entity.Resolution.ContainsKey("value") ? (JToken) new JValue(entity.Resolution["value"]) : JArray.FromObject(entity.Resolution["values"])); } } }
public void RestartFromMainCheckpoint(string variablePrefix, dynamic destPoint, int epNumber) { // Remove variables of future scenes from the minor and major variable list FillMinorAndMajorVars(variablePrefix); // Erase future main checkpoints from the checkpoint list var checkpointsList = new List <JObject>(); //Add all main checkpoints before the target to a list foreach (var checkpoint in MainData.checkpoints) { if (!IsFarewellCheckpoint(checkpoint.pointIdentifier.Value)) { checkpointsList.Add(checkpoint); if (checkpoint == destPoint) { break; } } } //Add all Farewell checkpoints to that same list foreach (var checkpoint in MainData.checkpoints) { if (IsFarewellCheckpoint(checkpoint.pointIdentifier.Value)) { checkpointsList.Add(checkpoint); } } MainData.checkpoints = JArray.FromObject(checkpointsList); // Copy flags from last (i.e target) checkpoint to global flags ((JToken)MainData.flags).Replace(destPoint.flags); // Copy float values from last checkpoint to global float values ((JToken)MainData.floatValuesDict).Replace(destPoint.floatValuesDict); // Set episode states string destPointId = destPoint.pointIdentifier; for (var i = 0; i < MainData.episodes.Count; i++) { if (i == (int)Episode.Bonus) { continue; } if (i < epNumber) { MainData.episodes[i].episodeState = Consts.EpisodeStates.Finished; } else if (i == epNumber && !destPointId.EndsWith("End")) { MainData.episodes[i].episodeState = Consts.EpisodeStates.InProgress; } else if (i > epNumber && MainData.episodes[i].episodeState != Consts.EpisodeStates.Unavailable) { MainData.episodes[i].episodeState = Consts.EpisodeStates.NotPlayed; } } // Syncronise last checkpoint and global variables foreach (var globalVar in MainData.variables) { foreach (var variable in destPoint.variables) { if (variable.storyVariable == globalVar.storyVariable) { globalVar.currentValue = variable.currentValue; break; } if (ShouldGlobalVarBeReseted(globalVar.storyVariable.Value, destPointId)) { globalVar.currentValue = 0; } } } SyncLastAndCurrentCheckpoints(destPoint, epNumber); MainData.uniqueId = Guid.NewGuid(); MainData.currentObjective = destPoint.currentObjective; RewindHeader(); }
/// <summary> /// 更新配置文件内容 /// </summary> /// <returns>成功写入配置文件的服务器的数量,0表示配置文件未修改</returns> private int UpdateFile() { if (ServerInfoFetcherCollection.Count() == 0) { throw new ApplicationException(Resources.NoFetcherEnabled); } // 获取服务器信息 ServerInfo[] serverInfoCollection = ( from fetcher in ServerInfoFetcherCollection.AsParallel() select fetcher.GetServers() ).Aggregate((x, y) => x.Concat(y)).ToArray <ServerInfo>(); serverInfoCollection = FilterByCountryAndUpdateCountryList(serverInfoCollection); if (serverInfoCollection.Count() == 0) { throw new ApplicationException(Resources.NoValidServer); } string str = (string)null; // 读取现有配置文件 JObject currentSettings; try { currentSettings = JObject.Parse(File.ReadAllText(OutputFileName())); str = ((object)currentSettings).ToString(); } catch (Exception) { currentSettings = new JObject(); } // 根据之前的服务器选择更新选择的服务器 int newIndex = -1; try { int oldIndex = currentSettings["index"].ToObject <int>(); if (oldIndex >= 0) { ServerInfo oldServer = ((JArray)currentSettings["configs"])[oldIndex].ToObject <ServerInfo>(); newIndex = BestMatchServer(serverInfoCollection, oldServer); } } catch (Exception) {} // 更新配置文件 currentSettings["configs"] = (JToken)JArray.FromObject((object)serverInfoCollection); currentSettings["index"] = (JToken) new JValue(newIndex); if (newIndex == -1 && currentSettings["strategy"].Type == JTokenType.Null) { currentSettings["strategy"] = "com.shadowsocks.strategy.ha"; } // 检查要输出的配置文件是否和原来完全一致,如果完全一致那么就不要打扰 string contents = ((object)currentSettings).ToString(); if (contents == str) { return(0); } File.WriteAllText(OutputFileName(), contents); return(serverInfoCollection.Length); }
public async Task <JObject> Post(string moduleName, [FromBody] JObject widgetList) { List <Widget> widgetUpdate = ((JArray)widgetList["widgets"]).Cast <JObject>() .Select(o => o.ToObject <Widget>()) .Where(w => w.Name != null) .ToList(); Module baseModule = await _context.Modules .Where(m => m.Name == moduleName ).FirstOrDefaultAsync(); List <Widget> baseWidgetList = await _context.Widgets .Include(w => w.Children) .ThenInclude(t => t.ChildWidget) .Where(p => p.Module.Name == moduleName ).ToListAsync(); Dictionary <Guid, string> widgetNameLookup = baseWidgetList.Select(w => new KeyValuePair <Guid, string>(w.WidgetId, w.Name) ).ToDictionary( kv => kv.Key, kv => kv.Value ); Dictionary <string, Guid> baseWidgetGuidLookup = baseWidgetList.Select(w => new KeyValuePair <string, Guid>(w.Name, w.WidgetId) ).ToDictionary( kv => kv.Key, kv => kv.Value ); List <Widget> newWidgets = widgetUpdate.Where(w => w.WidgetId == default(Guid)).ToList(); List <Widget> existingWidgets = widgetUpdate.Where(w => w.WidgetId != default(Guid)).ToList(); Dictionary <string, Guid> transformer = new Dictionary <string, Guid>(); Dictionary <string, List <Guid> > childList = new Dictionary <string, List <Guid> >(); for (int i = 0; i < newWidgets.Count; i++) { Guid newId = Guid.NewGuid(); transformer.Add(newWidgets[i].Name, newId); newWidgets[i].WidgetId = newId; newWidgets[i].Name = "NoName-" + newId.ToString(); widgetNameLookup.Add(newId, newWidgets[i].Name); } for (int i = 0; i < baseWidgetList.Count; i++) { Widget updateWidget = existingWidgets.Where(uw => uw.WidgetId == baseWidgetList[i].WidgetId).FirstOrDefault(); if (updateWidget != null) { JArray subWidgets = (JArray)updateWidget.WidgetProperties["subWidgets"]; baseWidgetList[i].DateModified = DateTime.UtcNow; baseWidgetList[i].ModifiedBy = Guid.Empty; baseWidgetList[i].Children = subWidgets.Cast <JToken>().Select((nameToken, sequence) => { string name = nameToken.ToString(); return(new WidgetTree() { WidgetTreeId = Guid.NewGuid(), DateCreated = DateTime.UtcNow, CreatedBy = Guid.Empty, DateModified = DateTime.UtcNow, ModifiedBy = Guid.Empty, IsActive = false, Sequence = sequence, WidgetId = baseWidgetList[i].WidgetId, ChildWidgetId = transformer.ContainsKey(name) ? transformer[name] : baseWidgetGuidLookup[name] }); }).ToList(); JObject updateProps = updateWidget.WidgetProperties; updateProps["subWidgets"] = JArray.FromObject(baseWidgetList[i].Children .OrderBy(c => c.Sequence ) .Select(c => widgetNameLookup[c.ChildWidgetId] ) ); baseWidgetList[i].WidgetProperties = updateProps; _context.Widgets.Update(baseWidgetList[i]); } } for (int i = 0; i < newWidgets.Count; i++) { JArray subWidgets = (JArray)newWidgets[i].WidgetProperties["subWidgets"]; if (subWidgets != null) { newWidgets[i].Children = subWidgets.Cast <JToken>().Select((nameToken, sequence) => { string name = nameToken.ToString(); return(new WidgetTree() { WidgetTreeId = Guid.NewGuid(), DateCreated = DateTime.UtcNow, CreatedBy = Guid.Empty, DateModified = DateTime.UtcNow, ModifiedBy = Guid.Empty, IsActive = false, Sequence = sequence, WidgetId = newWidgets[i].WidgetId, ChildWidgetId = transformer.ContainsKey(name) ? transformer[name] : baseWidgetGuidLookup[name] }); }).ToList(); } else { newWidgets[i].Children = new List <WidgetTree>(); } newWidgets[i].ModuleId = baseModule.ModuleId; newWidgets[i].Template = ""; newWidgets[i].DateCreated = DateTime.UtcNow; newWidgets[i].CreatedBy = Guid.Empty; newWidgets[i].DateModified = DateTime.UtcNow; newWidgets[i].ModifiedBy = Guid.Empty; newWidgets[i].IsActive = false; JObject updateProps = newWidgets[i].WidgetProperties; updateProps["subWidgets"] = JArray.FromObject(newWidgets[i].Children .OrderBy(c => c.Sequence ) .Select(c => widgetNameLookup[c.ChildWidgetId] ) ); newWidgets[i].WidgetProperties = updateProps; await _context.Widgets.AddAsync(newWidgets[i]); } await _context.SaveChangesAsync(); // return baseWidget == null ? null : JObject.FromObject(baseWidget); return(await Task.FromResult <JObject>(null)); }
//call to public IEnumerator PopulateContents(JArray inJData, bool subLevel = true, string parentName = "", bool createNewPanel = true, Category parentData = null, ThumbnailHelper parentThumbnail = null, bool updateInBg = false, bool forceBase = false, bool forceNumberThumbnails = false) { //Debug.Log(inJData); if (inJData == null) { //if there is no data, there is a possibility, it can be a custom category //add custom on click if (parentData != null) { OnClick(JToken.FromObject(parentData), parentThumbnail); } yield break; } #region Organising @inJData //organising the category and item data for proper sorting when displayed var jList = inJData.ToList(); var allCategories = JArray.FromObject(jList.TryAndFindList <Category>(cat => cat.HasValues)); var allItems = jList.TryAndFindList <Item>(item => item["Data"] != null); /*//sorting the item list -> newest always at top * allItems.Sort((a, b) => b.UploadDate.FromUnixTime().CompareTo(a.UploadDate.FromUnixTime())); //descending order*/ if (ItemPosFromJson) { allItems = (from item in allItems orderby item.PositionInList select item).ToList(); } var freeItems = allItems.FindAll(x => x.IsFree); var premiumItems = allItems.FindAll(x => !x.IsFree); var organisedItems = JArray.FromObject(freeItems.Concat(premiumItems)); var organisedData = allCategories.Concat(organisedItems).ToList(); #endregion CurrentParent = parentData; if (createNewPanel) { CreateSubPanel(parentData != null ? parentData.Name : parentName, parentData); } var holderPanel = subLevel ? SubLevelContent : CategoryContent; yield return(new WaitForEndOfFrame()); if (holderPanel == null) { yield break; //if no panel is there return } if (!updateInBg) //activate the panel if this is false { ViewController.Activate(holderPanel, UIType.NormalView, () => { if (ShowLoader) { UILoader.Instance.StartLoader(); } }); } var thumbnailPrefab = HybridPrefab; if (ContainsOnlyItems) { thumbnailPrefab = ItemPrefab; } //getting the override script var overrideRule = GetComponent <CategoryPopulateOverride>(); //applying override populate script if (overrideRule != null && !forceBase) { overrideRule.OverrideCreateAndFill(holderPanel, thumbnailPrefab, organisedData, ContainsOnlyItems, forceNumberThumbnails); } else { CreateAndFill(holderPanel, thumbnailPrefab, organisedData, ContainsOnlyItems, forceNumberThumbnails); } CallBackOnPopulate.Invoke(); yield return(new WaitForSeconds(0.5f)); if (ShowLoader) { UILoader.Instance.StopLoader(true); } }
public static void _outputTestFiles(string testRepoUsername, string testRepoPassword, string testRepoRegistry, string batchExtensionTemplatesRootDir, List <OutputContainerImage> imageDefinitions, List <string> imagesWithTagsToTest) { PublishContainerImages.WriteLog($"\nWriting test files for the following images:\n { string.Join("\n", imageDefinitions.Select(image => image.TestContainerImage))}"); var imagesWithTests = _removeInvalidPayloads(imageDefinitions); var updatedImageDefinitions = _updateTestConfigAndParametersWithTaggedImage(imagesWithTests); updatedImageDefinitions.ForEach(payload => { var parametersPath = Path.Combine(OutputTestPath(), payload.Payload.TestConfigurationDefinition.GetParametersFileName()); var parametersJson = Json.JsonSerializeObject(payload.Payload.TestParametersDefinition); FileInfo paramsFile = new FileInfo(parametersPath); Directory.CreateDirectory(paramsFile.DirectoryName); File.WriteAllText(parametersPath, parametersJson); PublishContainerImages.WriteLog($"\nWrote parameters file at: {paramsFile.FullName}, file contents:"); PublishContainerImages.WriteLog(parametersJson); }); updatedImageDefinitions.ForEach(payload => { var runnerDirectory = Path.Combine(ExecutableDirectory(), batchExtensionTemplatesRootDir, "runner"); var poolTemplateOriginalFullPath = Path.Combine(runnerDirectory, payload.Payload.TestConfigurationDefinition.PoolTemplate); var poolTemplateDynamic = Json.ReadJsonFileToDynamic(poolTemplateOriginalFullPath); if (!string.IsNullOrEmpty(testRepoUsername)) { var containerRegistries = JArray.FromObject(new[] { new { username = testRepoUsername, password = testRepoPassword, registryServer = testRepoRegistry } }); poolTemplateDynamic.variables.osType.containerConfiguration.containerRegistries = containerRegistries; } var poolTemplateJson = Json.JsonSerializeObject(poolTemplateDynamic); var relativeFinalPathForPoolTemplate = payload.Payload.TestConfigurationDefinition.PoolTemplate.Replace("../", ""); var poolTemplateFinalPath = Path.Combine(OutputTestPath(), relativeFinalPathForPoolTemplate); payload.Payload.TestConfigurationDefinition.PoolTemplate = poolTemplateFinalPath.Replace("\\", "/"); FileInfo poolTemplateFinal = new FileInfo(poolTemplateFinalPath); Directory.CreateDirectory(poolTemplateFinal.DirectoryName); File.WriteAllText(poolTemplateFinalPath, poolTemplateJson); PublishContainerImages.WriteLog($"\nWrote pool template file at: {poolTemplateFinalPath}, file contents:"); PublishContainerImages.WriteLog(poolTemplateJson); }); var testsConfiguration = new TestsDefinition { Tests = updatedImageDefinitions.Select(payload => { var config = payload.Payload.TestConfigurationDefinition; config.Parameters = Path.Combine(OutputTestPath(), config.GetParametersFileName()).Replace("\\", "/"); return(config); }).ToArray(), Images = new[] { new TestMarketplaceImageDefinition { Offer = "microsoft-azure-batch", OsType = "linux", Publisher = "centos-container", Sku = "7-5", Version = "latest", }, new TestMarketplaceImageDefinition { Offer = "microsoft-azure-batch", OsType = "linux", Publisher = "ubuntu-server-container", Sku = "16-04-lts", Version = "latest", } } }; var testsConfigurationFilepath = Path.Combine(OutputTestPath(), PublishContainerImages.TestConfigurationFilename); var testsConfigurationJson = Json.JsonSerializeObject(testsConfiguration); FileInfo configFile = new FileInfo(testsConfigurationFilepath); Directory.CreateDirectory(configFile.DirectoryName); File.WriteAllText(testsConfigurationFilepath, testsConfigurationJson); PublishContainerImages.WriteLog($"\nWrote configuration file at: {configFile.FullName}, file contents:"); PublishContainerImages.WriteLog(testsConfigurationJson); }
private async Task <bool> InvokeUserinfoEndpointAsync() { OpenIdConnectMessage request; if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { request = new OpenIdConnectMessage(Request.Query); } else if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { // See http://openid.net/specs/openid-connect-core-1_0.html#FormSerialization if (string.IsNullOrWhiteSpace(Request.ContentType)) { Options.Logger.LogError("The userinfo request was rejected because " + "the mandatory 'Content-Type' header was missing."); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received: " + "the mandatory 'Content-Type' header was missing from the POST request." })); } // May have media/type; charset=utf-8, allow partial match. if (!Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { Options.Logger.LogError("The userinfo request was rejected because an invalid 'Content-Type' " + "header was received: {ContentType}.", Request.ContentType); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received: " + "the 'Content-Type' header contained an unexcepted value. " + "Make sure to use 'application/x-www-form-urlencoded'." })); } request = new OpenIdConnectMessage(await Request.ReadFormAsync()); } else { Options.Logger.LogError("The userinfo request was rejected because an invalid " + "HTTP method was received: {Method}.", Request.Method); return(await SendErrorPageAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received: " + "make sure to use either GET or POST." })); } // Insert the userinfo request in the OWIN context. Context.SetOpenIdConnectRequest(request); string token; if (!string.IsNullOrEmpty(request.AccessToken)) { token = request.AccessToken; } else { var header = Request.Headers.Get("Authorization"); if (string.IsNullOrEmpty(header)) { Options.Logger.LogError("The userinfo request was rejected because " + "the 'Authorization' header was missing."); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received." })); } if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { Options.Logger.LogError("The userinfo request was rejected because the " + "'Authorization' header was invalid: {Header}.", header); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received." })); } token = header.Substring("Bearer ".Length); if (string.IsNullOrEmpty(token)) { Options.Logger.LogError("The userinfo request was rejected because access token was missing."); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed userinfo request has been received." })); } } var ticket = await DeserializeAccessTokenAsync(token, request); if (ticket == null) { Options.Logger.LogError("The userinfo request was rejected because access token was invalid."); // Note: an invalid token should result in an unauthorized response // but returning a 401 status would invoke the previously registered // authentication middleware and potentially replace it by a 302 response. // To work around this limitation, a 400 error is returned instead. // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoError return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Invalid token." })); } if (!ticket.Properties.ExpiresUtc.HasValue || ticket.Properties.ExpiresUtc < Options.SystemClock.UtcNow) { Options.Logger.LogError("The userinfo request was rejected because access token was expired."); // Note: an invalid token should result in an unauthorized response // but returning a 401 status would invoke the previously registered // authentication middleware and potentially replace it by a 302 response. // To work around this limitation, a 400 error is returned instead. // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoError return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidGrant, ErrorDescription = "Expired token." })); } var validatingContext = new ValidateUserinfoRequestContext(Context, Options, request); await Options.Provider.ValidateUserinfoRequest(validatingContext); // Stop processing the request if Validated was not called. if (!validatingContext.IsValidated) { Options.Logger.LogInformation("The userinfo request was rejected by application code."); return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = validatingContext.Error ?? OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = validatingContext.ErrorDescription, ErrorUri = validatingContext.ErrorUri })); } var notification = new HandleUserinfoRequestContext(Context, Options, request, ticket); notification.Subject = ticket.Identity.GetClaim(ClaimTypes.NameIdentifier); notification.Issuer = Context.GetIssuer(Options); // Note: when receiving an access token, its audiences list cannot be used for the "aud" claim // as the client application is not the intented audience but only an authorized presenter. // See http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse foreach (var presenter in ticket.GetPresenters()) { notification.Audiences.Add(presenter); } // The following claims are all optional and should be excluded when // no corresponding value has been found in the authentication ticket. if (ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) { notification.FamilyName = ticket.Identity.GetClaim(ClaimTypes.Surname); notification.GivenName = ticket.Identity.GetClaim(ClaimTypes.GivenName); notification.BirthDate = ticket.Identity.GetClaim(ClaimTypes.DateOfBirth); } if (ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) { notification.Email = ticket.Identity.GetClaim(ClaimTypes.Email); } ; if (ticket.HasScope(OpenIdConnectConstants.Scopes.Phone)) { notification.PhoneNumber = ticket.Identity.GetClaim(ClaimTypes.HomePhone) ?? ticket.Identity.GetClaim(ClaimTypes.MobilePhone) ?? ticket.Identity.GetClaim(ClaimTypes.OtherPhone); } ; await Options.Provider.HandleUserinfoRequest(notification); if (notification.HandledResponse) { return(true); } else if (notification.Skipped) { return(false); } // Ensure the "sub" claim has been correctly populated. if (string.IsNullOrEmpty(notification.Subject)) { Options.Logger.LogError("The mandatory 'sub' claim was missing from the userinfo response."); Response.StatusCode = 500; return(await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.ServerError, ErrorDescription = "The mandatory 'sub' claim was missing." })); } var payload = new JObject { [JwtRegisteredClaimNames.Sub] = notification.Subject }; if (notification.Address != null) { payload[OpenIdConnectConstants.Claims.Address] = notification.Address; } if (!string.IsNullOrEmpty(notification.BirthDate)) { payload[JwtRegisteredClaimNames.Birthdate] = notification.BirthDate; } if (!string.IsNullOrEmpty(notification.Email)) { payload[JwtRegisteredClaimNames.Email] = notification.Email; } if (notification.EmailVerified.HasValue) { payload[OpenIdConnectConstants.Claims.EmailVerified] = notification.EmailVerified.Value; } if (!string.IsNullOrEmpty(notification.FamilyName)) { payload[JwtRegisteredClaimNames.FamilyName] = notification.FamilyName; } if (!string.IsNullOrEmpty(notification.GivenName)) { payload[JwtRegisteredClaimNames.GivenName] = notification.GivenName; } if (!string.IsNullOrEmpty(notification.Issuer)) { payload[JwtRegisteredClaimNames.Iss] = notification.Issuer; } if (!string.IsNullOrEmpty(notification.PhoneNumber)) { payload[OpenIdConnectConstants.Claims.PhoneNumber] = notification.PhoneNumber; } if (notification.PhoneNumberVerified.HasValue) { payload[OpenIdConnectConstants.Claims.PhoneNumberVerified] = notification.PhoneNumberVerified.Value; } if (!string.IsNullOrEmpty(notification.PreferredUsername)) { payload[OpenIdConnectConstants.Claims.PreferredUsername] = notification.PreferredUsername; } if (!string.IsNullOrEmpty(notification.Profile)) { payload[OpenIdConnectConstants.Claims.Profile] = notification.Profile; } if (!string.IsNullOrEmpty(notification.Website)) { payload[OpenIdConnectConstants.Claims.Website] = notification.Website; } switch (notification.Audiences.Count) { case 0: break; case 1: payload.Add(JwtRegisteredClaimNames.Aud, notification.Audiences[0]); break; default: payload.Add(JwtRegisteredClaimNames.Aud, JArray.FromObject(notification.Audiences)); break; } foreach (var claim in notification.Claims) { // Ignore claims whose value is null. if (claim.Value == null) { continue; } payload.Add(claim.Key, claim.Value); } var context = new ApplyUserinfoResponseContext(Context, Options, request, payload); await Options.Provider.ApplyUserinfoResponse(context); if (context.HandledResponse) { return(true); } else if (context.Skipped) { return(false); } using (var buffer = new MemoryStream()) using (var writer = new JsonTextWriter(new StreamWriter(buffer))) { payload.WriteTo(writer); writer.Flush(); Response.ContentLength = buffer.Length; Response.ContentType = "application/json;charset=UTF-8"; Response.Headers.Set("Cache-Control", "no-cache"); Response.Headers.Set("Pragma", "no-cache"); Response.Headers.Set("Expires", "-1"); buffer.Seek(offset: 0, loc: SeekOrigin.Begin); await buffer.CopyToAsync(Response.Body, 4096, Request.CallCancelled); } return(true); }
public static string Build(string name = "", string value = "[]", int?provinceId = null) { if (value == null) { value = "[]"; } var ids = JArray.FromObject(JsonConvert.DeserializeObject(value)); var defaultListNames = ""; if (ids != null && ids.Count > 0) { defaultListNames += "<ul class='line-height-25 margin-top-6'>"; foreach (string id in ids) { defaultListNames += $@"<li>{RemarkUserId.Build(int.Parse(id))}</li>"; } defaultListNames += "</ul>"; } var markup = $@" <div> <a class='btn btn-info' data-role=""json"" href='/InterviewModule/SelectUserMulti/{provinceId}' onclick='return PopupCenter(this.href, ""ExirUserMultiSelect"", 900, 700)'>انتخاب</a> </div> <input type='hidden' name='{name}' value='{value}' id='RegateUserMulti_{name}' /> <div id='RegateUserMulti_{name}_List'>{defaultListNames}</div> "; var initScript = @" <script> function initRegateUserMulti(name) { window['__setUserMulti_' + name] = function(users) { console.log(users); var $list = $('#RegateUserMulti_' + name + '_List'); var $input = $('#RegateUserMulti_' + name); if (users.length === 0) { $input.val('[]'); $list.html(''); return true; } var $ul = $('<ul></ul>'); var ids = []; $.each(users, function(index, user) { $('<li></li>').text(user.FullName).appendTo($ul); ids.push(user.Id + ''); }); $list.html(''); $ul.appendTo($list); $input.val(JSON.stringify(ids)); $.fn.matchHeight._update(); } } </script> "; var script = $@" <script> initRegateUserMulti('{name}'); </script> "; return(markup + initScript + script); }
/// <summary> /// Invokes the callback. /// </summary> /// <param name="arguments">The callback arguments.</param> public void Invoke(params object[] arguments) { _instance.InvokeCallback(_id, arguments != null ? JArray.FromObject(arguments) : s_empty); }
public Program() { Get("/mine", _ => { var lastBlock = blockchain.LastBlock; var proof = Blockchain.ProofOfWork(lastBlock); blockchain.NewTransaction(sender: "0", recipient: nodeIdentifier, amount: 1); var previousHash = Blockchain.Hash(lastBlock); var block = blockchain.NewBlock(proof, previousHash); var response = new JObject { { "message", "New Block Forged" }, { "index", block.Index }, { "transactions", JArray.FromObject(block.Transactions) }, { "proof", block.Proof }, { "previous_hash", block.PreviousHash }, }; return(((Response)(response.ToString(Formatting.None))) .WithStatusCode(HttpStatusCode.OK).WithContentType("application/json")); }); Post("/transactions/new", _ => { var values = JObject.Parse(Request.Body.AsString()); var required = new[] { "sender", "recipient", "amount" }; if (required.Any(x => values[x] == null)) { return(Negotiate.WithStatusCode(HttpStatusCode.BadRequest).WithModel("Missing values")); } var index = blockchain.NewTransaction((string)values["sender"], (string)values["recipient"], (long)values["amount"]); var response = new JObject { { "message", $"Transaction will be added to Block {index}" } }; return(((Response)(response.ToString(Formatting.None))) .WithStatusCode(HttpStatusCode.Created).WithContentType("application/json")); }); Get("/chain", _ => { var response = new JObject { { "chain", JArray.FromObject(blockchain.Chain) }, { "length", blockchain.Chain.Count }, }; return(((Response)(response.ToString(Formatting.None))) .WithStatusCode(HttpStatusCode.OK).WithContentType("application/json")); }); Post("/nodes/register", _ => { var values = JObject.Parse(Request.Body.AsString()); var nodes = values["nodes"].ToObject <IList <string> >(); if (nodes == null) { return(Negotiate.WithStatusCode(HttpStatusCode.BadRequest).WithModel("Error: Please supply a valid list of nodes")); } foreach (var node in nodes) { blockchain.RegisterNode(node); } var response = new JObject { { "message", "New nodes have been added" }, { "total_nodes", JArray.FromObject(blockchain.Nodes) }, }; return(((Response)(response.ToString(Formatting.None))) .WithStatusCode(HttpStatusCode.Created).WithContentType("application/json")); }); Get("/nodes/resolve", async _ => { var replaced = await blockchain.ResolveConflicts(); var response = replaced ? new JObject { { "message", "Our chain was replaced" }, { "new_chain", JArray.FromObject(blockchain.Chain) }, } : new JObject { { "message", "Our chain is authoritative" }, { "chain", JArray.FromObject(blockchain.Chain) }, }; return(((Response)(response.ToString(Formatting.None))) .WithStatusCode(HttpStatusCode.OK).WithContentType("application/json")); }); }
public string ToJson() { string result = JArray.FromObject(this).ToString(); return(result); }
public JArray SerializeParts() { return(JArray.FromObject(parts.Select(p => p.Serialize()))); }
public async System.Threading.Tasks.Task <FileResult> DownloadAsync(string clientId) { GraphIntune graphIntune = new GraphIntune(clientId); SignalRMessage signalRMessage = new SignalRMessage(clientId); try { var deviceCompliancePolicies = await graphIntune.GetDeviceCompliancePoliciesAsync(); var deviceConfigurations = await graphIntune.GetDeviceConfigurationsAsync(); var managedAppProtection = await graphIntune.GetManagedAppProtectionAsync(); var managedAppConfiguration = await graphIntune.GetManagedDeviceMobileAppConfigurationsAsync(); var windowsAutopilotDeploymentProfiles = await graphIntune.GetWindowsAutopilotDeploymentProfiles(); var deviceManagementScripts = await graphIntune.GetDeviceManagementScriptsAsync(); var deviceEnrollmentConfig = await graphIntune.GetDeviceEnrollmentConfigurationsAsync(); var scopeTags = await graphIntune.GetRoleScopeTagsAsync(); var roleAssignments = await graphIntune.GetRoleAssignmentsAsync(); //var gpos = await graphIntune.GetGroupPolicyConfigurationsAsync(); //foreach (GroupPolicyConfiguration gpo in gpos) //{ // var values = await graphIntune.GetGroupPolicyDefinitionValuesAsync(gpo.Id); // signalRMessage.sendMessage(JsonConvert.SerializeObject(gpo, Formatting.Indented) + JsonConvert.SerializeObject(values, Formatting.Indented)); // foreach (GroupPolicyDefinitionValue value in values) // { // var res = await graphIntune.GetGroupPolicyPresentationValuesAsync(value.Id); // signalRMessage.sendMessage(JsonConvert.SerializeObject(res, Formatting.Indented)); // } //} using (MemoryStream ms = new MemoryStream()) { using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (DeviceEnrollmentConfiguration item in deviceEnrollmentConfig) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); var zipArchiveEntry = archive.CreateEntry("DeviceEnrollmentConfiguration\\" + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (DeviceConfiguration item in deviceConfigurations) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("DeviceConfiguration\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (DeviceCompliancePolicy item in deviceCompliancePolicies) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("DeviceCompliancePolicy\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (ManagedDeviceMobileAppConfiguration item in managedAppConfiguration) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("ManagedAppPolicy\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (ManagedAppPolicy item in managedAppProtection) { if (item.ODataType.Equals("#microsoft.graph.iosManagedAppProtection") || item.ODataType.Equals("#microsoft.graph.androidManagedAppProtection")) { var assignedApps = await graphIntune.GetManagedAppProtectionAssignmentAsync(item.Id); // Create json object from mam policy JObject appProtectionPolicy = JObject.FromObject(item); JArray appProtectionPolicyAssignedApps = JArray.FromObject(assignedApps); // Add assigned apps to export appProtectionPolicy.Add("assignedApps", appProtectionPolicyAssignedApps); byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(appProtectionPolicy, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("ManagedAppPolicy\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } else if (item.ODataType.Equals("#microsoft.graph.targetedManagedAppConfiguration")) { var assignedApps = await graphIntune.GetTargetedManagedAppConfigurationsAssignedAppsAsync(item.Id); // Create json object from mam policy JObject appProtectionPolicy = JObject.FromObject(item); JArray appProtectionPolicyAssignedApps = JArray.FromObject(assignedApps); // Add assigned apps to export appProtectionPolicy.Add("assignedApps", appProtectionPolicyAssignedApps); byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(appProtectionPolicy, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("ManagedAppPolicy\\" + "ManagedAppConfiguration_" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } else { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("ManagedAppPolicy\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } } foreach (WindowsAutopilotDeploymentProfile item in windowsAutopilotDeploymentProfiles) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("WindowsAutopilotDeploymentProfile\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (DeviceManagementScript item in deviceManagementScripts) { string fixedItem = await graphIntune.GetDeviceManagementScriptRawAsync(item.Id); byte[] temp = Encoding.UTF8.GetBytes(fixedItem); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("DeviceManagementScript\\" + fileName + "_" + item.Id.Substring(0, 8) + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (RoleScopeTag item in scopeTags) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("RoleScopeTags\\" + fileName + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } foreach (DeviceAndAppManagementRoleAssignment item in roleAssignments) { byte[] temp = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(item, Formatting.Indented)); string fileName = FilenameHelper.ProcessFileName(item.DisplayName); var zipArchiveEntry = archive.CreateEntry("RoleAssignments\\" + fileName + ".json", CompressionLevel.Fastest); using (var zipStream = zipArchiveEntry.Open()) zipStream.Write(temp, 0, temp.Length); } } string domainName = await GraphHelper.GetDefaultDomain(clientId); return(File(ms.ToArray(), "application/zip", "IntuneConfig_" + domainName + ".zip")); } } catch (Exception e) { signalRMessage.sendMessage($"Error {e.Message}"); return(File(new MemoryStream(), "application/zip", "IntuneConfig_.zip")); } }
public void SendPushNotification() { string sLanguageCode = string.Empty; if (enmLanguage == Languages.Arabic) { sLanguageCode = ConstantNames.ArabicLanguageCode; } else { sLanguageCode = ConstantNames.EnglishLanguageCode; } var oWebRequest = WebRequest.Create(CommonHelper.sGetConfigKeyValue(ConstantNames.OneSignalServiceURL)) as HttpWebRequest; oWebRequest.KeepAlive = true; oWebRequest.Method = "POST"; oWebRequest.ContentType = "application/json; charset=utf-8"; string sAutherizationKey = string.Format("Basic {0}", sOneSignalAuthKey); oWebRequest.Headers.Add("authorization", sAutherizationKey); var oSerializer = new JavaScriptSerializer(); try { dynamic JObjectData = new JObject(); JObjectData.app_id = sOneSignalAppID; if (enmLanguage == Languages.Arabic) { JObjectData.headings = new JObject( new JProperty("en", sHeadings), new JProperty(sLanguageCode, sHeadings) ); } else { JObjectData.headings = new JObject( new JProperty(sLanguageCode, sHeadings) ); } if (enmLanguage == Languages.Arabic) { JObjectData.contents = new JObject( new JProperty("en", sContent), new JProperty(sLanguageCode, sContent) ); } else { JObjectData.contents = new JObject( new JProperty(sLanguageCode, sContent) ); } switch (NotificationType) { case enmNotificationType.News: JObjectData.data = new JObject( new JProperty("News", "News"), new JProperty("NewsID", sRecordID), new JProperty("LanguageID", (int)enmLanguage) ); break; case enmNotificationType.Events: JObjectData.data = new JObject( new JProperty("Events", "Events"), new JProperty("EventID", sRecordID), new JProperty("LanguageID", (int)enmLanguage) ); break; case enmNotificationType.Tickets: JObjectData.data = new JObject( new JProperty("Tickets", "Tickets"), new JProperty("TicketID", sRecordID), new JProperty("LanguageID", (int)enmLanguage) ); break; case enmNotificationType.TicketChats: JObjectData.content_available = true; JObjectData.data = new JObject( new JProperty("TicketChats", "TicketChats"), new JProperty("TicketID", oTicketChatViewModel.TICKET_ID), new JProperty("TicketChatID", oTicketChatViewModel.ID), new JProperty("ReplyMsg", oTicketChatViewModel.REPLY_MESSAGE), new JProperty("ReplyDate", oTicketChatViewModel.REPLIED_DATE), new JProperty("RemoteFilePath", oTicketChatViewModel.REPLY_FILE_PATH), new JProperty("TicketChatType", oTicketChatViewModel.TICKET_CHAT_TYPE_ID), new JProperty("UserId", 1), new JProperty("Username", "Admin123"), new JProperty("Typename", oTicketChatViewModel.CHAT_TYPE) ); break; } if (sDeviceID != "") { string[] arrry = sDeviceID.Split(','); JObjectData.include_player_ids = JArray.FromObject(arrry); } else { JObjectData.included_segments = new JArray("All"); } sRequestJSON = JObjectData.ToString(Newtonsoft.Json.Formatting.None); byte[] arrBytes = Encoding.UTF8.GetBytes(JObjectData.ToString(Newtonsoft.Json.Formatting.None)); using (var writer = oWebRequest.GetRequestStream()) { writer.Write(arrBytes, 0, arrBytes.Length); } using (var response = oWebRequest.GetResponse() as HttpWebResponse) { using (var reader = new StreamReader(response.GetResponseStream())) { this.bIsSentNotification = true; this.sResponseResult = reader.ReadToEnd(); } } } catch (WebException ex) { Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Elmah.Error(ex)); } }
public async Task <object> getResAsync(JsonRPCrequest req, string reqAddr) { JArray result = new JArray(); string resultStr = string.Empty; string findFliter = string.Empty; string sortStr = string.Empty; try { switch (req.method) { #region 获取block case "getblock": result = msq.GetBlock(req); break; case "getacblock": result = msq.GetAppChainBlock(req); break; #endregion #region 获取blocks case "getblocks": result = msq.GetBlocks(req); break; case "getappchainblocks": result = msq.GetAppchainBlocks(req); break; case "getblocksdesc": result = msq.GetBlocksDESC(req); break; case "getappchainblocksdesc": result = msq.GetAppchainBlocksDESC(req); break; case "getblocksdesccache": result = msq.GetBlocksDESCCache(req); break; case "getappchainblocksdesccache": result = msq.GetAppchainBlocksDESCCache(req); break; #endregion #region 获取block from hash case "getblockfromhash": result = msq.GetBlockFromHash(req); break; case "getappchainblockfromhash": result = msq.GetAppChainBlockFromHash(req); break; #endregion #region 获取blockcount case "getblockcount": var blockcount = Helper.MakeRpcUrl(ZoroHelper.ZoroUrl, "getblockcount", rootChain); var s = await Helper.HttpGet(blockcount); var a = new JArray(); a.Add(new JObject { { "blockcount", JObject.Parse(s)["result"].ToString() } }); result = a; break; case "getappchainblockcount": var appchainblockcount = Helper.MakeRpcUrl(ZoroHelper.ZoroUrl, "getblockcount", req.@params[0].ToString()); var apps = await Helper.HttpGet(appchainblockcount); var appa = new JArray(); appa.Add(new JObject { { "blockcount", JObject.Parse(apps)["result"].ToString() } }); result = appa; break; #endregion #region 获取爬虫爬到的blockcount case "getdatablockheight": result = msq.GetDataBlockHeight(req); break; case "getappchaindatablockheight": result = msq.GetAppchainBlockCount(req); break; #endregion #region 获取addrcount case "getaddrcount": result = msq.GetAddrCount(req); break; case "getappchainaddrcount": result = msq.GetAppchainAddrCount(req); break; #endregion #region 获取txcount case "gettxcount": result = msq.GetTxCount(req); break; case "getappchaintxcount": result = msq.GetAppchainTxCount(req); break; #endregion #region 获取rawtransaction case "getrawtransaction": result = msq.GetRawTransaction(req); break; case "getacrawtransaction": result = msq.GetAppChainRawTransaction(req); break; #endregion #region 获取transaction case "gettransaction": result = msq.GetTransaction(req); break; case "getactransaction": result = msq.GetAppChainTransaction(req); break; #endregion #region 获取transaction_ex case "gettransactions_ex": result = msq.GetTransactions_EX(req); break; case "getactransactions_ex": result = msq.GetAppChainTransactions_EX(req); break; #endregion #region 获取rawtransactions case "getrawtransactions": result = msq.GetRawTransactions(req); break; case "getappchainrawtransactions": result = msq.GetAppchainRawTransactions(req); break; case "getrawtransactionsdesc": result = msq.GetRawTransactionsDESC(req); break; case "getappchainrawtransactionsdesc": result = msq.GetAppchainRawTransactionsDESC(req); break; case "getrawtransactionsdesccache": result = msq.GetRawTransactionsDESCCache(req); break; case "getappchainrawtransactionsdesccache": result = msq.GetAppchainRawTransactionsDESCCache(req); break; #endregion #region 获取allnep5asset case "getallnep5asset": result = msq.GetAllNep5Asset(req); break; case "getappchainallnep5asset": result = msq.GetAllNep5AssetByChainHash(req); break; #endregion #region 获取hashlist,appchain case "gethashlist": result = msq.GetHashlist(req); break; case "getallappchains": result = msq.GetAllAppchains(req); break; case "getappchain": result = msq.GetAppchain(req); break; #endregion #region 获取nep5asset case "getnep5asset": result = msq.GetNep5Asset(req); break; case "getappchainnep5asset": result = msq.GetAppChainNep5Asset(req); break; case "getaddressasset": result = msq.GetAddressAsset(req); break; case "getaddressallasset": result = await msq.GetAddressAllAssetAsync(req); break; #endregion #region 获取address case "getaddress": result = msq.GetAddress(req); break; case "getappchainaddress": result = msq.GetAppChainAddress(req); break; #endregion #region 获取addr case "getaddr": result = msq.GetAddr(req); break; case "getappchainaddr": result = msq.GetAppChainAddr(req); break; #endregion #region 获取addrs case "getaddrs": result = msq.GetAddrs(req); break; case "getappchainaddrs": result = msq.GetAppChainAddrs(req); break; #endregion #region 获取addresstxs case "getaddresstxs": result = msq.GetAddressTxs(req); break; case "getappchainaddresstxs": result = msq.GetAppChainAddressTxs(req); break; case "getaddressnep5txs": result = msq.GetAddressNep5Txs(req); break; #endregion #region 获取balance case "getbalance": result = await msq.GetBalanceByAssetAsync(req); break; case "getbalancebyasset": result = await msq.GetAssetBalanceAsync(req); break; case "getappchainbalance": result = await msq.GetAppChainBalanceAsync(req); break; #endregion #region 获取utxo case "getutxo": result = msq.GetUTXO(req); break; case "getappchainutxo": result = msq.GetAppChainUTXO(req); break; #endregion #region 获取rankasset case "getrankbyasset": result = msq.GetRankByAsset(req); break; case "getappchainrankbyasset": result = msq.GetAppChainRankByAsset(req); break; #endregion #region 获取rankbyassetcount case "getrankbyassetcount": result = msq.GetRankByAssetCount(req); break; case "getappchainrankbyassetcount": result = msq.GetAppChainRankByAssetCount(req); break; #endregion #region 获取nep5transferbytxid case "getnep5transferbytxid": result = msq.GetNep5TransferByTxid(req); break; case "getappchainnep5transferbytxid": result = msq.GetAppChainNep5TransferByTxid(req); break; #endregion #region 获取nep5transferbytxidex case "getnep5transferbytxidex": result = msq.GetNep5TransferByTxidEX(req); break; case "getappchainnep5transferbytxidex": result = msq.GetAppChainNep5TransferByTxidEX(req); break; #endregion #region 获取nep5transferbytxids case "getnep5transferbytxids": result = msq.GetNep5TransferByTxids(req); break; case "gettransferbytxids": result = msq.GetTransferByTxids(req); break; #endregion #region 获取nep5transfer case "getnep5transfer": result = msq.GetNep5Transfer(req); break; case "getappchainnep5transfer": result = msq.GetAppChainNep5Transfer(req); break; case "getnep5transferbyasset": result = msq.GetNep5TransferByAsset(req); break; case "getnep5transferbyassetandaddress": result = msq.GetNep5TransferByAssetAndAddress(req); break; case "getsendallamountbyaddress": result = msq.GetSendAllAmountByAddress(req); break; #endregion #region 获取 nft 相关信息 case "getnftfromaddrandhash": result = msq.GetNFTFromAddrAndHash(req); break; case "getnfthashfromaddr": result = msq.GetNFTHashFromAddr(req); break; case "getnftfromhash": result = msq.GetNFTFromHash(req); break; case "gettokenproperties": result = msq.getProperties(req); break; #endregion #region 和链交互 case "sendrawtransaction": var tx = ""; if ([email protected] > 1) { if (req.@params[0].ToString() == "") { chainhash = rootChain; } else { chainhash = req.@params[0].ToString(); } tx = await ZoroHelper.SendRawTransaction(req.@params[1].ToString(), chainhash); } else { //byte[] postArray = APIHelper.HexString2Bytes(req.@params[0].ToString()); tx = await ZoroHelper.SendRawTransaction(req.@params[0].ToString(), rootChain); } if (JObject.Parse(tx)["result"].ToString() == "True") { result = new JArray() { new JObject { { "sendrawtransactionresult", JObject.Parse(tx)["result"] } } } } ; else { result = new JArray() { JObject.Parse(tx)["result"] } }; break; case "invokescript": var invokescript = ""; if ([email protected] > 1) { byte[] postArray = APIHelper.HexString2Bytes(req.@params[1].ToString()); invokescript = await ZoroHelper.InvokeScript(postArray, req.@params[0].ToString()); } else { byte[] postArray = APIHelper.HexString2Bytes(req.@params[0].ToString()); invokescript = await ZoroHelper.InvokeScript(postArray, rootChain); } result = new JArray() { JObject.Parse(invokescript)["result"] }; break; case "estimategas": decimal estimategas = 0; if ([email protected] > 1) { //byte[] postArray = APIHelper.HexString2Bytes(req.@params[1].ToString()); estimategas = await ZoroHelper.EstimateGas(req.@params[1].ToString(), req.@params[0].ToString()); } else { //byte[] postArray = APIHelper.HexString2Bytes(req.@params[0].ToString()); estimategas = await ZoroHelper.EstimateGas(req.@params[0].ToString(), rootChain); } result = new JArray() { new JObject { { "gas", estimategas } } }; break; case "getcontractstate": var url = ""; if ([email protected] > 1) { byte[] postArray = null; Zoro.IO.Json.JArray jArray = new Zoro.IO.Json.JArray(); jArray.Add(req.@params[0].ToString()); jArray.Add(req.@params[1].ToString()); url = Helper.MakeRpcUrlPost(ZoroHelper.ZoroUrl, "getcontractstate", out postArray, jArray); url = await Helper.HttpPost(url, postArray); } else { byte[] postArray = null; Zoro.IO.Json.JArray jArray = new Zoro.IO.Json.JArray(); jArray.Add(rootChain); jArray.Add(req.@params[0].ToString()); url = Helper.MakeRpcUrlPost(ZoroHelper.ZoroUrl, "getcontractstate", out postArray, jArray); url = await Helper.HttpPost(url, postArray); } result = new JArray() { JObject.Parse(url)["result"] }; break; #endregion #region 其他 case "getpagemessage": result = msq.getPageMessage(req.@params[0].ToString(), req.@params[1].ToString()); break; case "getnep5count": result = msq.GetNep5Count(req); break; case "getnep5allnep5assetofaddress": result = msq.GetAllNep5AssetOfAddress(req); break; case "getcontractmessage": string contractChainHash = ""; string contract = ""; if ([email protected] > 1) { if (req.@params[0].ToString() == "") { contractChainHash = rootChain; } else { contractChainHash = req.@params[0].ToString(); } contract = req.@params[1].ToString(); if (!contract.StartsWith("0x")) { contract = "0x" + contract; } result = msq.GetContractMessage(contractChainHash, contract); } else { contract = req.@params[0].ToString(); if (!contract.StartsWith("0x")) { contract = "0x" + contract; } result = msq.GetContractMessage(rootChain, contract); } break; case "getallnep5assetofaddress": string NEP5addr = (string)req.@params[0]; bool isNeedBalance = false; string chainHash = ""; if ([email protected]() > 1) { isNeedBalance = ((Int64)req.@params[1] == 1) ? true : false; } if ([email protected]() > 2) { chainHash = req.@params[2].ToString(); } var assetAdds = msq.GetNep5AssetByAddress(chainHash, NEP5addr); List <NEP5.AssetBalanceOfAddr> addrAssetBalances = new List <NEP5.AssetBalanceOfAddr>(); if (isNeedBalance) { //UInt160 addr = UInt160.Parse(ThinNeo.Helper.GetPublicKeyHashFromAddress(NEP5addr).ToString()); foreach (var assetAdd in assetAdds) { if (assetAdd["type"].ToString() == "NativeNep5") { var nep5 = await APIHelper.getNativeBalanceOfAsync(chainHash, assetAdd["assetid"].ToString(), NEP5addr); if (nep5.balance != "0") { addrAssetBalances.Add(nep5); } } else { var nep5 = await APIHelper.getBalanceOfAsync(chainHash, assetAdd["assetid"].ToString(), NEP5addr); if (nep5.balance != "0") { addrAssetBalances.Add(nep5); } } } } if (!isNeedBalance) { result = JArray.FromObject(assetAdds); } else { result = JArray.FromObject(addrAssetBalances); } break; #endregion } if (result != null && result.Count > 0 && result[0]["errorCode"] != null) { JsonPRCresponse_Error resE = new JsonPRCresponse_Error(req.id, (int)result[0]["errorCode"], (string)result[0]["errorMsg"], (string)result[0]["errorData"]); return(resE); } if (result.Count == 0) { JsonPRCresponse_Error resE = new JsonPRCresponse_Error(req.id, -1, "No Data", "Data does not exist"); return(resE); } } catch (Exception e) { JsonPRCresponse_Error resE = new JsonPRCresponse_Error(req.id, -100, "Parameter Error", e.Message); return(resE); } JsonPRCresponse res = new JsonPRCresponse(); res.jsonrpc = req.jsonrpc; res.id = req.id; res.result = result; return(res); }
/// <summary> /// 获取存储字符串 /// </summary> /// <returns></returns> public override string ToSaveString() { return(JArray.FromObject(all_items).ToString()); }
public async Task <IEnumerable <QueryIntervalValue <IEnumerable <QueryGroupValue <string> > > > > Metric(QueryType queryType, string collection, string targetProperty, string groupby, IQueryTimeframe timeframe, QueryInterval interval, IEnumerable <QueryFilter> filters = null, string timezone = "") { if (queryType == null) { throw new ArgumentNullException("queryType"); } if (string.IsNullOrWhiteSpace(collection)) { throw new ArgumentNullException("collection"); } if (string.IsNullOrWhiteSpace(targetProperty) && (queryType != QueryType.Count())) { throw new ArgumentNullException("targetProperty"); } if (null == timeframe) { throw new ArgumentException("timeframe", "Timeframe must be specified for a series query."); } if (null == interval) { throw new ArgumentNullException("interval", "interval must be specified for a series query"); } if (string.IsNullOrWhiteSpace(groupby)) { throw new ArgumentNullException("groupby", "groupby field name must be specified for a goupby query"); } var parms = new Dictionary <string, string>(); parms.Add(KeenConstants.QueryParmEventCollection, collection); parms.Add(KeenConstants.QueryParmTargetProperty, targetProperty); parms.Add(KeenConstants.QueryParmGroupBy, groupby); parms.Add(KeenConstants.QueryParmTimeframe, timeframe.ToSafeString()); parms.Add(KeenConstants.QueryParmInterval, interval.ToSafeString()); parms.Add(KeenConstants.QueryParmTimezone, timezone); parms.Add(KeenConstants.QueryParmFilters, filters == null ? "" : JArray.FromObject(filters).ToString()); var reply = await KeenWebApiRequest(queryType.ToString(), parms).ConfigureAwait(false); IEnumerable <QueryIntervalValue <IEnumerable <QueryGroupValue <string> > > > result; if (queryType == QueryType.SelectUnique()) { // This is to support SelectUnique which is the only query type with a list-type result. result = from i in reply.Value <JArray>("result") let v = (from r in i.Value <JArray>("value") let c = string.Join(",", r.Value <JArray>("result").Values <string>()) let g = r.Value <string>(groupby) select new QueryGroupValue <string>(c, g)) let t = i.Value <JObject>("timeframe") select new QueryIntervalValue <IEnumerable <QueryGroupValue <string> > >(v, t.Value <DateTime>("start"), t.Value <DateTime>("end")); } else { result = from i in reply.Value <JArray>("result") let v = (from r in i.Value <JArray>("value") let c = r.Value <string>("result") let g = r.Value <string>(groupby) select new QueryGroupValue <string>(c, g)) let t = i.Value <JObject>("timeframe") select new QueryIntervalValue <IEnumerable <QueryGroupValue <string> > >(v, t.Value <DateTime>("start"), t.Value <DateTime>("end")); } return(result); }
/// <summary> /// Sets a content property value using a deploy property. /// </summary> /// <param name="content">The content item.</param> /// <param name="alias">The property alias.</param> /// <param name="value">The deploy property value.</param> /// <remarks> /// This is a bit tricky because for each row of inner content we need to pass the value of it to it's related /// IValueConnector because each row is essentially a Property Type - though a fake one. /// So to do this we have to create a fake content item for the underlying IValueConnector to set it's value on and /// then we can extract that value from it to put on the main serialized object to set on the real IContentBase item. /// </remarks> public void SetValue(IContentBase content, string alias, string value) { if (string.IsNullOrWhiteSpace(value)) { content.SetValue(alias, value); return; } if (value.DetectIsJson() == false) { return; } var innerContent = JsonConvert.DeserializeObject <InnerContentValue[]>(value); if (innerContent == null) { return; } var allContentTypes = innerContent.Select(x => x.IcContentTypeAlias) .Distinct() .ToDictionary(a => a, a => _contentTypeService.GetContentType(a)); //Ensure all of these content types are found if (allContentTypes.Values.Any(contentType => contentType == null)) { throw new InvalidOperationException($"Could not resolve these content types for the Inner Content property: {string.Join(",", allContentTypes.Where(x => x.Value == null).Select(x => x.Key))}"); } var mocks = new Dictionary <IContentType, IContent>(); foreach (var row in innerContent) { var contentType = allContentTypes[row.IcContentTypeAlias]; // note // the way we do it here, doing content.SetValue() several time on the same content, reduces // allocations and should be ok because SetValue does not care about the previous value - would // be different for the overloads that manage eg files for uploads (not sure how NestedContent // deals with them really) // we need a fake content instance to pass in to the value connector, since the value connector // wants to SetValue on an object - then we can extract the value back from that object to set // it correctly on the real instance IContent mockContent; if (!mocks.TryGetValue(contentType, out mockContent)) { mockContent = mocks[contentType] = new Content("IC_" + Guid.NewGuid(), -1, contentType); } foreach (var key in row.PropertyValues.Keys.ToArray()) { var propertyType = contentType.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == key); if (propertyType == null) { LogHelper.Debug <InnerContentConnector>($"No Property Type found with alias {key} on Content Type {contentType.Alias}"); continue; } // throws if not found - no need for a null check var propValueConnector = ValueConnectors.Get(propertyType); var rowValue = row.PropertyValues[key]; if (rowValue != null) { propValueConnector.SetValue(mockContent, propertyType.Alias, rowValue.ToString()); var convertedValue = mockContent.GetValue(propertyType.Alias); // integers needs to be converted into strings if (convertedValue is int) { row.PropertyValues[key] = convertedValue.ToString(); } else { // test if the value is a json object (thus could be a nested complex editor) // if that's the case we'll need to add it as a json object instead of string to avoid it being escaped var jtokenValue = convertedValue.ToString().DetectIsJson() ? JToken.Parse(convertedValue.ToString()) : null; if (jtokenValue != null) { row.PropertyValues[key] = jtokenValue; } else { row.PropertyValues[key] = convertedValue; } } } else { row.PropertyValues[key] = rowValue; } } } // InnerContent does not use formatting when serializing JSON values value = JArray.FromObject(innerContent).ToString(Formatting.None); content.SetValue(alias, value); }
internal static JToken ExtractEntityValue(EntityModel entity) { if (entity.Type.StartsWith("builtin.geographyV2.", StringComparison.Ordinal)) { var subtype = entity.Type.Substring(20); return(new JObject( new JProperty("type", subtype), new JProperty("location", entity.Entity))); } if (entity.AdditionalProperties == null || !entity.AdditionalProperties.TryGetValue("resolution", out dynamic resolution)) { return(entity.Entity); } if (entity.Type.StartsWith("builtin.datetime.", StringComparison.Ordinal)) { return(JObject.FromObject(resolution)); } if (entity.Type.StartsWith("builtin.datetimeV2.", StringComparison.Ordinal)) { if (resolution.values == null || resolution.values.Count == 0) { return(JArray.FromObject(resolution)); } var resolutionValues = (IEnumerable <dynamic>)resolution.values; var type = resolution.values[0].type; var timexes = resolutionValues.Select(val => val.timex); var distinctTimexes = timexes.Distinct(); return(new JObject(new JProperty("type", type), new JProperty("timex", JArray.FromObject(distinctTimexes)))); } if (entity.Type.StartsWith("builtin.ordinalV2", StringComparison.Ordinal)) { return(new JObject( new JProperty("relativeTo", resolution.relativeTo), new JProperty("offset", Number(resolution.offset)))); } switch (entity.Type) { case "builtin.number": case "builtin.ordinal": return(Number(resolution.value)); case "builtin.percentage": { var svalue = (string)resolution.value; if (svalue.EndsWith("%", StringComparison.Ordinal)) { svalue = svalue.Substring(0, svalue.Length - 1); } return(Number(svalue)); } case "builtin.age": case "builtin.dimension": case "builtin.currency": case "builtin.temperature": { var units = (string)resolution.unit; var val = Number(resolution.value); var obj = new JObject(); if (val != null) { obj.Add("number", val); } obj.Add("units", units); return(obj); } default: return(resolution.value ?? (resolution.values != null ? JArray.FromObject(resolution.values) : resolution)); } }
private async Task InvokeValidationEndpointAsync() { OpenIdConnectMessage request; // See https://tools.ietf.org/html/rfc7662#section-2.1 // and https://tools.ietf.org/html/rfc7662#section-4 if (string.Equals(Request.Method, "GET", StringComparison.OrdinalIgnoreCase)) { request = new OpenIdConnectMessage(Request.Query.ToDictionary()) { RequestType = OpenIdConnectRequestType.AuthenticationRequest }; } else if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { // See http://openid.net/specs/openid-connect-core-1_0.html#FormSerialization if (string.IsNullOrEmpty(Request.ContentType)) { await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed validation request has been received: " + "the mandatory 'Content-Type' header was missing from the POST request." }); return; } // May have media/type; charset=utf-8, allow partial match. if (!Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed validation request has been received: " + "the 'Content-Type' header contained an unexcepted value. " + "Make sure to use 'application/x-www-form-urlencoded'." }); return; } var form = await Request.ReadFormAsync(Context.RequestAborted); request = new OpenIdConnectMessage(form.ToDictionary()) { RequestType = OpenIdConnectRequestType.AuthenticationRequest }; } else { Logger.LogInformation("A malformed request has been received by the validation endpoint."); await SendErrorPageAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed validation request has been received: " + "make sure to use either GET or POST." }); return; } if (string.IsNullOrWhiteSpace(request.GetToken())) { await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.InvalidRequest, ErrorDescription = "A malformed validation request has been received: " + "a 'token' parameter with an access, refresh, or identity token is required." }); return; } // When client_id and client_secret are both null, try to extract them from the Authorization header. // See http://tools.ietf.org/html/rfc6749#section-2.3.1 and // http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication if (string.IsNullOrEmpty(request.ClientId) && string.IsNullOrEmpty(request.ClientSecret)) { string header = Request.Headers[HeaderNames.Authorization]; if (!string.IsNullOrEmpty(header) && header.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase)) { try { var value = header.Substring("Basic ".Length).Trim(); var data = Encoding.UTF8.GetString(Convert.FromBase64String(value)); var index = data.IndexOf(':'); if (index >= 0) { request.ClientId = data.Substring(0, index); request.ClientSecret = data.Substring(index + 1); } } catch (FormatException) { } catch (ArgumentException) { } } } var clientNotification = new ValidateClientAuthenticationContext(Context, Options, request); await Options.Provider.ValidateClientAuthentication(clientNotification); // Reject the request if client authentication was rejected. if (clientNotification.IsRejected) { Logger.LogError("The validation request was rejected " + "because client authentication was invalid."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } // Ensure that the client_id has been set from the ValidateClientAuthentication event. else if (clientNotification.IsValidated && string.IsNullOrEmpty(request.ClientId)) { Logger.LogError("Client authentication was validated but the client_id was not set."); await SendErrorPayloadAsync(new OpenIdConnectMessage { Error = OpenIdConnectConstants.Errors.ServerError, ErrorDescription = "An internal server error occurred." }); return; } AuthenticationTicket ticket = null; // Note: use the "token_type_hint" parameter to determine // the type of the token sent by the client application. // See https://tools.ietf.org/html/rfc7662#section-2.1 switch (request.GetTokenTypeHint()) { case OpenIdConnectConstants.Usages.AccessToken: ticket = await DeserializeAccessTokenAsync(request.GetToken(), request); break; case OpenIdConnectConstants.Usages.RefreshToken: ticket = await DeserializeRefreshTokenAsync(request.GetToken(), request); break; case OpenIdConnectConstants.Usages.IdToken: ticket = await DeserializeIdentityTokenAsync(request.GetToken(), request); break; } // Note: if the token can't be found using "token_type_hint", // the search must be extended to all supported token types. // See https://tools.ietf.org/html/rfc7662#section-2.1 if (ticket == null) { ticket = await DeserializeAccessTokenAsync(request.GetToken(), request) ?? await DeserializeIdentityTokenAsync(request.GetToken(), request) ?? await DeserializeRefreshTokenAsync(request.GetToken(), request); } if (ticket == null) { Logger.LogInformation("The validation request was rejected because the token was invalid."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } // Note: unlike refresh or identity tokens that can only be validated by client applications, // access tokens can be validated by either resource servers or client applications: // in both cases, the caller must be authenticated if the ticket is marked as confidential. if (clientNotification.IsSkipped && ticket.IsConfidential()) { Logger.LogWarning("The validation request was rejected " + "because the caller was not authenticated."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } // If the ticket is already expired, directly return active=false. if (ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc < Options.SystemClock.UtcNow) { Logger.LogDebug("expired token"); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } switch (ticket.GetUsage()) { case OpenIdConnectConstants.Usages.AccessToken: { // When the caller is authenticated, ensure it is // listed as a valid audience or authorized presenter. if (clientNotification.IsValidated && !ticket.HasAudience(clientNotification.ClientId) && !ticket.HasPresenter(clientNotification.ClientId)) { Logger.LogWarning("The validation request was rejected because the access token " + "was issued to a different client or for another resource server."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } break; } case OpenIdConnectConstants.Usages.IdToken: { // When the caller is authenticated, reject the validation // request if the caller is not listed as a valid audience. if (clientNotification.IsValidated && !ticket.HasAudience(clientNotification.ClientId)) { Logger.LogWarning("The validation request was rejected because the " + "identity token was issued to a different client."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } break; } case OpenIdConnectConstants.Usages.RefreshToken: { // When the caller is authenticated, reject the validation request if the caller // doesn't correspond to the client application the token was issued to. if (clientNotification.IsValidated && !ticket.HasPresenter(clientNotification.ClientId)) { Logger.LogWarning("The validation request was rejected because the " + "refresh token was issued to a different client."); await SendPayloadAsync(new JObject { [OpenIdConnectConstants.Claims.Active] = false }); return; } break; } } // Insert the validation request in the ASP.NET context. Context.SetOpenIdConnectRequest(request); var notification = new ValidationEndpointContext(Context, Options, request, ticket); notification.Active = true; // Note: "token_type" may be null when the received token is not an access token. // See https://tools.ietf.org/html/rfc7662#section-2.2 and https://tools.ietf.org/html/rfc6749#section-5.1 notification.TokenType = ticket.Principal.GetClaim(OpenIdConnectConstants.Claims.TokenType); notification.Issuer = Context.GetIssuer(Options); notification.Subject = ticket.Principal.GetClaim(ClaimTypes.NameIdentifier); notification.IssuedAt = ticket.Properties.IssuedUtc; notification.ExpiresAt = ticket.Properties.ExpiresUtc; // Copy the audiences extracted from the "aud" claim. foreach (var audience in ticket.GetAudiences()) { notification.Audiences.Add(audience); } // Note: non-metadata claims are only added if the caller is authenticated AND is in the specified audiences. if (clientNotification.IsValidated && notification.Audiences.Contains(clientNotification.ClientId)) { // Extract the main identity associated with the principal. var identity = (ClaimsIdentity)ticket.Principal.Identity; notification.Username = identity.Name; notification.Scope = ticket.GetProperty(OpenIdConnectConstants.Properties.Scopes); // Potentially sensitive claims are only exposed to trusted callers // if the ticket corresponds to an access or identity token. if (ticket.IsAccessToken() || ticket.IsIdentityToken()) { foreach (var claim in ticket.Principal.Claims) { // Exclude standard claims, that are already handled via strongly-typed properties. // Make sure to always update this list when adding new built-in claim properties. if (string.Equals(claim.Type, identity.NameClaimType, StringComparison.Ordinal) || string.Equals(claim.Type, ClaimTypes.NameIdentifier, StringComparison.Ordinal)) { continue; } if (string.Equals(claim.Type, JwtRegisteredClaimNames.Aud, StringComparison.Ordinal) || string.Equals(claim.Type, JwtRegisteredClaimNames.Exp, StringComparison.Ordinal) || string.Equals(claim.Type, JwtRegisteredClaimNames.Iat, StringComparison.Ordinal) || string.Equals(claim.Type, JwtRegisteredClaimNames.Iss, StringComparison.Ordinal) || string.Equals(claim.Type, JwtRegisteredClaimNames.Nbf, StringComparison.Ordinal) || string.Equals(claim.Type, JwtRegisteredClaimNames.Sub, StringComparison.Ordinal)) { continue; } if (string.Equals(claim.Type, OpenIdConnectConstants.Claims.TokenType, StringComparison.Ordinal) || string.Equals(claim.Type, OpenIdConnectConstants.Claims.Scope, StringComparison.Ordinal)) { continue; } string type; // Try to resolve the short name associated with the claim type: // if none can be found, the claim type is used as-is. if (!JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.TryGetValue(claim.Type, out type)) { type = claim.Type; } // Note: make sure to use the indexer // syntax to avoid duplicate properties. notification.Claims[type] = claim.Value; } } } await Options.Provider.ValidationEndpoint(notification); // Flow the changes made to the authentication ticket. ticket = notification.AuthenticationTicket; if (notification.HandledResponse) { return; } var payload = new JObject(); payload.Add(OpenIdConnectConstants.Claims.Active, notification.Active); // Only add the other properties if // the token is considered as active. if (notification.Active) { if (!string.IsNullOrEmpty(notification.Issuer)) { payload.Add(JwtRegisteredClaimNames.Iss, notification.Issuer); } if (!string.IsNullOrEmpty(notification.Username)) { payload.Add(OpenIdConnectConstants.Claims.Username, notification.Username); } if (!string.IsNullOrEmpty(notification.Subject)) { payload.Add(JwtRegisteredClaimNames.Sub, notification.Subject); } if (!string.IsNullOrEmpty(notification.Scope)) { payload.Add(OpenIdConnectConstants.Claims.Scope, notification.Scope); } if (notification.IssuedAt.HasValue) { payload.Add(JwtRegisteredClaimNames.Iat, EpochTime.GetIntDate(notification.IssuedAt.Value.UtcDateTime)); payload.Add(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(notification.IssuedAt.Value.UtcDateTime)); } if (notification.ExpiresAt.HasValue) { payload.Add(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(notification.ExpiresAt.Value.UtcDateTime)); } if (!string.IsNullOrEmpty(notification.TokenType)) { payload.Add(OpenIdConnectConstants.Claims.TokenType, notification.TokenType); } switch (notification.Audiences.Count) { case 0: break; case 1: payload.Add(JwtRegisteredClaimNames.Aud, notification.Audiences[0]); break; default: payload.Add(JwtRegisteredClaimNames.Aud, JArray.FromObject(notification.Audiences)); break; } foreach (var claim in notification.Claims) { // Ignore claims whose value is null. if (claim.Value == null) { continue; } // Note: make sure to use the indexer // syntax to avoid duplicate properties. payload[claim.Key] = claim.Value; } } var context = new ValidationEndpointResponseContext(Context, Options, payload); await Options.Provider.ValidationEndpointResponse(context); if (context.HandledResponse) { return; } using (var buffer = new MemoryStream()) using (var writer = new JsonTextWriter(new StreamWriter(buffer))) { payload.WriteTo(writer); writer.Flush(); Response.ContentLength = buffer.Length; Response.ContentType = "application/json;charset=UTF-8"; Response.Headers[HeaderNames.CacheControl] = "no-cache"; Response.Headers[HeaderNames.Pragma] = "no-cache"; Response.Headers[HeaderNames.Expires] = "-1"; buffer.Seek(offset: 0, loc: SeekOrigin.Begin); await buffer.CopyToAsync(Response.Body, 4096, Context.RequestAborted); } }
public async Task <IActionResult> Post([FromBody] TenantDef tenant) { if ((User == null) || (!User.IsInRole("ief"))) { return(new UnauthorizedObjectResult("Unauthorized")); } if ((string.IsNullOrEmpty(tenant.name) || (string.IsNullOrEmpty(tenant.ownerId)))) { return(BadRequest("Invalid parameters")); } var http = await _graph.GetClientAsync(); try { await http.GetStringAsync($"{Graph.BaseUrl}users/{tenant.ownerId}"); } catch (HttpRequestException ex) { return(BadRequest("Unable to validate user id")); } if ((tenant.name.Length > 60) || !Regex.IsMatch(tenant.name, "^[A-Za-z]\\w*$")) { return(BadRequest("Invalid tenant name")); } var resp = await http.GetAsync($"{Graph.BaseUrl}groups?$filter=(displayName eq '{tenant.name}')"); if (!resp.IsSuccessStatusCode) { return(BadRequest("Unable to validate tenant existence")); } var values = JObject.Parse(await resp.Content.ReadAsStringAsync())["value"].Value <JArray>(); if (values.Count != 0) { return(new ConflictObjectResult(new { userMessage = "Tenant already exists", status = 409, version = 1.0 })); } var group = new { description = tenant.description, mailNickname = tenant.name, displayName = tenant.name.ToUpper(), groupTypes = new string[] { }, mailEnabled = false, securityEnabled = true, }; var jGroup = JObject.FromObject(group); var owners = new string[] { $"{Graph.BaseUrl}users/{tenant.ownerId}" }; jGroup.Add("*****@*****.**", JArray.FromObject(owners)); //jGroup.Add("*****@*****.**", JArray.FromObject(owners)); // https://docs.microsoft.com/en-us/graph/api/group-post-groups?view=graph-rest-1.0&tabs=http resp = await http.PostAsync( $"{Graph.BaseUrl}groups", new StringContent(jGroup.ToString(), System.Text.Encoding.UTF8, "application/json")); if (!resp.IsSuccessStatusCode) { return(BadRequest("Tenant creation failed")); } var json = await resp.Content.ReadAsStringAsync(); var newGroup = JObject.Parse(json); var id = newGroup["id"].Value <string>(); // add this group to the user's tenant collection return(new OkObjectResult(new { id, roles = new string[] { "admin", "member" }, userMessage = "Tenant created" })); }
public static CdmManifestDefinition FromObject(CdmCorpusContext ctx, string name, string nameSpace, string path, ManifestContent dataObj) { // Determine name of the manifest var manifestName = !string.IsNullOrEmpty(dataObj.ManifestName) ? dataObj.ManifestName : dataObj.FolioName; // We haven't found the name in the file, use one provided in the call but without the suffixes if (string.IsNullOrEmpty(manifestName)) { manifestName = name.Replace(PersistenceLayer.ManifestExtension, "").Replace(PersistenceLayer.FolioExtension, ""); } var manifest = ctx.Corpus.MakeObject <CdmManifestDefinition>(CdmObjectType.ManifestDef, manifestName); manifest.Name = name; // this is the document name which is assumed by constructor to be related to the the manifestName, but may not be manifest.FolderPath = path; manifest.Namespace = nameSpace; manifest.Explanation = dataObj.Explanation; if (!string.IsNullOrEmpty(dataObj.Schema)) { manifest.Schema = dataObj.Schema; } if (DynamicObjectExtensions.HasProperty(dataObj, "JsonSchemaSemanticVersion") && !string.IsNullOrEmpty(dataObj.JsonSchemaSemanticVersion)) { manifest.JsonSchemaSemanticVersion = dataObj.JsonSchemaSemanticVersion; } if (!string.IsNullOrEmpty(dataObj.ManifestName)) { manifest.ManifestName = dataObj.ManifestName; } // Might be populated in the case of folio.cdm.json or manifest.cdm.json file. else if (!string.IsNullOrEmpty(dataObj.FolioName)) { manifest.ManifestName = dataObj.FolioName; } if (dataObj.ExhibitsTraits != null) { Utils.AddListToCdmCollection(manifest.ExhibitsTraits, Utils.CreateTraitReferenceList(ctx, JArray.FromObject(dataObj.ExhibitsTraits))); } if (dataObj.Imports != null) { foreach (var importObj in dataObj.Imports) { manifest.Imports.Add(ImportPersistence.FromData(ctx, importObj)); } } if (dataObj.Definitions != null) { for (int i = 0; i < dataObj.Definitions.Count; i++) { dynamic d = dataObj.Definitions[i]; if (d["dataTypeName"] != null) { manifest.Definitions.Add(DataTypePersistence.FromData(ctx, d)); } else if (d["purposeName"] != null) { manifest.Definitions.Add(PurposePersistence.FromData(ctx, d)); } else if (d["attributeGroupName"] != null) { manifest.Definitions.Add(AttributeGroupPersistence.FromData(ctx, d)); } else if (d["traitName"] != null) { manifest.Definitions.Add(TraitPersistence.FromData(ctx, d)); } else if (d["entityShape"] != null) { manifest.Definitions.Add(ConstantEntityPersistence.FromData(ctx, d)); } else if (d["entityName"] != null) { manifest.Definitions.Add(EntityPersistence.FromData(ctx, d)); } } } if (dataObj.LastFileStatusCheckTime != null) { manifest.LastFileStatusCheckTime = DateTimeOffset.Parse(dataObj.LastFileStatusCheckTime); } if (dataObj.LastFileModifiedTime != null) { manifest.LastFileModifiedTime = DateTimeOffset.Parse(dataObj.LastFileModifiedTime); } if (dataObj.LastChildFileModifiedTime != null) { manifest.LastChildFileModifiedTime = DateTimeOffset.Parse(dataObj.LastChildFileModifiedTime); } if (dataObj.Entities != null) { var fullPath = !string.IsNullOrEmpty(nameSpace) ? $"{nameSpace}:{path}" : path; foreach (var entityObj in dataObj.Entities) { CdmEntityDeclarationDefinition entity = null; if (entityObj["type"] != null) { if (entityObj["type"].ToString() == EntityDeclarationDefinitionType.LocalEntity) { entity = LocalEntityDeclarationPersistence.FromData(ctx, fullPath, entityObj); } else if (entityObj["type"].ToString() == EntityDeclarationDefinitionType.ReferencedEntity) { entity = ReferencedEntityDeclarationPersistence.FromData(ctx, fullPath, entityObj); } else { Logger.Error(nameof(ManifestPersistence), ctx, "Couldn't find the type for entity declaration", nameof(FromObject)); } } else { // We see old structure of entity declaration, check for entity schema/declaration. if (entityObj["entitySchema"] != null) { // Local entity declaration used to use entity schema. entity = LocalEntityDeclarationPersistence.FromData(ctx, fullPath, entityObj); } else { // While referenced entity declaration used to use entity declaration. entity = ReferencedEntityDeclarationPersistence.FromData(ctx, fullPath, entityObj); } } manifest.Entities.Add(entity); } } if (dataObj.Relationships != null) { foreach (var rel in dataObj.Relationships) { manifest.Relationships.Add(E2ERelationshipPersistence.FromData(ctx, rel)); } } if (dataObj.SubManifests != null) { foreach (var subManifest in dataObj.SubManifests) { manifest.SubManifests.Add(ManifestDeclarationPersistence.FromData(ctx, subManifest)); } } // Might be populated in the case of folio.cdm.json or manifest.cdm.json file. else if (dataObj.SubFolios != null) { foreach (var subFolio in dataObj.SubFolios) { manifest.SubManifests.Add(ManifestDeclarationPersistence.FromData(ctx, subFolio)); } } return(manifest); }
protected string GetLogMessage(IEnumerable <T> infos, [CallerMemberName] string caller = "") { return(caller + " --> " + JArray.FromObject(infos).ToString(Formatting.None)); }
public static API.GetUserViewModel ToGetUserViewModel(this Models.User source) { return(new API.GetUserViewModel() { SubjectId = source.SubjectId, Email = source.Email, AdditionalProperties = source.Claims?.GroupBy(x => x.Type).ToDictionary( x => x.Key, x => x.Count() == 1 ? (JToken) new JValue(x.FirstOrDefault()?.Value) : (JToken)JArray.FromObject(x.Select(y => y.Value)) ) }); }
private static JToken ExtractEntityValue(EntityModel entity) { #pragma warning disable IDE0007 // Use implicit type if (entity.AdditionalProperties == null || !entity.AdditionalProperties.TryGetValue("resolution", out dynamic resolution)) #pragma warning restore IDE0007 // Use implicit type { return(entity.Entity); } if (entity.Type.StartsWith("builtin.datetimeV2.")) { if (resolution.values == null || resolution.values.Count == 0) { return(JArray.FromObject(resolution)); } var resolutionValues = (IEnumerable <dynamic>)resolution.values; var type = resolution.values[0].type; var timexes = resolutionValues.Select(val => val.timex); var distinctTimexes = timexes.Distinct(); return(new JObject(new JProperty("type", type), new JProperty("timex", JArray.FromObject(distinctTimexes)))); } else { switch (entity.Type) { case "builtin.number": case "builtin.ordinal": return(Number(resolution.value)); case "builtin.percentage": { var svalue = (string)resolution.value; if (svalue.EndsWith("%")) { svalue = svalue.Substring(0, svalue.Length - 1); } return(Number(svalue)); } case "builtin.age": case "builtin.dimension": case "builtin.currency": case "builtin.temperature": { var units = (string)resolution.unit; var val = Number(resolution.value); var obj = new JObject(); if (val != null) { obj.Add("number", val); } obj.Add("units", units); return(obj); } default: return(resolution.value ?? JArray.FromObject(resolution.values)); } } }