public static JObject CSharpTest(RPCRequestInfo c, JObject p) { Thread.Sleep ((int)p ["ms"].AsNumber (0.0)); return new JObject { { "hello", "world" } }; }
public void LoadFromJson(JObject source) { // This is where the automatic deserialization takes place. We just tell the Jobject that we want an object of the type RelfectionData and it will handle the rest var reflectionDataObject = source.Deserialize<ReflectionData>(); // This is just a simple method a created to read the data from reflectionDataObject back into this object reflectionDataObject.ToMonoBehavior(this); }
public RPCException(string code, string msg, RPCException orig, JObject data = null) { ErrorCode = code; ErrorMessage = msg + ": " + orig.ErrorMessage; ErrorData = data ?? new JObject (); ErrorData ["orig"] = orig.AsHeader (); }
public RPCException(string code, string msg, JObject data = null) : base(msg) { ErrorCode = code; ErrorMessage = msg; ErrorData = data; }
private static JObject CreateResponse(JObject id) { JObject response = new JObject(); response["jsonrpc"] = "2.0"; response["id"] = id; return response; }
public Download(Uri uri, string key, CookieContainer cc, JObject song) { m_uri = uri; m_key = key; m_cc = cc; m_song = song; song["Status"] = "Opening file"; string filename = (string)song["ArtistName"] + " - " + (string)song["Name"] + ".mp3"; m_logger = new Logger(this.GetType().ToString() + " " + filename); string dst = ""; string path = ""; if (Main.PATH.Length != 0) path = Main.PATH + Path.DirectorySeparatorChar; dst = path + filename; try { m_path = dst; m_fs = new FileStream(dst, FileMode.Create); } catch (Exception ex) { char[] invalf = Path.GetInvalidFileNameChars(); foreach (char c in invalf) filename = filename.Replace(c, '_'); dst = path + filename; try { m_path = dst; m_fs = new FileStream(dst, FileMode.Create); } catch (Exception exc) { for (int i = 0; i < dst.Length; i++) { if (!Char.IsLetterOrDigit(dst[i])) filename = filename.Replace(dst[i], '_'); dst = path + filename; } try { m_path = dst; m_fs = new FileStream(dst, FileMode.Create); } catch (Exception exc2) { throw new Exception("Could not save the file buddy. (" + exc2.Message + ")"); } } } m_logger.Info("Starting download"); song["Status"] = "Starting download"; Segment s = new Segment(uri, cc, key, 0, SEGMENT_SIZE-1, m_path); m_segments.Add(s); s.Progress += new EventHandler(s_Progress); s.HeadersReceived += new Segment.HeadersReceivedHandler(s_HeadersReceived); s.Start(); m_start = DateTime.Now; }
public void Example() { #region Usage JObject o = new JObject { { "Cpu", "Intel" }, { "Memory", 32 }, { "Drives", new JArray { "DVD", "SSD" } } }; Console.WriteLine(o.ToString()); // { // "Cpu": "Intel", // "Memory": 32, // "Drives": [ // "DVD", // "SSD" // ] // } #endregion }
public void Example() { #region Usage JObject o = new JObject { { "name1", "value1" }, { "name2", "value2" } }; JsonWriter writer = o.CreateWriter(); writer.WritePropertyName("name3"); writer.WriteStartArray(); writer.WriteValue(1); writer.WriteValue(2); writer.WriteEndArray(); Console.WriteLine(o.ToString()); // { // "name1": "value1", // "name2": "value2", // "name3": [ // 1, // 2 // ] // } #endregion }
public JObject ToJson() { JObject json = new JObject(); json["stack"] = StackScript.ToHexString(); json["redeem"] = RedeemScript.ToHexString(); return json; }
public ProccessDefination(JObject data) : base(data) { this.StartAlias = data["StartAlias"].ToString(); this.FinishAlias = data["FinishAlias"].ToString(); var rtIdData = data["RuntimeId"]; if (rtIdData != null) this.RuntimeId = new Guid(rtIdData.ToString()); }
public JObject ToJson() { JObject json = new JObject(); json["usage"] = Usage; json["data"] = Data.ToHexString(); return json; }
public void Example() { #region Usage JValue s1 = new JValue("A string"); JValue s2 = new JValue("A string"); JValue s3 = new JValue("A STRING"); Console.WriteLine(JToken.DeepEquals(s1, s2)); // true Console.WriteLine(JToken.DeepEquals(s2, s3)); // false JObject o1 = new JObject { { "Integer", 12345 }, { "String", "A string" }, { "Items", new JArray(1, 2) } }; JObject o2 = new JObject { { "Integer", 12345 }, { "String", "A string" }, { "Items", new JArray(1, 2) } }; Console.WriteLine(JToken.DeepEquals(o1, o2)); // true Console.WriteLine(JToken.DeepEquals(s1, o1["String"])); // true #endregion }
private IElasticCoreType GetTypeFromJObject(JObject po, JsonSerializer serializer) { JToken typeToken; serializer.TypeNameHandling = TypeNameHandling.None; if (po.TryGetValue("type", out typeToken)) { var type = typeToken.Value<string>().ToLowerInvariant(); switch (type) { case "string": return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping; case "float": case "double": case "byte": case "short": case "integer": case "long": return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping; case "date": return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping; case "boolean": return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping; case "binary": return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping; } } return null; }
public static ProcessDefination FromJson(JObject data) { var entity = new ProcessDefination(); entity.Id = new Guid(data["Id"].ToString()); entity.ActivityDefinationId = new Guid(data["ActivityDefinationId"].ToString()); entity.ActivityId = new Guid(data["ActivityId"].ToString()); entity.Description = data["Description"].ToString(); var arr = data["ActivedActivityIds"] as JArray; if (arr != null) { entity.ActivedActivityIds = new List<Guid>(); foreach (JToken item in arr) { entity.ActivedActivityIds.Add(new Guid(item.ToString())); } } var extra = data["Extra"] as JObject; if (extra != null) { entity.Extras = new Dictionary<string, string>(); foreach (var pair in extra) { entity.Extras.Add(pair.Key, pair.Value.ToString()); } } return entity; }
public TransactionDefination(JObject data) : base(data) { this.FromAlias = data["FromAlias"].ToString(); this.ToAlias = data["ToAlias"].ToString(); this.ConstraintKind = (ConstraintKinds)Enum.Parse(typeof(ConstraintKinds), data["ConstraintKind"].ToString()); if (this.ConstraintKind != ConstraintKinds.None) this.Constraint = data["Constraint"]?.ToString(); }
// change the json string to json object public void toJObject(string feed, JObject JO) { JsonSerializer serializer = new JsonSerializer(); using (JsonWriter writer = new JsonTextWriter(feed)) { serializer.Serialize(writer, JO); } }
public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.Equal(@"{ ""novalue"": null }", o.ToString()); }
public JObject ToJson(ushort index) { JObject json = new JObject(); json["n"] = index; json["asset"] = AssetId.ToString(); json["value"] = Value.ToDecimal(); json["address"] = Wallet.ToAddress(ScriptHash); return json; }
public TransactionInfo(JObject data) : base(data) { this.From = new Guid(data["From"].ToString()); this.To = new Guid(data["To"].ToString()); this.ConstraintKind = (ConstraintKinds)Enum.Parse(typeof(ConstraintKinds), data["ConstraintKind"].ToString()); if (this.ConstraintKind != ConstraintKinds.None) this.Constraint = data["Constraint"].ToString(); }
public void MoveTo(int x, int y, int z) { JObject jRoot = new JObject(); bool bRet = SavePosition(x, y, z); jRoot.Items.Add(KEY_RETURN, new JBoolean(bRet)); jr.RespondJSON(jRoot); }
public ParallelActivityInfo(JObject data) :base(data){ var parallels = data["ParallelActivities"] as JArray; if (parallels != null) { foreach (var idstr in parallels) { this._parallelActivities.Add(new Guid(idstr)); } } }
private IElasticType GetTypeFromJObject(JObject po, JsonSerializer serializer) { JToken typeToken; JToken propertiesToken; JToken fieldsToken; var type = string.Empty; var hasType = po.TryGetValue("type", out typeToken); if (hasType) type = typeToken.Value<string>().ToLowerInvariant(); else if (po.TryGetValue("properties", out propertiesToken)) type = "object"; var originalType = type; var hasFields = po.TryGetValue("fields", out fieldsToken); if (hasFields) type = "multi_field"; serializer.TypeNameHandling = TypeNameHandling.None; switch (type) { case "string": return serializer.Deserialize(po.CreateReader(), typeof(StringMapping)) as StringMapping; case "float": case "double": case "byte": case "short": case "integer": case "long": return serializer.Deserialize(po.CreateReader(), typeof(NumberMapping)) as NumberMapping; case "date": return serializer.Deserialize(po.CreateReader(), typeof(DateMapping)) as DateMapping; case "boolean": return serializer.Deserialize(po.CreateReader(), typeof(BooleanMapping)) as BooleanMapping; case "binary": return serializer.Deserialize(po.CreateReader(), typeof(BinaryMapping)) as BinaryMapping; case "object": return serializer.Deserialize(po.CreateReader(), typeof(ObjectMapping)) as ObjectMapping; case "nested": return serializer.Deserialize(po.CreateReader(), typeof(NestedObjectMapping)) as NestedObjectMapping; case "multi_field": var m =serializer.Deserialize(po.CreateReader(), typeof(MultiFieldMapping)) as MultiFieldMapping; m.Type = originalType; return m; case "ip": return serializer.Deserialize(po.CreateReader(), typeof(IPMapping)) as IPMapping; case "geo_point": return serializer.Deserialize(po.CreateReader(), typeof(GeoPointMapping)) as GeoPointMapping; case "geo_shape": return serializer.Deserialize(po.CreateReader(), typeof(GeoShapeMapping)) as GeoShapeMapping; case "attachment": return serializer.Deserialize(po.CreateReader(), typeof(AttachmentMapping)) as AttachmentMapping; } return null; }
public void Example() { #region Usage List<Post> posts = GetPosts(); JObject rss = new JObject( new JProperty("channel", new JObject( new JProperty("title", "James Newton-King"), new JProperty("link", "http://james.newtonking.com"), new JProperty("description", "James Newton-King's blog."), new JProperty("item", new JArray( from p in posts orderby p.Title select new JObject( new JProperty("title", p.Title), new JProperty("description", p.Description), new JProperty("link", p.Link), new JProperty("category", new JArray( from c in p.Categories select new JValue(c))))))))); Console.WriteLine(rss.ToString()); // { // "channel": { // "title": "James Newton-King", // "link": "http://james.newtonking.com", // "description": "James Newton-King's blog.", // "item": [ // { // "title": "Json.NET 1.3 + New license + Now on CodePlex", // "description": "Annoucing the release of Json.NET 1.3, the MIT license and being available on CodePlex", // "link": "http://james.newtonking.com/projects/json-net.aspx", // "category": [ // "Json.NET", // "CodePlex" // ] // }, // { // "title": "LINQ to JSON beta", // "description": "Annoucing LINQ to JSON", // "link": "http://james.newtonking.com/projects/json-net.aspx", // "category": [ // "Json.NET", // "LINQ" // ] // } // ] // } // } #endregion }
public void AndExpressionTest() { CompositeExpression compositeExpression = new CompositeExpression { Operator = QueryOperator.And, Expressions = new List<QueryExpression> { new BooleanQueryExpression { Operator = QueryOperator.Exists, Path = new List<PathFilter> { new FieldFilter { Name = "FirstName" } } }, new BooleanQueryExpression { Operator = QueryOperator.Exists, Path = new List<PathFilter> { new FieldFilter { Name = "LastName" } } } } }; JObject o1 = new JObject { {"Title","Title!"}, {"FirstName", "FirstName!"}, {"LastName", "LastName!"} }; Assert.True(compositeExpression.IsMatch(o1)); JObject o2 = new JObject { {"Title","Title!"}, {"FirstName", "FirstName!"} }; Assert.False(compositeExpression.IsMatch(o2)); JObject o3 = new JObject { {"Title","Title!"} }; Assert.False(compositeExpression.IsMatch(o3)); }
public static TransactionDefination FromJson(JObject data, TransactionDefination entity = null) { if (entity == null) entity = new TransactionDefination(); Defination.FromJson(data, entity); entity.Constraint = data["Constraint"].ToString(); entity.ConstraintKind = (ConstraintKinds)Enum.Parse(typeof(ConstraintKinds), data["ConstraintKind"].ToString()); entity.From = new Guid(data["From"].ToString()); entity.To = new Guid(data["To"].ToString()); return entity; }
public ProccessInfo(JObject data) : base(data) { this.BlockId = new Guid(data["BlockId"]); var actived = data["Activied"] as JArray; if (actived != null) { foreach (var idstr in actived) { this.Actived.Add(new Guid(idstr)); } } }
private static JObject CreateErrorResponse(JObject id, int code, string message, JObject data = null) { JObject response = CreateResponse(id); response["error"] = new JObject(); response["error"]["code"] = code; response["error"]["message"] = message; if (data != null) response["error"]["data"] = data; return response; }
public void JObjectDictionary() { Dictionary<JToken, int> dic = new Dictionary<JToken, int>(JToken.EqualityComparer); JObject v11 = new JObject() { { "Test", new JValue(1) }, { "Test1", new JValue(1) } }; JObject v12 = new JObject() { { "Test", new JValue(1) }, { "Test1", new JValue(1) } }; dic[v11] = 1; dic[v12] += 1; Assert.AreEqual(2, dic[v11]); }
public ActivityInfo(JObject data) :base(data){ this.Deal = data["Deal"]?.ToString(); this.StartMode = (ExecutionModes)Enum.Parse(typeof(ExecutionModes), data["StartMode"].ToString()); this.FinishMode = (ExecutionModes)Enum.Parse(typeof(ExecutionModes), data["FinishMode"].ToString()); this.StartConstraintKind = (ConstraintKinds)Enum.Parse(typeof(ConstraintKinds), data["StartConstraintKind"].ToString()); this.FinishConstraintKind = (ConstraintKinds)Enum.Parse(typeof(ConstraintKinds), data["FinishConstraintKind"].ToString()); if (this.StartConstraintKind != ConstraintKinds.None ) this.StartConstraint = data["StartConstraint"].ToString(); if (this.FinishConstraintKind != ConstraintKinds.None ) this.FinishConstraint = data["FinishConstraint"].ToString(); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Department department = (Department)value; JObject o = new JObject(); o["DepartmentId"] = new JValue(department.DepartmentId.ToString()); o["Name"] = new JValue(new string(department.Name.Reverse().ToArray())); o.WriteTo(writer); }
private int getStartHeight(string mongodbConnStr, string mongodbDatabase, int refundVal, string addr) { //地址下面所有未使用的兑换记录 JArray mints = getMintSNEOByAddr(mongodbConnStr, mongodbDatabase, addr); if (mints.Count == 0) { return(0); } //默认第一个就是开始高度 JObject firstOb = (JObject)mints[0]; int remainTotal = 0; Console.WriteLine("mintsneo size:" + mints.Count); //记录使用被匹配的兑换记录 List <NEP5.MintSNEOTemp> temps = new List <NEP5.MintSNEOTemp>(); foreach (JObject mint in mints) { int remainVal = (int)mint["remainVal"]; string txid = (string)mint["txid"]; int blockindex = (int)mint["blockindex"]; remainTotal = remainTotal + remainVal; int result = remainTotal - refundVal; if (result <= 0) { NEP5.MintSNEOTemp temp = new NEP5.MintSNEOTemp(addr, txid, 0); temps.Add(temp); } else { NEP5.MintSNEOTemp temp = new NEP5.MintSNEOTemp(addr, txid, result); temps.Add(temp); break; } } //更新MintSNEO记录 foreach (NEP5.MintSNEOTemp temp in temps) { string txid = temp.txid; int remainVal = temp.remainVal; Console.WriteLine("txid:" + txid + "/remainVal:" + remainVal); var client = new MongoClient(mongodbConnStr); var database = client.GetDatabase(mongodbDatabase); var coll = database.GetCollection <BsonDocument>("MintSNEO"); BsonDocument queryBson = BsonDocument.Parse("{from:'" + addr + "',txid:'" + txid + "'}"); var collBson = database.GetCollection <NEP55.MintSNEO>("MintSNEO"); List <NEP55.MintSNEO> query = collBson.Find(queryBson).ToList(); NEP55.MintSNEO oper = query[0]; oper.remainVal = remainVal; collBson.ReplaceOne(queryBson, oper); } return((int)firstOb["blockindex"]); }
public async Task <bool> Find(string deviceName) { // Find all the installed device types var response = await myConnection.GetAsync(myConnection.DeviceTypeList); if (response.StatusCode != HttpStatusCode.OK) { return(false); } var htmlResult = await response.Content.ReadAsStringAsync(); // From String var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(htmlResult); var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//a"); foreach (var node in htmlNodes) { if (node.Attributes["href"]?.Value.StartsWith("/ide/device/editor") == true) { if (node.InnerText.Trim().Contains(deviceName)) { Id = node.Attributes["href"].Value.Replace("/ide/device/editor/", ""); break; } } } if (Id == null) { return(false); } // Get the resource list for the smart app response = await myConnection.GetAsync($"{myConnection.DeviceTypeResourceListUri.ToString()}?id={Id}"); if (response.StatusCode != HttpStatusCode.OK) { return(false); } var jsonResult = response.Content.ReadAsStringAsync(); var jobject = JObject.Parse("{ root: " + jsonResult.Result + " }"); ResourceId = null; ResourceType = null; foreach (var jo in jobject.SelectToken("root").Children()) { if (jo["type"].ToString() == "file") { ResourceId = (string)jo["id"]; ResourceType = (string)jo["li_attr"]["resource-type"]; break; } } if (ResourceId == null) { return(false); } // Get the code for this app List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >(); parms.Add(new KeyValuePair <string, string>("id", Id)); parms.Add(new KeyValuePair <string, string>("resourceId", ResourceId)); parms.Add(new KeyValuePair <string, string>("resourceType", ResourceType)); var content = new System.Net.Http.FormUrlEncodedContent(parms); response = await myConnection.PostAsync(myConnection.DeviceTypeCodeForResourceUri, content); if (response.StatusCode != HttpStatusCode.OK) { return(false); } // Here is the code! Code = await response.Content.ReadAsStringAsync(); // Success return(true); }
/// <summary> /// Create an instance of object, based on properties in the JSON object. /// </summary> /// <param name="objectType">The type of object expected.</param> /// <param name="jObject">The contents of JSON object that will be deserialized.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> protected abstract T Create(Type objectType, JObject jObject, JsonSerializer serializer);
public void Load() { JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.AreEqual(true, (bool)o["pie"]); }
public abstract Task <JObject> Process(JObject connectEvent, ILambdaContext context);
public Totales getTotales(JObject lista) { bool cuitValido = Convert.ToBoolean(lista["valido"]), convenio = Convert.ToBoolean(lista["convenio"]), enDomicilio = Convert.ToBoolean(lista["enDomicilio"].ToString()), esExento = Convert.ToBoolean(lista["esExento"]); int empresaid = Convert.ToInt32(lista["empresaid"]); string provincia = lista["provincia"].ToString(), cuit = lista["cuit"].ToString(), codpro, monfac = lista["monfac"].ToString(); prueba2 p = new prueba2(); var lis = lista["lista"].ToArray(); List<stocks> listaItems; stocks item, aux; Totales totales = new Totales(); decimal bonicli = Convert.ToDecimal(lista["bonifcli"].ToString()); if (lis.Count() > 0) { for (int i = 0; i < lis.Count(); i++) { if (lis[i]["asociado"].ToString().Contains("[")) lis[i]["asociado"] = ""; item = JsonConvert.DeserializeObject<stocks>(lis[i].ToString()); if (item.codpro == "") codpro = lis[i]["articulo"].ToString(); else codpro = item.codpro; aux = new stocks(item.cantidad, item.precioVenta, item.bonif, item.bonif1, item.impint, codpro, item.asociado, bonicli, item.parafecha, item.detalle, empresaid); p.lista.Add(aux); } listaItems = p.lista; totales.subtotal = this.getSubTotal(listaItems); totales.bonif = this.getBonifTotal(listaItems, bonicli); totales.neto = this.getNeto(listaItems, bonicli); totales.exento = this.getExento(listaItems); totales.impint = this.getImpInt(listaItems); totales.ivagral = this.getIvaGral(listaItems, bonicli); totales.ivadif = this.getIvaIDif(listaItems, bonicli); totales.percep = this.getPercep(listaItems, bonicli, empresaid, cuit, provincia, totales.neto, convenio, esExento, enDomicilio, cuitValido, monfac); totales.total = this.getTotal(listaItems); totales.total = totales.total + totales.percep; return totales;// totales; } else { totales.subtotal = 0; totales.bonif = 0; totales.neto = 0; totales.exento = 0; totales.impint = 0; totales.ivagral = 0; totales.ivadif = 0; totales.percep = 0; totales.total = 0; return totales; } }
private async Task <HttpResponseMessage> ExecuteOnOneInstanceAsync(Func <HttpRequestMessage> createRequest) { // There may be many base urls - roll until one is found that works. // // Start with the last client that was used by this method, which only gets set on // success, so it's probably going to work. // // Otherwise, try every client until a successful call is made (true even under // concurrent access). string aggregatedErrorMessage = null; HttpResponseMessage response = null; bool firstError = true; int startClientIndex; lock (lastClientUsedLock) { startClientIndex = this.lastClientUsed; } int loopIndex = startClientIndex; int clientIndex = -1; // prevent uninitialized variable compiler error. bool finished = false; for (; loopIndex < clients.Count + startClientIndex && !finished; ++loopIndex) { clientIndex = loopIndex % clients.Count; try { response = await clients[clientIndex] .SendAsync(createRequest()) .ConfigureAwait(continueOnCapturedContext: false); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent) { lock (lastClientUsedLock) { this.lastClientUsed = clientIndex; } return(response); } string message = ""; int errorCode = -1; // 4xx errors with valid SR error message as content should not be retried (these are conclusive). if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 500) { try { JObject errorObject = null; errorObject = JObject.Parse( await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false)); message = errorObject.Value <string>("message"); errorCode = errorObject.Value <int>("error_code"); } catch (Exception) { // consider an unauthorized response from any server to be conclusive. if (response.StatusCode == HttpStatusCode.Unauthorized) { finished = true; throw new HttpRequestException($"Unauthorized"); } } throw new SchemaRegistryException(message, response.StatusCode, errorCode); } if (!firstError) { aggregatedErrorMessage += "; "; } firstError = false; try { var errorObject = JObject.Parse( await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false)); message = errorObject.Value <string>("message"); errorCode = errorObject.Value <int>("error_code"); } catch { aggregatedErrorMessage += $"[{clients[clientIndex].BaseAddress}] {response.StatusCode}"; } aggregatedErrorMessage += $"[{clients[clientIndex].BaseAddress}] {response.StatusCode} {errorCode} {message}"; } catch (HttpRequestException e) { // don't retry error responses originating from Schema Registry. if (e is SchemaRegistryException) { throw; } if (!firstError) { aggregatedErrorMessage += "; "; } firstError = false; aggregatedErrorMessage += $"[{clients[clientIndex].BaseAddress}] HttpRequestException: {e.Message}"; } } throw new HttpRequestException(aggregatedErrorMessage); }
public async Task <IActionResult> ImportUsersAsync(string accountId, string projectId, [FromBody] JObject data) { Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead, Scope.AccountWrite }); if (!await IsAccountAdmin(accountId, bearer.access_token, credentials)) { return(null); } string roleId = data["roleId"].Value <string>(); JArray users = data["userIds"].Value <JArray>(); dynamic usersToAdd = new JArray(); foreach (dynamic user in users) { dynamic userToAdd = new JObject(); userToAdd.user_id = user; userToAdd.industry_roles = new JArray(); userToAdd.industry_roles.Add(roleId); userToAdd.services = new JObject(); userToAdd.services.project_administration = new JObject(); userToAdd.services.project_administration.access_level = "admin"; userToAdd.services.document_management = new JObject(); userToAdd.services.document_management.access_level = "admin"; usersToAdd.Add(userToAdd); } RestClient client = new RestClient(BASE_URL); RestRequest importUserRequest = new RestRequest("/hq/v2/accounts/{account_id}/projects/{project_id}/users/import", RestSharp.Method.POST); importUserRequest.AddParameter("account_id", accountId.Replace("b.", string.Empty), ParameterType.UrlSegment); importUserRequest.AddParameter("project_id", projectId.Replace("b.", string.Empty), ParameterType.UrlSegment); importUserRequest.AddParameter("application/json", Newtonsoft.Json.JsonConvert.SerializeObject(usersToAdd), ParameterType.RequestBody); importUserRequest.AddHeader("Authorization", "Bearer " + credentials.TokenInternal); IRestResponse importUserResponse = await client.ExecuteTaskAsync(importUserRequest); return(Ok()); }
public async Task <ActionResult> DoLogin(FormCollection form) { string email = form[Keywords.EMAIL]; string password = form[Keywords.PASSWORD]; HttpResponseMessage response = await _loginService.CheckLogin(email, password); if (response == null) { TempData[Keywords.ERROR] = Messages.SERVER_ERROR; return(RedirectToAction(Keywords.INDEX)); } if (response.StatusCode == HttpStatusCode.Unauthorized) { TempData[Keywords.ERROR] = Messages.INVALID_ACCOUNT_ERROR; return(RedirectToAction(Keywords.INDEX)); } string token = response.Headers.TryGetValues(Keywords.TOKEN_KEY, out var values) ? values.FirstOrDefault() : null; string content = await response.Content.ReadAsStringAsync(); JObject jObject = JObject.Parse(content); JObject dataJSON = (JObject)jObject.GetValue(Keywords.DATA); string name = dataJSON.GetValue(Keywords.NAME).ToString(); bool isAdmin = !dataJSON.ContainsKey(Keywords.PERMISSION); User user = null; if (isAdmin) { user = new User(email, name, token, isAdmin); SetUserInfoToCooke(user); return(RedirectToAction(Keywords.INDEX, Keywords.DASHBOARD)); } if ((int)dataJSON.GetValue(Keywords.STATUS) == Configs.DEACTIVE_STATUS) { // User had been blocked TempData[Keywords.ERROR] = Messages.DEACTIVE_USER; return(RedirectToAction(Keywords.INDEX)); } // Set User Info string id = jObject.GetValue(Keywords.ID).ToString(); string idGroup = dataJSON.GetValue(Keywords.ID_GROUP).ToString(); string gender = dataJSON.GetValue(Keywords.GENDER).ToString(); string phoneNumber = string.Empty; if (dataJSON.ContainsKey(Keywords.PHONE)) { phoneNumber = dataJSON.GetValue(Keywords.PHONE).ToString(); } string address = string.Empty; if (dataJSON.ContainsKey(Keywords.ADDRESS)) { address = dataJSON.GetValue(Keywords.ADDRESS).ToString(); } user = new User(email, name, token, idGroup, gender, phoneNumber, address, id, isAdmin); SetUserInfoToCooke(user); return(RedirectToAction(Keywords.INDEX, Keywords.REPORT, new { page = 1 })); }
/// <summary> /// Try to parse the given JSON representation of an energy mix. /// </summary> /// <param name="JSON">The JSON to parse.</param> /// <param name="EnergyMix">The parsed connector.</param> /// <param name="ErrorResponse">An optional error response.</param> /// <param name="CustomEnergyMixParser">A delegate to parse custom energy mix JSON objects.</param> public static Boolean TryParse(JObject JSON, out EnergyMix EnergyMix, out String ErrorResponse, CustomJObjectParserDelegate <EnergyMix> CustomEnergyMixParser) { try { EnergyMix = default; if (JSON?.HasValues != true) { ErrorResponse = "The given JSON object must not be null or empty!"; return(false); } #region Parse IsGreenEnergy [mandatory] if (!JSON.ParseMandatory("is_green_energy", "is green energy", out Boolean IsGreenEnergy, out ErrorResponse)) { return(false); } #endregion #region Parse EnergySources [optional] if (JSON.ParseOptionalJSON("energy_sources", "energy sources", EnergySource.TryParse, out IEnumerable <EnergySource> EnergySources, out ErrorResponse)) { if (ErrorResponse != null) { return(false); } } #endregion #region Parse EnvironmentalImpacts [optional] if (JSON.ParseOptionalJSON("environ_impact", "environmental impacts", EnvironmentalImpact.TryParse, out IEnumerable <EnvironmentalImpact> EnvironmentalImpacts, out ErrorResponse)) { if (ErrorResponse != null) { return(false); } } #endregion #region Parse SupplierName [optional] var SupplierName = JSON.GetString("supplier_name"); #endregion #region Parse EnergyProductName [optional] var EnergyProductName = JSON.GetString("energy_product_name"); #endregion EnergyMix = new EnergyMix(IsGreenEnergy, EnergySources, EnvironmentalImpacts, SupplierName, EnergyProductName); if (CustomEnergyMixParser != null) { EnergyMix = CustomEnergyMixParser(JSON, EnergyMix); } return(true); } catch (Exception e) { EnergyMix = default; ErrorResponse = "The given JSON representation of an energy mix is invalid: " + e.Message; return(false); } }
private string GetTestHostPath(string runtimeConfigDevPath, string depsFilePath, string sourceDirectory) { string testHostPackageName = "microsoft.testplatform.testhost"; string testHostPath = string.Empty; if (this.fileHelper.Exists(runtimeConfigDevPath) && this.fileHelper.Exists(depsFilePath)) { EqtTrace.Verbose("DotnetTestHostmanager: Reading file {0} to get path of testhost.dll", depsFilePath); // Get testhost relative path using (var stream = this.fileHelper.GetStream(depsFilePath, FileMode.Open)) { var context = new DependencyContextJsonReader().Read(stream); var testhostPackage = context.RuntimeLibraries.Where(lib => lib.Name.Equals(testHostPackageName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); if (testhostPackage != null) { foreach (var runtimeAssemblyGroup in testhostPackage.RuntimeAssemblyGroups) { foreach (var path in runtimeAssemblyGroup.AssetPaths) { if (path.EndsWith("testhost.dll", StringComparison.CurrentCultureIgnoreCase)) { testHostPath = path; break; } } } testHostPath = Path.Combine(testhostPackage.Path, testHostPath); EqtTrace.Verbose("DotnetTestHostmanager: Relative path of testhost.dll with respect to package folder is {0}", testHostPath); } } // Get probing path using (StreamReader file = new StreamReader(this.fileHelper.GetStream(runtimeConfigDevPath, FileMode.Open))) using (JsonTextReader reader = new JsonTextReader(file)) { JObject context = (JObject)JToken.ReadFrom(reader); JObject runtimeOptions = (JObject)context.GetValue("runtimeOptions"); JToken additionalProbingPaths = runtimeOptions.GetValue("additionalProbingPaths"); foreach (var x in additionalProbingPaths) { EqtTrace.Verbose("DotnetTestHostmanager: Looking for path {0} in folder {1}", testHostPath, x.ToString()); string testHostFullPath = Path.Combine(x.ToString(), testHostPath); if (this.fileHelper.Exists(testHostFullPath)) { return(testHostFullPath); } } } } if (string.IsNullOrEmpty(testHostPath)) { // Try resolving testhost from output directory of test project. This is required if user has published the test project // and is running tests in an isolated machine. A second scenario is self test: test platform unit tests take a project // dependency on testhost (instead of nuget dependency), this drops testhost to output path. testHostPath = Path.Combine(sourceDirectory, "testhost.dll"); EqtTrace.Verbose("DotnetTestHostManager: Assume published test project, with test host path = {0}.", testHostPath); } return(testHostPath); }
public JObject ToJObject() { JObject jobject = JObject.FromObject(this); return jobject; }
public static void ConvertUUIDs(JObject bundle) { ConvertUUIDs(bundle, CreateUUIDLookUpTable(bundle)); }
public JObject BuildQuerySettings(string collection) { var indexConfig = OpenContentUtils.GetIndexConfig(_templateUri, collection); var jsonEdit = Build(collection, DnnLanguageUtils.GetCurrentCultureCode(), true, true, false, false); SchemaConfig newSchema = new SchemaConfig(true); // max results newSchema.Properties.Add("MaxResults", new SchemaConfig() { Title = "MaxResults", Type = "number" }); // Default no results newSchema.Properties.Add("DefaultNoResults", new SchemaConfig() { Title = "Default No Results", Type = "boolean" }); // Remove current item newSchema.Properties.Add("ExcludeCurrentItem", new SchemaConfig() { Title = "Exclude Current Item", Type = "boolean" }); // Show only Current User Items newSchema.Properties.Add("CurrentUserItems", new SchemaConfig() { Title = "Only Current User Items", Type = "boolean" }); // Filter SchemaConfig newSchemaFilter = new SchemaConfig(true) { Title = "Filter" }; newSchema.Properties.Add("Filter", newSchemaFilter); OptionsConfig newOptions = new OptionsConfig(true); OptionsConfig newOptionsFilter = new OptionsConfig(true); newOptions.Fields.Add("Filter", newOptionsFilter); SchemaConfig schemaConfig = new SchemaConfig(); var schemaJson = jsonEdit["schema"]; if (schemaJson != null) { schemaConfig = schemaJson.ToObject <SchemaConfig>(); } OptionsConfig optionsConfig = new OptionsConfig(); JToken optionsJson = jsonEdit["options"]; if (optionsJson != null) { optionsConfig = optionsJson.ToObject <OptionsConfig>(); } List <string> fieldLst = new List <string>(); GetFields(newSchemaFilter, newOptionsFilter, schemaConfig, optionsConfig, fieldLst, indexConfig); fieldLst.Add(JsonMappingUtils.FIELD_TIMESTAMP); // Sort SchemaConfig newSchemaSort = new SchemaConfig() { Type = "array", Title = "Sort" }; newSchema.Properties.Add("Sort", newSchemaSort); newSchemaSort.Type = "array"; newSchemaSort.Items = new SchemaConfig(true); newSchemaSort.Items.Properties.Add("Field", new SchemaConfig() { Title = "Field", Enum = fieldLst }); newSchemaSort.Items.Properties.Add("Order", new SchemaConfig() { Title = "Order", Enum = new List <string>(new string[] { "asc", "desc" }) }); OptionsConfig newOptionsSort = new OptionsConfig(); newOptions.Fields.Add("Sort", newOptionsSort); newOptionsSort.Type = "table"; newOptionsSort.Items = new OptionsConfig(true); newOptionsSort.Items.Fields.Add("Field", new OptionsConfig() { Type = "select", RemoveDefaultNone = true }); newOptionsSort.Items.Fields.Add("Order", new OptionsConfig() { Type = "select", RemoveDefaultNone = true }); var json = new JObject(); json["schema"] = JObject.FromObject(newSchema); json["options"] = JObject.FromObject(newOptions); //File.WriteAllText(TemplateUri.PhysicalFullDirectory + "\\test.json", json.ToString()); return(json); }
public override void Deserialize(Dictionary <PCFResourceType, DataBlockBase> dataBlocks, UnityNodeBase parentNode, ResourceResponse resourceResponse, List <Action <UnityNodeBase> > postInstallActions, bool optimizedLoad) { GameObject parentGameObject = parentNode.GetGameObject(); this.skinnedMesh = parentGameObject.AddComponent <SkinnedMeshRenderer>(); ResourceBlock dataBlock = dataBlocks[resourceType] as ResourceBlock; AssetResource resource = dataBlock.GetResource(this.referenceID); byte[] metaDataBuffer = resource.GetMetaData(); JObject metaData = JObject.Parse(System.Text.Encoding.UTF8.GetString(metaDataBuffer)); UInt32 materialID = metaData.Value <UInt32>("materialID"); string rootBoneName = metaData.Value <string>("rootBone"); string probeBoneName = metaData.Value <string>("probeAnchor"); int quality = metaData.Value <int>("quality"); string[] boneNames = metaData.Value <JArray>("bones").ToObject <string[]>(); float[] blendShapeWeights = metaData.Value <JArray>("blendShapeWeights").ToObject <float[]>(); // Add a post install action so the bones will have time to be created. postInstallActions.Add((UnityNodeBase node) => { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); Transform[] bones = new Transform[boneNames.Length]; //Mapp all bone transform in the hierarchy. Dictionary <string, Transform> bonesMapping = new Dictionary <string, Transform>(); FindTransformsInHierarchy(node, bonesMapping); for (int i = 0; i < boneNames.Length; i++) { string name = boneNames[i]; if (bonesMapping.ContainsKey(name)) { bones[i] = bonesMapping[name]; } else { bones[i] = null; } } this.mesh = MeshSerializeUtilities.ReadMesh(resource.GetResourceData(), true); if (optimizedLoad) { //Free up mono memory for this mesh, now owned by the GPU. this.mesh.UploadMeshData(true); } this.skinnedMesh.sharedMesh = this.mesh; this.skinnedMesh.bones = bones; this.skinnedMesh.quality = (SkinQuality)Enum.ToObject(typeof(SkinQuality), quality); for (int i = 0; i < blendShapeWeights.Length; i++) { this.skinnedMesh.SetBlendShapeWeight(i, blendShapeWeights[i]); } if (bonesMapping.ContainsKey(rootBoneName)) { this.skinnedMesh.rootBone = bonesMapping[rootBoneName]; } if (probeBoneName != null) { this.skinnedMesh.probeAnchor = bonesMapping[probeBoneName]; } watch.Stop(); //Debug.Log("time to deserialize skinned mesh: " + watch.ElapsedMilliseconds); }); for (int i = 0; i < this.ChildNodes.Count; i++) { UnityNodeBase child = this.ChildNodes[i]; //Create a request to be send down the chain of children, see if any child will handle it. ResourceResponse materialRequest = new ResourceResponse(materialID, (ResourceResponse response) => { skinnedMesh.material = response.GetMaterialRequest; }); child.Deserialize(dataBlocks, this, materialRequest, postInstallActions, optimizedLoad); } }
public async Task <JArray> GetProjectsAsync(string hubId) { Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // the API SDK ProjectsApi projectsApi = new ProjectsApi(); projectsApi.Configuration.AccessToken = credentials.TokenInternal; var projectsDM = await projectsApi.GetHubProjectsAsync(hubId); // 2-legged account:read token TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead }); // get all projects RestClient client = new RestClient(BASE_URL); RestRequest projectsRequest = new RestRequest("/hq/v1/accounts/{account_id}/projects?limit=100", RestSharp.Method.GET); projectsRequest.AddParameter("account_id", hubId.Replace("b.", string.Empty), ParameterType.UrlSegment); projectsRequest.AddHeader("Authorization", "Bearer " + bearer.access_token); IRestResponse projectsResponse = await client.ExecuteTaskAsync(projectsRequest); dynamic projectsHQ = JArray.Parse(projectsResponse.Content); // get business units RestRequest bizUnitsRequest = new RestRequest("/hq/v1/accounts/{account_id}/business_units_structure", RestSharp.Method.GET); bizUnitsRequest.AddParameter("account_id", hubId.Replace("b.", string.Empty), ParameterType.UrlSegment); bizUnitsRequest.AddHeader("Authorization", "Bearer " + bearer.access_token); IRestResponse bizUnitsResponse = await client.ExecuteTaskAsync(bizUnitsRequest); dynamic bizUnits = JObject.Parse(bizUnitsResponse.Content); if (bizUnits.business_units != null) { foreach (dynamic projectHQ in projectsHQ) { foreach (dynamic bizUnit in bizUnits.business_units) { if (projectHQ.business_unit_id == bizUnit.id) { projectHQ.business_unit = bizUnit; } } } } dynamic projectsFullData = new JArray(); foreach (dynamic projectHQ in projectsHQ) { if (projectHQ.status != "active") { continue; } foreach (KeyValuePair <string, dynamic> projectDM in new DynamicDictionaryItems(projectsDM.data)) { if (projectHQ.id == projectDM.Value.id.Replace("b.", string.Empty)) { projectHQ.DMData = JObject.Parse(projectDM.Value.ToString()); break; } } projectsFullData.Add(projectHQ); } return(new JArray(((JArray)projectsFullData).OrderBy(p => (string)p["name"]))); }
static void Main() { Console.Clear(); Console.Title = "2DXTicker"; Console.Write("-------------------------\nCreated by GHYAKIMA#4310\n-------------------------\nBuild: {0}\nVersion: {1}x\n-------------------------\n", _buildDate,_version); // Parse the json file try { _jsonData = JObject.Parse(File.ReadAllText(_jsonPath)); } catch (FileNotFoundException ex) { throw ex; } // Wait for beatmania process while (_waitForProcess) { foreach (dynamic _json in _jsonData.Titles) { // Get hwnd if (_hwnd == IntPtr.Zero) { _hwnd = memUtils.FindWindow((string)_json.windowTitle); _windowTitle = (string)_json.windowTitle; } else if (_hwnd != IntPtr.Zero && _windowTitle == (string)_json.windowTitle) { _moduleName = (string)_json.moduleName; _tickerAddress = (int)_json.tickerAddress; } } // Get process id if (_processID == 0) { _processID = memUtils.GetWindowPID(_hwnd); } else { // Get process handle if (_pHandle == IntPtr.Zero) { _pHandle = memUtils.OpenProcess(_processID); } // Get base address of '_moduleName' _memoryAddress = IntPtr.Add(memUtils.GetModuleAddress(_processID, _moduleName), _tickerAddress); _waitForProcess = false; } /* */ Thread.Sleep(1000); } /* debug info */ if ((bool)_jsonData.Ticker.debug) { Console.Write("_windowTitle: {0}\n_moduleName: {1}\n_tickerAddress: {2}\n-------------------------", _windowTitle, _moduleName, "0x" + _tickerAddress.ToString("X")); Console.Write("\n_hwnd: {0}\n_processID: {1}\n_pHandle: {2}\n_memoryAddress: {3}\n-------------------------\n", _hwnd, _processID, _pHandle, "0x" + _memoryAddress.ToString("X")); } /* Create event handler */ _process = Process.GetProcessById((int)_processID); _process.EnableRaisingEvents = true; _process.Exited += new EventHandler(process_Exited); /* Open serial connection */ setupConnection(); /* Start reading ticker bytes */ if (serialPort.IsOpen) { readTickerBytes(); } Thread.Sleep(-1); }
public static async Task<JObject> GetJObjectFromJsonBodyAsync(this HttpContext source) { var json = await source.ReadBodyTextAsync(); var result = JObject.Parse(json); return result; }
private void a_valid_address_is_validated() { JObject jObjectResponse = JObject.Parse(this.responseText); jObjectResponse["isvalid"].Value<bool>().Should().BeTrue(); }
internal Status(JObject status) : base(status) { }
public void AddValueToObject() { JObject o = new JObject(); o.Add(5); }
public ThemeItemState(JObject o) { Parse(o); }
public void Parse() { JObject o = (JObject)JToken.Parse("{'pie':true}"); Assert.AreEqual(true, (bool)o["pie"]); }
public static string GetAliasFromConfig(JObject config) { var name = GetValue <string>(config, "v2raygcon.alias"); return(string.IsNullOrEmpty(name) ? I18N.Empty : CutStr(name, 12)); }
private bool FieldExists(string fieldName, JObject jObject) { return(jObject[fieldName] != null); }
public static string Config2String(JObject config) { return(config.ToString(Formatting.None)); }
/// <summary> /// Builds the object from the JSON response body /// </summary> /// <param name="data">JSON response body as a <see cref="JObject"/></param> public TransitionSettings(JObject data) { JsonConvert.PopulateObject(data.ToString(), this); }
public static string Config2Base64String(JObject config) { return(Base64Encode(config.ToString(Formatting.None))); }
private static string TryGetValue(JObject user, string propertyName) { JToken value; return(user.TryGetValue(propertyName, out value) ? value.ToString() : null); }
private void StoreChanged(object sender, JObject data) { ComputeContent(inputContent, data); }