public void Delete(DataModel application) { if (string.IsNullOrEmpty(application.Id) || _array.All(d => d["Id"].ToString() != application.Id)) { return; } var token = _array.FirstOrDefault(d => d["Id"].ToString() == application.Id); _array.Remove(token); File.WriteAllText(_dataPath, _dataSource.ToString()); // could be very time consuming. Also for update it will be hit twice. Only for interview purposes }
private ActionResult PostToCollection(System.IO.FileInfo collFile) { // we are putting a manifest into a collection - but this is not containment, it's association. // The JSON-LD object posted is just the @id var postedObject = GetRequestBodyAsJObject(); // require for now it looks like this: // { "@id": ... , "@type": "sc:Manifest" } // we can relax this a bit later... var asUri = new Uri(postedObject["@id"].ToString()); var mfOp = Resolve("POST", asUri); if (mfOp != null) { var filePath = GetManifestFile(mfOp.Params[0]); JArray manifestList = new JArray(); if (collFile.Exists) { manifestList = JArray.Parse(System.IO.File.ReadAllText(collFile.FullName)); } if (manifestList.All(m => m.ToString() != filePath.FullName)) { manifestList.Add(filePath.FullName); var json = JsonConvert.SerializeObject(manifestList, Formatting.Indented); System.IO.File.WriteAllText(collFile.FullName, json, Encoding.UTF8); } Response.StatusCode = 202; Response.StatusDescription = "Accepted"; return(Content("\"Accepted\"", "application/json")); } Response.StatusCode = 400; Response.StatusDescription = "Only Presley manifests for now in this mockup"; return(new EmptyResult()); }
private string Week(string groupId) { dynamic data = JsonConvert.DeserializeObject(GetSchedule(groupId)); if (data["schedules"] == null) { return($"Group {groupId} is free this week!"); } var output = new StringBuilder($"This week's schedule for group {groupId} is:\n"); foreach (var day in data["schedules"]) { output += "\n" + day["weekDay"] + ":\n"; bool freeDay = true; foreach (var lesson in day["schedule"]) { JArray weekNumber = lesson["weekNumber"]; var currentWeek = data["currentWeekNumber"]; if (weekNumber.All(kek => kek != currentWeek)) { continue; } output += LessonToString(lesson); freeDay = false; } if (freeDay) { output.Append("This day is free this week!\n"); } } return(output.ToString()); }
public HttpResponseMessage GetAllBeers(string beerName) { try { HttpResponseMessage httpResponseMessage; if (string.IsNullOrWhiteSpace(beerName)) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter valid name.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } JArray beers = null; if (!string.IsNullOrWhiteSpace(_data)) { beers = JArray.Parse(_data); if (beers.All(x => x.SelectToken("name").ToString() != beerName)) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter valid name with this no beer exists.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } } JObject jObject = (JObject)beers.FirstOrDefault(x => x.SelectToken("name").ToString() == beerName);//.FirstOrDefault().Select(x => new { Id = x.SelectToken("id").ToString(), name = x.SelectToken("name").ToString(), description = x.SelectToken("description").ToString() }); var beer = new Beer { Id = (int)jObject.SelectToken("id"), description = jObject.SelectToken("description").ToString(), name = jObject.SelectToken("name").ToString() }; var dataFile = Path.Combine("E:\\Test Projects\\TestPunkApi\\", "Database.json"); var jsonData = System.IO.File.ReadAllText(dataFile); var db = JsonConvert.DeserializeObject <DbJson>(jsonData); if (!db.searchbeers.Any(x => x.Id.ToString() == beer.Id.ToString())) { db.searchbeers.Add(beer); jsonData = JsonConvert.SerializeObject(db); File.WriteAllText(dataFile, jsonData); } var ratings = db.userRatings.Where(x => x.BeerId.ToString() == beer.Id.ToString()).ToList(); httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = new { beer.Id, beer.name, beer.description, ratings }, error = "0" }, new JsonMediaTypeFormatter()), StatusCode = HttpStatusCode.OK }; return(httpResponseMessage); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Failure")); } }
private static object[] ConvertArray(JArray array, JsonSerializer serializer) { // There are two cases to consider: Either everything is a string, or it's not. If not, don't attempt // any conversions and return everything in an object array. return(array.All(t => t.Type == JTokenType.String || t.Type == JTokenType.Null) ? array.Select(t => t.Value <string>()).ToArray() : array.Select(t => t.ToObject(typeof(object), serializer)).ToArray()); }
public void RootContainerHasTfsProjectCollectionNodeChildren() { JArray expectedProjects = TfsDataService.RetrieveProjectCollections(); Collection <IDriveItem> actualProjectNodes = PowerShell.AddScript($"Get-ChildItem").Invoke <IDriveItem>(); Assert.IsFalse(PowerShell.HadErrors); Assert.IsTrue(expectedProjects.All(expectedProject => actualProjectNodes.Any(projectNode => projectNode.Name == expectedProject.Value <string>("name")))); }
public HttpResponseMessage AddRatingToBeer(BeerRating beerRating) { try { JArray beers = null; HttpResponseMessage httpResponseMessage; if (!string.IsNullOrWhiteSpace(_data)) { beers = JArray.Parse(_data); if (beers.All(x => x.SelectToken("id").ToString() != beerRating.BeerId.ToString())) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter valid id with this no beer exists.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } } if (beerRating != null && (beerRating.Rating == 0 || beerRating.Rating > 5)) { httpResponseMessage = new HttpResponseMessage() { Content = new ObjectContent <object>(new { message = "Please enter rating range between 1 to 5 only.", error = "1" }, new JsonMediaTypeFormatter()), ReasonPhrase = "Invalid request", StatusCode = HttpStatusCode.BadRequest }; return(httpResponseMessage); } var jObject = (JObject)beers.FirstOrDefault(x => beerRating != null && x.SelectToken("id").ToString() == beerRating.BeerId.ToString()); string json = JsonConvert.SerializeObject(beerRating, Formatting.Indented); var dataFile = Path.Combine("E:\\Test Projects\\TestPunkApi\\", "Database.json"); //Reading the file var jsonData = System.IO.File.ReadAllText(dataFile); var db = JsonConvert.DeserializeObject <DbJson>(jsonData); db.userRatings.Add(beerRating); jsonData = JsonConvert.SerializeObject(db); System.IO.File.WriteAllText(dataFile, jsonData); httpResponseMessage = new HttpResponseMessage { Content = new ObjectContent <object>(new { message = "success", error = "0" }, new JsonMediaTypeFormatter()), StatusCode = HttpStatusCode.OK }; return(httpResponseMessage); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Failure")); } }
private bool ValidateTaxonomyTerm(dynamic parent, ContentItem term) { JArray terms = _taxonomyHelper.GetTerms(JObject.FromObject(parent)); return(terms?.All(x => (string)x["ContentItemId"] == term.ContentItemId || (string)x["DisplayText"] != term.DisplayText) ?? true); }
private void clearTempRes(JArray queryRes, string projId) { tempNotClearAllFlag = false; if (queryRes.All(p => p["memberAddress"] == null)) { return; } var rr = queryRes.Where(p => p["event"].ToString() == "SubmitVote").Select(p => new { address = p["memberAddress"].ToString(), proposalIndex = p["proposalIndex"].ToString() }).ToArray(); var rb = queryRes.Select(p => { var eventName = p["event"].ToString(); if (eventName == "SummonComplete") { return(p["summoner"].ToString()); } if (eventName == "ProcessProposal") { return(p["applicant"].ToString()); } if (eventName == "Ragequit") { return(p["memberAddress"].ToString()); } return(""); }).Where(p => p != "").Distinct().ToArray(); // 清除临时字段数据 tempNotClearAllFlag = false; var dbZERO = decimal.Zero.format(); try { foreach (var item in rr) { var findStr = new JObject { { "projId", projId }, { "proposalIndex", item.proposalIndex }, { "address", item.address } }.ToString(); var updateStr = new JObject { { "$set", new JObject { { "balanceTp", 0 } } } }.ToString(); mh.UpdateData(lConn.connStr, lConn.connDB, moloProjBalanceInfoCol, updateStr, findStr); } foreach (var item in rb) { var findStr = new JObject { { "projId", projId }, { "proposalIndex", "" }, { "address", item } }.ToString(); var updateStr = new JObject { { "$set", new JObject { { "balanceTp", 0 } } } }.ToString(); mh.UpdateData(lConn.connStr, lConn.connDB, moloProjBalanceInfoCol, updateStr, findStr); } } catch (Exception ex) { // Console.WriteLine(ex); tempNotClearAllFlag = true; } }
public bool TrySet(JArray filterTokens) { return(filterTokens.All(TrySet)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "mergeproperties")] HttpRequest req, ILogger log) { // Get Request Details RequestDetails requestDetails = new RequestDetails(req, LogId); string logPrefix = $"{LogId}:{requestDetails.TrackingId}: "; // Add the tracking ID to the Response Headers if (!string.IsNullOrWhiteSpace(requestDetails.TrackingId)) { req.HttpContext.Response.Headers[HeaderConstants.AimTrackingId] = requestDetails.TrackingId; } log.LogDebug($"{logPrefix}Called with parameters messageContentType: {requestDetails.RequestContentType}, messageContentEncoding: {requestDetails.RequestContentEncoding}, messageTransferEncoding: {requestDetails.RequestTransferEncoding}, headerTrackingId: {requestDetails.TrackingId}, clearCache: {requestDetails.ClearCache}, enableTrace: {requestDetails.EnableTrace}"); // Validate the request IActionResult result = ValidateRequest(requestDetails, logPrefix, log); if (result != null) { return(await Task.FromResult <IActionResult>(result)); } log.LogDebug($"{logPrefix}Request parameters are valid"); // We expect the body to be an array of property bags // e.g. // [ // { // "properties": // { // "property1": "value1" // } // }, // { // "properties": // { // "property2": "value2" // } // } // ] // Check we have a JSON array in the body content if (!(requestDetails.RequestBodyAsJson is JArray)) { // We need an array to be supplied return(await Task.FromResult <IActionResult>(AzureResponseHelper.CreateFaultObjectResult(requestDetails, "The supplied request body is not a JSON array", logPrefix, log))); } JArray propertiesArray = requestDetails.RequestBodyAsJson as JArray; // Check we have at least one element in the array if (propertiesArray.Count == 0) { // We need at least one element in the supplied array return(await Task.FromResult <IActionResult>(AzureResponseHelper.CreateFaultObjectResult(requestDetails, "The supplied request body contains an empty JSON array", logPrefix, log))); } // Check that all the array elements are JSON Objects if (!propertiesArray.All(j => j is JObject)) { // All elements in the array must be JSON Objects return(await Task.FromResult <IActionResult>(AzureResponseHelper.CreateFaultObjectResult(requestDetails, "All elements in the supplied JSON Array must be JSON Objects", logPrefix, log))); } JObject firstElement = propertiesArray[0] as JObject; log.LogDebug($"{logPrefix}Merging property objects"); try { // Merge every subsequent element in the array (other than the first) with the first array element for (int arrayIndex = 1; arrayIndex < propertiesArray.Count; arrayIndex++) { firstElement.Merge(propertiesArray[arrayIndex] as JObject, new JsonMergeSettings { // Union array values together to avoid duplicates MergeArrayHandling = MergeArrayHandling.Union }); } } catch (Exception ex) { return(await Task.FromResult <IActionResult>(AzureResponseHelper.CreateFaultObjectResult(requestDetails, $"An exception occurred trying to merge the property bags", ex, logPrefix, log))); } return(await Task.FromResult <IActionResult>(new OkObjectResult(firstElement))); }
private bool AndEvaluator(JArray conditions, UserAttributes userAttributes) { return(conditions.All(condition => Evaluate(condition, userAttributes))); }