public bool FetchDiff (Push push) { string url = null; try { string response = CachingFetcher.FetchDiff (push.CHAuthID, push.Repository.Owner.Name, push.Repository.Name, ID, out url); if (response == null) return false; var jdes = new JsonDeserializer (); var wrapper = jdes.Deserialize<CommitWithDiffJsonWrapper> (response); if (wrapper != null) { var diff = wrapper.Commit; if (!diff.FetchBlobs (push)) { Log (LogSeverity.Error, "Failed to fetch blobs for commit '{0}' from URL '{1}'", ID, url); return false; } Diff = diff; } else { Log (LogSeverity.Error, "Failed to fetch diff for commit '{0}' from URL '{1}'", ID, url); return false; } } catch (Exception ex) { Log (ex, "Exception while fetching diff for commit '{4}' from URL '{5}'\n{0}", ID, url); return false; } CommitWithDiff ret = Diff; if (ret == null) Log (LogSeverity.Info, "FetchDiff did not fail, but no diff retrieved?"); return ret != null; }
public void TestReadTrelloExport() { var contents = File.ReadAllText("..\\..\\..\\..\\Data\\Trello\\testExport.json"); var x = new JsonDeserializer(); var dato = SimpleJson.DeserializeObject<Board>(contents); }
private static bool HitboxOnlineState(string sStream) { var req = new RestRequest("/media/live/" + sStream, Method.GET); IRestClientProvider _restClientProvider = new RestClientProvider(new RestClient("http://api.hitbox.tv")); var response = _restClientProvider.Execute(req); try { var des = new JsonDeserializer(); var data = des.Deserialize<HitboxRootObject>(response); foreach (var item in data.livestream) { if(item.media_user_name.ToLower() == sStream.ToLower()) { if(item.media_is_live == "1") { return true; } } } return false; } catch (Exception) { return false; } }
private void GetToken_Click(object sender, RoutedEventArgs e) { var client = new RestClient("https://api.home.nest.com/oauth2/access_token"); var request = new RestRequest(Method.POST); request.AddParameter("client_id", TextNestClientId.Text); request.AddParameter("code", TextNestPin.Text); request.AddParameter("client_secret", PwNestSecret.Password); request.AddParameter("grant_type", "authorization_code"); var response = client.Execute(request); JsonDeserializer deserializer = new JsonDeserializer(); var json = deserializer.Deserialize<Dictionary<string, string>>(response); if (json.ContainsKey("access_token")) { TextNestAccessToken.Text = json["access_token"]; return; } if (json.ContainsKey("message")) { TextNestAccessToken.Text = json["message"]; return; } if (json.ContainsKey("error_description")) { TextNestAccessToken.Text = json["error_description"]; return; } }
public void ReplayAllEvents() { using (IDocumentSession session = _eventStorage.OpenSession()) { int startPos = 0; while (true) { RavenQueryStatistics stats; var events = session.Query<EventDescriptor>() .Statistics(out stats) .OrderBy(ev => ev.AggregateId) .ThenBy(ev => ev.Version) .Select(ev => ev) .Skip(startPos) .ToArray(); JsonDeserializer deserializer = new JsonDeserializer(); foreach (EventDescriptor ev in events) { Publish(deserializer.Deserialize(ev.EventType, ev.EventData)); } if (stats.TotalResults <= startPos) { break; } startPos += 128; } } }
public void Setup() { string url = ConfigurationManager.AppSettings["url"]; string clientKey = ConfigurationManager.AppSettings["client-key"]; string clientSecret = ConfigurationManager.AppSettings["client-secret"]; responsePath = ConfigurationManager.AppSettings["response-path"]; Assert.IsNotNullOrEmpty(clientKey); Assert.IsNotNullOrEmpty(clientSecret); Assert.IsNotNullOrEmpty(url); // ReSharper disable UnusedVariable //##BEGIN EXAMPLE accessingapi## var api = new Api(url, clientKey, clientSecret); var tokenResponse = api.Authenticate(); var rootLinks = api.Root; //##END EXAMPLE## // ReSharper restore UnusedVariable responses = ResponseReader.readResponses(responsePath); deserializer = new JsonDeserializer(); TestUtils.Deserializer = deserializer; }
public void JSONDeserializationTest() { var path = Path.Combine(Environment.CurrentDirectory, "User.json"); var ds = new JsonDeserializer(); var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK }; // Read the file as one string. StreamReader myFile = new StreamReader(path); string json = myFile.ReadToEnd(); myFile.Close(); response.Content = json; var myUser = ds.Deserialize<User>(response); Assert.IsNotNull(myUser); Assert.AreEqual("PT23IWX", myUser.id); Assert.AreEqual("Tim Wright", myUser.name); Assert.AreEqual("*****@*****.**", myUser.email); Assert.AreEqual("Eastern Time (US & Canada)", myUser.time_zone); Assert.AreEqual("purple", myUser.color); Assert.AreEqual("owner", myUser.role); Assert.AreEqual("https://secure.gravatar.com/avatar/923a2b907dc04244e9bb5576a42e70a7.png?d=mm&r=PG", myUser.avatar_url); Assert.AreEqual("/users/PT23IWX", myUser.user_url); Assert.AreEqual(false, myUser.invitation_sent); Assert.AreEqual(false, myUser.marketing_opt_out); }
public JiraRestClient(string baseUrl, string username, string password) { this.username = username; this.password = password; deserializer = new JsonDeserializer(); client = new RestClient { BaseUrl = new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/") + "rest/api/2/") }; }
public void JSONDeserializationTest() { var path = Path.Combine(Environment.CurrentDirectory, "Schedule.json"); var ds = new JsonDeserializer(); var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK }; // Read the file as one string. StreamReader myFile = new StreamReader(path); string json = myFile.ReadToEnd(); myFile.Close(); response.Content = json; var mySchedule = ds.Deserialize<Schedule>(response); Assert.IsNotNull(mySchedule); Assert.IsNotNull(mySchedule.escalation_policies); Assert.AreEqual("FS4LEQD", mySchedule.id); Assert.AreEqual("24x7 Schedule", mySchedule.name); Assert.AreEqual("UTC", mySchedule.time_zone); Assert.AreEqual(new DateTime(635726880000000000), mySchedule.today); Assert.AreEqual(1, mySchedule.escalation_policies.Count); Assert.AreEqual("PAD5HK6", mySchedule.escalation_policies[0].id); Assert.AreEqual("Escalation Policy - 24x7", mySchedule.escalation_policies[0].name); }
public void JSONDeserializationTest() { var path = Path.Combine(Environment.CurrentDirectory, "Incident.json"); var ds = new JsonDeserializer(); var response = new RestResponse() { ContentType = "application/json", ResponseStatus = ResponseStatus.Completed, StatusCode = System.Net.HttpStatusCode.OK }; // Read the file as one string. StreamReader myFile = new StreamReader(path); string json = myFile.ReadToEnd(); myFile.Close(); response.Content = json; var myAlert = ds.Deserialize<Incident>(response); Assert.IsNotNull(myAlert); Assert.IsNotNull(myAlert.service); Assert.IsNotNull(myAlert.last_status_change_by); Assert.AreEqual("1", myAlert.incident_number); Assert.AreEqual(new DateTime(634830005610000000), myAlert.created_on); Assert.AreEqual("resolved", myAlert.status); Assert.AreEqual("https://acme.pagerduty.com/incidents/P2A6J96", myAlert.html_url); Assert.AreEqual(null, myAlert.incident_key); Assert.AreEqual(null, myAlert.assigned_to_user); Assert.AreEqual("https://acme.pagerduty.com/incidents/P2A6J96/log_entries/P2NQP6P", myAlert.trigger_details_html_url); Assert.AreEqual(new DateTime(634830006590000000), myAlert.last_status_change_on); }
private void OnContentReceived(string content) { JsonDeserializer deserializer = new JsonDeserializer(); var response = new RestResponse(); response.Content = content; MessageContent messageContent = null; try { messageContent = deserializer.Deserialize<MessageContent>(response); } catch { MessageContent = null; } if (messageContent != null) { MessageContent = messageContent; if (Event == "message" || Event == "comment") { ExtractedBody = messageContent.Text; } } else if(Event == "message") { ExtractedBody = content; } Displayable = ExtractedBody != null; TimeStamp = UnixTimeToLocal(Sent); }
public void TestDeserializeChannelResult() { var doc = File.ReadAllText(Path.Combine("Resources", "channels.json")); var json = new JsonDeserializer(); var output = json.Deserialize<ChannelResult>(new RestResponse {Content = doc}); Assert.NotNull(output); Assert.NotNull(output.Channels); Assert.AreEqual(1, output.Channels.Count); Assert.AreEqual("CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", output.Channels[0].Sid); Assert.AreEqual("ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", output.Channels[0].AccountSid); Assert.AreEqual("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", output.Channels[0].ServiceSid); Assert.AreEqual("my channel", output.Channels[0].FriendlyName); Assert.IsEmpty(output.Channels[0].Attributes); Assert.AreEqual("system", output.Channels[0].CreatedBy); Assert.AreEqual("public", output.Channels[0].Type); Assert.AreEqual( "http://localhost/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", output.Channels[0].Url); Dictionary<string, string> dictionary = output.Channels[0].Links; Assert.NotNull(dictionary); Assert.True(dictionary.ContainsKey("members")); Assert.True(dictionary.ContainsKey("messages")); Assert.AreEqual( "http://localhost/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members", dictionary["members"]); Assert.AreEqual( "http://localhost/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages", dictionary["messages"]); }
/// <summary> /// Initializes a new instance of the <see cref="AccessTokenClient"/> class. /// </summary> /// <param name="serverConfiguration">The client configuration.</param> /// <exception cref="System.ArgumentNullException">clientConfiguration</exception> public AccessTokenClient(OAuthServerConfiguration serverConfiguration) { Requires.NotNull(serverConfiguration, "clientConfiguration"); this.jsonDeserializer = new JsonDeserializer(); this.serverConfiguration = serverConfiguration; this.RestClient = new RestClient(serverConfiguration.BaseUrl.ToString()); }
public void Deserialize_SerializationRepresentation_DeserializedObject() { var subject = new JsonDeserializer(); var deserialized = subject.Deserialize<Serializable>(Serializable.JsonString("s", 3m)); Assert.That(deserialized.D, Is.EqualTo(3m)); Assert.That(deserialized.S, Is.EqualTo("s")); }
public void testDeserializeResponse() { var doc = File.ReadAllText(Path.Combine("Resources", "workspace_statistics.json")); var json = new JsonDeserializer(); var output = json.Deserialize<WorkspaceStatistics>(new RestResponse { Content = doc }); Assert.NotNull(output); }
public void testDeserializeListResponse() { var doc = File.ReadAllText(Path.Combine("Resources", "task_queues_statistics.json")); var json = new JsonDeserializer(); var output = json.Deserialize<TaskQueueStatisticsResult>(new RestResponse { Content = doc }); Assert.NotNull(output); }
public static SinusModel GetParams() { var request = new RestRequest(Method.GET); request.Resource = "model/" + ModelId; IRestResponse response = client.Execute (request); var json = new JsonDeserializer(); return json.Deserialize<SinusModel>(response); }
public void testDeserializeInstanceResponse() { var doc = Twilio.Api.Tests.Utilities.UnPack(BASE_NAME + "worker_statistics.json"); var json = new JsonDeserializer(); var output = json.Deserialize<WorkerStatistics>(new RestResponse { Content = doc }); Assert.NotNull(output); }
public RottenTomatoes(string apiKey) { ApiKey = apiKey; Error = null; Timeout = null; Deserializer = new JsonDeserializer(); Generator = new RequestGenerator(apiKey); }
public void testDeserializeListResponse() { //var doc = File.ReadAllText(Path.Combine("Resources", "workers_statistics.json")); var doc = Twilio.Api.Tests.Utilities.UnPack(BASE_NAME + "workers_statistics.json"); var json = new JsonDeserializer(); var output = json.Deserialize<WorkersStatistics>(new RestResponse { Content = doc }); Assert.NotNull(output); }
public FanartTV(string apiKey) { ApiKey = apiKey; Error = null; Timeout = null; Deserializer = new JsonDeserializer(); Generator = new RequestGenerator(apiKey); }
public Boolean OnLogInButtonClicked(string email, string password) { var hud = DependencyService.Get<IHud> (); hud.Show ("Verifying Credentials"); var client = new RestClient("http://dev.envocsupport.com/GameStore2/"); var request = new RestRequest("api/ApiKey?email=" + email + "&password="******"application/json"; }; IRestResponse queryResult = client.Execute(request); if (queryResult.StatusCode == HttpStatusCode.OK) { RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer(); var x = deserial.Deserialize<UserApiKey>(queryResult); Application.Current.Properties["ApiKey"] = x.ApiKey; Application.Current.Properties ["UserId"] = x.UserId; //Console.WriteLine ("first" + queryResult.Content); // Console.WriteLine ("key:"+x.ApiKey); // next request for User request = new RestRequest ("api/Users/"+x.UserId,Method.GET); var ApiKey = Application.Current.Properties ["ApiKey"]; var UserId = Application.Current.Properties ["UserId"]; request.AddHeader ("xcmps383authenticationkey",ApiKey.ToString ()); request.AddHeader ("xcmps383authenticationid",UserId.ToString ()); queryResult = client.Execute (request); User user = new User (); statusCodeCheck (queryResult); if (queryResult.StatusCode == HttpStatusCode.OK) { user = deserial.Deserialize<User>(queryResult); } Application.Current.Properties ["FirstName"] = user.FirstName; // Console.WriteLine (Application.Current.Properties ["UserId"]); //Console.WriteLine ("here" + queryResult.Content); loginStatus = true; return loginStatus ; } else { loginStatus = false; return loginStatus; } }
public void testDeserializeResponse() { var doc = File.ReadAllText(Path.Combine("Resources", "credential_list.json")); var json = new JsonDeserializer(); var output = json.Deserialize<CredentialList>(new RestResponse { Content = doc }); Assert.NotNull(output); Assert.NotNull(output.DateCreated); Assert.AreEqual("support", output.FriendlyName); }
public void testDeserializeResponse() { var doc = File.ReadAllText(Path.Combine("Resources", "phone_number.json")); var json = new JsonDeserializer(); var output = json.Deserialize<AssociatedPhoneNumber>(new RestResponse { Content = doc }); Assert.NotNull(output); Assert.NotNull(output.DateCreated); Assert.AreEqual("867-5309 (Jenny)", output.FriendlyName); }
/// <summary> /// Retrieves list of BannerFlow brands in given account /// </summary> /// <returns>List of brand</returns> public List<Brand> GetBrands() { var respBrands = apiClient.Request(String.Format("accounts/{0}/brands", credentials.accountSlug)); var brandList = new JsonDeserializer().Deserialize<List<Brand>>(respBrands); foreach (Brand brand in brandList) { Console.WriteLine(brand.name); } return brandList; }
public PagingResponse<Company> Current() { var url = string.Format("Company/Get?apikey={0}", _apiKey); var request = new RestRequest(url, Method.GET); request.RequestFormat = DataFormat.Json; var response = _client.Execute(request); JsonDeserializer deserializer = new JsonDeserializer(); return deserializer.Deserialize<PagingResponse<Company>>(response); }
public void testDeserializeListResponse() { var doc = Twilio.Api.Tests.Utilities.UnPack(BASE_NAME + "task_queues_statistics.json"); var json = new JsonDeserializer(); var output = json.Deserialize<TaskQueueStatisticsResult>(new RestResponse { Content = doc }); Assert.NotNull(output); Assert.NotNull(output.Meta); }
public void testDeserializeResponse() { var doc = File.ReadAllText(Path.Combine("Resources", "origination_url.json")); var json = new JsonDeserializer(); var output = json.Deserialize<OriginationUrl>(new RestResponse { Content = doc }); Assert.NotNull(output); Assert.NotNull(output.DateCreated); Assert.AreEqual(10, output.Weight); Assert.AreEqual(true, output.Enabled); }
public Tmdb(string apiKey, string language) { Error = null; ApiKey = apiKey; Language = language; Timeout = null; Deserializer = new JsonDeserializer(); Generator = new RequestGenerator(apiKey, Language); ETagGenerator = new RequestGenerator(apiKey, Language, Method.HEAD); }
public void testDeserializeListResponse() { var doc = File.ReadAllText(Path.Combine("../../Resources", "phone_number_countries.json")); var json = new JsonDeserializer(); var output = json.Deserialize<PhoneNumberCountryResult>(new RestResponse { Content = doc }); Assert.NotNull(output); Assert.AreEqual(3, output.Countries.Count); Assert.AreEqual("AC", output.Countries [0].IsoCountry); Assert.AreEqual("Ascension", output.Countries [0].Country); }
internal static void Main() { // Test connection to SQL Server Database.SetInitializer(new MigrateDatabaseToLatestVersion <AirportSystemMsSqlDbContext, ConfigurationMSSql>()); using (AirportSystemMsSqlDbContext db = new AirportSystemMsSqlDbContext()) { db.Database.CreateIfNotExists(); foreach (var e in db.FlightTypes) { Console.WriteLine(e.Name); } } // Test Deserializers var xmlSer = new XmlDeserializer(); var jsonSer = new JsonDeserializer(); var excelSer = new ExcelDeserializer(); var xmlPath = "../../../SampleInputFiles/sample.xml"; var jsonPath = "../../../SampleInputFiles/sample.json"; var excelPath = "../../../SampleInputFiles/sample.xlsx"; // Test repository var msSqlData = new AirportSystemMsSqlData(new AirportSystemMsSqlDbContext()); var pSqlData = new AirportSystemPSqlData(new AirportSystemPSqlDbContext()); var sqliteData = new AirportSystemSqliteData(new AirportSystemSqliteDbContext()); msSqlData.Airports.Add(new Airport { Code = "LBWN", Name = "Varna Airport" }); msSqlData.Airports.Add(new Airport { Code = "LBSF", Name = "Sofia Airport" }); msSqlData.Airlines.Add(new Airline { Name = "Bongo Air" }); Console.WriteLine(); Console.WriteLine("Airports:"); Console.WriteLine("=========="); foreach (var entity in msSqlData.Airports.GetAll(null)) { Console.WriteLine("{0} - {1}", entity.Code, entity.Name); } Console.WriteLine("Airlines:"); Console.WriteLine("=========="); foreach (var entity in msSqlData.Airlines.GetAll(null)) { Console.WriteLine("{0}", entity.Name); } // Test shedule updater var su = new ScheduleUpdater(msSqlData, pSqlData, sqliteData); int countAdded = 0; countAdded = su.UpdateScheduleFromFile(xmlPath, xmlSer); Console.WriteLine("{0} FLIGHTS ADDDED!!!", countAdded); countAdded = su.UpdateScheduleFromFile(jsonPath, jsonSer); Console.WriteLine("{0} FLIGHTS ADDDED!!!", countAdded); countAdded = su.UpdateScheduleFromFile(excelPath, excelSer); Console.WriteLine("{0} FLIGHTS ADDDED!!!", countAdded); Console.WriteLine(); var f = new FlightRepository(new AirportSystemMsSqlDbContext()); var allFlights = f.GetAll(null); foreach (var item in allFlights) { var fl = (Flight)item; Console.WriteLine("{0} - {1} - {2} - {3} - {4} - {5} - {6} - {7} - {8} - {9} - {10} - {11}", fl.DestinationAirport.Name, fl.DestinationAirport.Code, fl.FlightType.Name, fl.Plane.Manufacturers.Name, fl.Terminal.Name, fl.Plane.Airlines.Name, fl.Plane.PlanePassport.RegistrationNumber, fl.Plane.PlanePassport.YearOfRegistration, fl.Plane.PlanePassport.State, fl.SheduledTime, fl.Plane.Models.Name, fl.Plane.Models.Seats); } var filteredFlights = f.GetAll(x => x.DestinationAirportId == 3); Console.WriteLine(filteredFlights.Count()); }
private void ReceiveMessages() { try { while (true) { var metadata = _reader.ReadString(); var obj = JsonDeserializer.Deserialize(new StringReader(metadata)) as JsonObject; var messageType = obj.ValueAsString("MessageType"); switch (messageType) { case "Assembly": //{ // "MessageType": "Assembly", // "ContextId": 1, // "AssemblyPath": null, // "Diagnostics": [], // "Blobs": 2 //} // Embedded Refs (special) // Blob 1 // Blob 2 if (ProjectCompiled != null) { var compileResponse = new CompileResponse(); compileResponse.AssemblyPath = obj.ValueAsString(nameof(CompileResponse.AssemblyPath)); compileResponse.Diagnostics = ValueAsCompilationMessages(obj, (nameof(CompileResponse.Diagnostics))); int contextId = obj.ValueAsInt("ContextId"); int blobs = obj.ValueAsInt("Blobs"); var embeddedReferencesCount = _reader.ReadInt32(); compileResponse.EmbeddedReferences = new Dictionary <string, byte[]>(); for (int i = 0; i < embeddedReferencesCount; i++) { var key = _reader.ReadString(); int valueLength = _reader.ReadInt32(); var value = _reader.ReadBytes(valueLength); compileResponse.EmbeddedReferences[key] = value; } var assemblyBytesLength = _reader.ReadInt32(); compileResponse.AssemblyBytes = _reader.ReadBytes(assemblyBytesLength); var pdbBytesLength = _reader.ReadInt32(); compileResponse.PdbBytes = _reader.ReadBytes(pdbBytesLength); // Skip over blobs that aren't understood for (int i = 0; i < blobs - 2; i++) { int length = _reader.ReadInt32(); _reader.ReadBytes(length); } ProjectCompiled(contextId, compileResponse); } break; case "Sources": //{ // "MessageType": "Sources", // "Files": [], //} if (ProjectSources != null) { var files = obj.ValueAsStringArray("Files"); ProjectSources(files); } break; case "ProjectContexts": //{ // "MessageType": "ProjectContexts", // "Projects": { "path": id }, //} if (ProjectsInitialized != null) { var projects = obj.ValueAsJsonObject("Projects"); var projectContexts = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase); foreach (var key in projects.Keys) { projectContexts[key] = projects.ValueAsInt(key); } ProjectsInitialized(projectContexts); } break; case "ProjectChanged": //{ // "MessageType": "ProjectChanged", // "ContextId": id, //} if (ProjectChanged != null) { int id = obj.ValueAsInt("ContextId"); ProjectChanged(id); } break; case "Error": //{ // "MessageType": "Error", // "ContextId": id, // "Payload": { // "Message": "", // "Path": "", // "Line": 0, // "Column": 1 // } //} if (Error != null) { var id = obj.ValueAsInt("ContextId"); var message = obj.ValueAsJsonObject("Payload"). ValueAsString("Message"); Error(id, message); } break; default: break; } } } catch (Exception ex) { Logger.TraceError("[{0}]: Exception occurred: {1}", GetType().Name, ex); Closed(); return; } }
/// <summary> /// Returns a list of members (Athletes) in a Club. The response includes the Id and Name of each Athlete whose a member of the Club. /// </summary> /// <param name="id">Required. The Id of the Club.</param> /// <returns>Club and list of its members.</returns> public ClubMembers Members(int id) { var response = Client.Download(string.Format("clubs/{0}/members", id)); return(JsonDeserializer.Deserialize <ClubMembers>(response)); }
async Task SendTestResults(bool isAdd, int runId, ICollection <IDictionary <string, object> > body) { if (body.Count == 0) { return; } // For adds, we need to remove the unique id's and correlate to the responses // For update we need to look up the reponses List <ITest> added = null; if (isAdd) { added = new List <ITest>(body.Count); // Add them to the list so we can ref by ordinal on the response foreach (var item in body) { var uniqueId = (ITest)item[UNIQUEIDKEY]; item.Remove(UNIQUEIDKEY); added.Add(uniqueId); } } else { // The values should be in the map foreach (var item in body) { var test = (ITest)item[UNIQUEIDKEY]; item.Remove(UNIQUEIDKEY); // lookup and add var testId = testToTestIdMap[test]; item.Add("id", testId); } } var method = isAdd ? HttpMethod.Post : PatchHttpMethod; var bodyString = ToJson(body); var url = $"{baseUri}/{runId}/results?api-version=3.0-preview"; try { var bodyBytes = Encoding.UTF8.GetBytes(bodyString); var request = new HttpRequestMessage(method, url) { Content = new ByteArrayContent(bodyBytes) }; request.Content.Headers.ContentType = JsonMediaType; request.Headers.Accept.Add(JsonMediaType); using (var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(30))) { var response = await client.SendAsync(request, tcs.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { logger.LogWarning($"When sending '{method} {url}', received status code '{response.StatusCode}'; request body:\n{bodyString}"); previousErrors = true; } if (isAdd) { var respString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); using (var sr = new StringReader(respString)) { var resp = JsonDeserializer.Deserialize(sr) as JsonObject; var testCases = resp.Value("value") as JsonArray; for (var i = 0; i < testCases.Length; ++i) { var testCase = testCases[i] as JsonObject; var id = testCase.ValueAsInt("id"); // Match the test by ordinal var test = added[i]; testToTestIdMap[test] = id; } } } } } catch (Exception ex) { logger.LogError($"When sending '{method} {url}' with body '{bodyString}', exception was thrown: {ex.Message}"); throw; } }
public CustomFieldSupportedDeserialiser() { DefaultDeserialiser = new JsonDeserializer(); }
/// <summary> /// Processes messages recieved from client. /// If message is a sucessful login, server will return product list. /// If message is /// </summary> /// <param name="s"></param> /// <param name="msgType"></param> /// <returns></returns> public string ProcessMessage(string s, string msgType) { string[] splitter = s.Split('#'); string msg = splitter[0]; string ID = splitter[1]; // Retrieve message from client serializedmsg = msg; //Check to see what type of message it is JsonDeserializer rm = new JsonDeserializer(); string returnmsg = ""; switch (msgType) { case "Login": LoginMessage login = rm.DeserializeLoginMessage(serializedmsg); string valid = c.ValidateLogin(login.userName, login.password); switch (valid) { case "Good": { AddUser(ID, login.userName); //Serialize list of product returnmsg = "Login#" + JsonConvert.SerializeObject(p.GetProduct); break; } case "New": case "Bad": { returnmsg = "Failed#failed"; break; } default: break; } //Add to the list if it is new user if (valid == "New") { c.Add(login.userName, login.password); } break; case "Bid": BidMessage bid = rm.DeserializeBidMessage(msg); bool validProduct = ValidateBid(bid.productName, bid.bidAmount); if (validProduct) { returnmsg = "Bid#" + JsonConvert.SerializeObject(p.GetProduct); AddTopBid(bid.productName, ID); } else { returnmsg = "BadBid#" + JsonConvert.SerializeObject(p.GetProduct); } break; default: break; } return(returnmsg); }
public override bool SendMailBatch(MailInformation mail, IEnumerable <JobWorkItem> recipients, bool onlyTestDontSendMail) { MailgunSettings settings = GetSettings(); // ReSharper disable PossibleMultipleEnumeration if (recipients == null || recipients.Count() == 0) { throw new ArgumentException("No workitems", "recipients"); } if (recipients.Count() > 1000) { throw new ArgumentOutOfRangeException("recipients", "Mailgun supports maximum 1000 recipients per batch send."); } RestClient client = new RestClient { BaseUrl = settings.ApiBaseUrl, Authenticator = new HttpBasicAuthenticator("api", settings.ApiKey) }; if (string.IsNullOrEmpty(settings.ProxyAddress) == false) { client.Proxy = new WebProxy(settings.ProxyAddress, settings.ProxyPort); // Makes it easy to debug as Fiddler will show us the requests } RestRequest request = new RestRequest(); request.AlwaysMultipartFormData = true; request.AddParameter("domain", settings.Domain, ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", mail.From); request.AddParameter("subject", mail.Subject); request.AddParameter("text", mail.BodyText); request.AddParameter("html", mail.BodyHtml); if (mail.EnableTracking) { request.AddParameter("o:tracking", mail.EnableTracking); request.AddParameter("o:tracking-clicks", mail.EnableTracking); request.AddParameter("o:tracking-opens", mail.EnableTracking); } foreach (KeyValuePair <string, object> customProperty in mail.CustomProperties) { request.AddParameter(customProperty.Key, customProperty.Value.ToString()); } // Add custom data about job if (mail.CustomProperties.ContainsKey("v:newsletter-data") == false) { request.AddParameter("v:newsletter-data", string.Format("{{\"id\": \"{0}\", \"page\": \"{1}\" }}", recipients.First().JobId, mail.PageLink.ID)); } // Add all recipients StringBuilder recipVariables = new StringBuilder(); bool first = true; foreach (JobWorkItem recipient in recipients) { request.AddParameter("to", recipient.EmailAddress); if (first == false) { recipVariables.Append(","); } first = false; recipVariables.AppendFormat("\"{0}\" : {{\"id\": \"{1}\" }}", recipient.EmailAddress, recipient.GetHashCode()); } request.AddParameter("recipient-variables", "{" + recipVariables.ToString() + "}"); //if(onlyTestDontSendMail) //{ // request.AddParameter("o:testmode", true); //} request.Method = Method.POST; var response = client.Execute(request); Dictionary <string, string> resultParams = null; try { resultParams = new JsonDeserializer().Deserialize <Dictionary <string, string> >(response); } catch (Exception e) { _log.Warning("Unable to parse Mailgun response.", e); } if (response.StatusCode == HttpStatusCode.OK) { _log.Debug("Mailgun responded with: {0} - {1}", response.StatusCode, response.StatusDescription); if (string.IsNullOrEmpty(response.ErrorMessage) == false) { _log.Error("Response Error: {0}", response.ErrorMessage); } _log.Debug(response.Content); // json looks like: //{ // "message": "Queued. Thank you.", // "id": "<*****@*****.**>" //} // Update all recipients with information if (resultParams != null) { string info = resultParams["id"]; foreach (JobWorkItem recipient in recipients) { recipient.Info = info; } } } else { _log.Debug("Mailgun responded with: {0} - {1}", response.StatusCode, response.StatusDescription); string errorMessage = response.StatusDescription; if (resultParams != null) { errorMessage = resultParams["message"]; } if (string.IsNullOrEmpty(response.ErrorMessage) == false) { _log.Error("Response Error: {0}", response.ErrorMessage); } _log.Debug(response.Content); throw new HttpException((int)response.StatusCode, errorMessage); } return(true); // ReSharper restore PossibleMultipleEnumeration }
/// <summary> /// Json字符串反序列化成T类型 /// </summary> /// <typeparam name="T">反序列化目标类型</typeparam> /// <param name="jsonString">JsonObject类型</param> /// <returns>反序列化目标对象</returns> public static T Deserialize <T>(string jsonString) { JsonDeserializer <T> deserializer = new JsonDeserializer <T>(jsonString); return(deserializer.Deserialize()); }
public List <string> ValidateRecipientList(List <EmailAddress> recipientAddresses, RecipientList blocked) { _log.Debug("Validating {0} emails using block list {1} ({2})", recipientAddresses.Count, blocked.Name, blocked.Id); if (recipientAddresses.Count == 0) { return(new List <string>()); } MailgunSettings settings = GetSettings(); RestClient client = new RestClient { BaseUrl = settings.ApiBaseUrl, Authenticator = new HttpBasicAuthenticator("api", settings.PublicKey) }; if (string.IsNullOrEmpty(settings.ProxyAddress) == false) { client.Proxy = new WebProxy(settings.ProxyAddress, settings.ProxyPort); // Makes it easy to debug as Fiddler will show us the requests } RestRequest request = new RestRequest(); // We're sending a lot of data, which should // be a post, but Mailgun does not allow that // request.Method = Method.POST; request.Resource = "/address/parse"; // Validate strict request.AddParameter("syntax_only", false); string addresses = ""; foreach (EmailAddress emailAddress in recipientAddresses) { addresses += emailAddress.Email + ","; } _log.Debug("Length of address field sent to Mailgun: {0}", addresses.Length); if (addresses.Length > 8000) { throw new ApplicationException("Mailgun only accepts address fields with length of 8000 characters."); } request.AddParameter("addresses", addresses.TrimEnd(',')); var response = client.Execute(request); _log.Debug("Mailgun responded with status: {0} - {1}", (int)response.StatusCode, response.StatusDescription); if (response.StatusCode == HttpStatusCode.OK) { /* * { * "parsed": [ * "Alice <*****@*****.**>", * "*****@*****.**" * ], * "unparseable": [ * "example.com" * ] * } */ Dictionary <string, List <string> > resultParams = null; try { resultParams = new JsonDeserializer().Deserialize <Dictionary <string, List <string> > >(response); } catch (Exception e) { _log.Warning("Unable to parse Mailgun response.", e); } // Update all recipients with information if (resultParams != null) { List <string> invalidAddresses = resultParams["unparseable"]; foreach (string address in invalidAddresses) { EmailAddress emailAddress = recipientAddresses.Find(a => a.Email.Equals(address, StringComparison.InvariantCultureIgnoreCase)); if (emailAddress != null) { emailAddress.Comment = "Mailgun reported address as invalid."; emailAddress.Save(); } EmailAddress blockedAddress = blocked.CreateEmailAddress(address); blockedAddress.Comment = "Mailgun reported address as invalid."; blockedAddress.Save(); } return(invalidAddresses); } } else { // Attempt to log error from Mailgun if (string.IsNullOrEmpty(response.ErrorMessage) == false) { _log.Warning(response.ErrorMessage); } if (string.IsNullOrEmpty(response.Content) == false) { _log.Debug(response.Content); } throw new ApplicationException("Cannot validate email addresses using Mailgun: " + response.ErrorMessage); } return(null); }
public void SendScanPost() { // endpoint: POST /api/v3/releases/{releaseId}/static-scans/start-scan // required parameters: releaseId, assessmentTypeId, technologyStack, languageLevel, fragNo, offset, entitlementId, entitlementFrequencyType // New optional: isRemediationScan* SetEntitlementInformation(); var fi = new FileInfo(_submissionZip); Trace.WriteLine("Beginning upload...."); var endpoint = new StringBuilder(); endpoint.Append(_baseUri.Scheme + "://"); endpoint.Append(_baseUri.Host + "/"); endpoint.Append("api/v3/releases/"); endpoint.Append(_queryParameters.Get("pv")); endpoint.Append("/static-scans/start-scan"); var client = new RestClient(endpoint.ToString()) { Timeout = Globaltimeoutinminutes * 120 }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // Read it in chunks var uploadStatus = ""; IRestResponse response = null; using (var fs = new FileStream(_submissionZip, FileMode.Open)) { byte[] readByteBuffer = new byte[Seglen]; var fragmentNumber = 0; var offset = 0; double bytesSent = 0; double fileSize = fi.Length; var chunkSize = Seglen; try { int bytesRead; while ((bytesRead = fs.Read(readByteBuffer, 0, (int)chunkSize)) > 0) { var uploadProgress = Math.Round(((decimal)bytesSent / (decimal)fileSize) * 100.0M); var sendByteBuffer = new byte[chunkSize]; if (bytesRead < Seglen) { fragmentNumber = -1; Array.Resize(ref sendByteBuffer, bytesRead); Array.Copy(readByteBuffer, sendByteBuffer, sendByteBuffer.Length); response = SendData(client, sendByteBuffer, fragmentNumber, offset); uploadStatus = response.StatusCode.ToString(); break; } Array.Copy(readByteBuffer, sendByteBuffer, sendByteBuffer.Length); response = SendData(client, sendByteBuffer, fragmentNumber++, offset); uploadStatus = response.StatusCode.ToString(); offset += bytesRead; bytesSent += bytesRead; if ((fs.Length - offset) < Seglen) { chunkSize = (fs.Length - offset); } Trace.WriteLine(uploadProgress + "%"); } } catch (Exception ex) { Trace.WriteLine(ex); throw; } finally { // ReSharper disable once ConstantConditionalAccessQualifier fs?.Close(); } if (uploadStatus.Equals("OK")) { Trace.WriteLine("Assessment submission successful."); } else { Trace.WriteLine("Status: " + uploadStatus); if (uploadStatus.Equals("BadRequest")) { var errors = new JsonDeserializer().Deserialize <ErrorResponse>(response); foreach (var e in errors.Errors) { Trace.WriteLine($"Error: {e.Message}"); } } else { Trace.WriteLine("Error submitting to Fortify on Demand."); } Environment.Exit(-1); } } }
public static Dictionary <string, string> DeserializeResponse(this IRestResponse restResponse) { var JSONObj = new JsonDeserializer().Deserialize <Dictionary <string, string> >(restResponse); return(JSONObj); }
/// <summary> /// Returns extended information for a Ride. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <returns>Ride for the specified id with extended information.</returns> public Ride Show(int id) { var response = Client.Download(string.Format("rides/{0}", id)); return(JsonDeserializer.Deserialize <RideWrapper>(response).Ride); }
private DependencyContext Read(TextReader reader) { // { // "runtimeTarget": {...}, // "compilationOptions": {...}, // "targets": {...}, // "libraries": {...}, // "runtimes": {...} // } var root = JsonDeserializer.Deserialize(reader) as JsonObject; if (root == null) { return(null); } var runtime = string.Empty; var framework = string.Empty; var isPortable = true; ReadRuntimeTarget(root.ValueAsJsonObject(DependencyContextStrings.RuntimeTargetPropertyName), out var runtimeTargetName, out var runtimeSignature); var compilationOptions = ReadCompilationOptions(root.ValueAsJsonObject(DependencyContextStrings.CompilationOptionsPropertName)); var targets = ReadTargets(root.ValueAsJsonObject(DependencyContextStrings.TargetsPropertyName)); var libraryStubs = ReadLibraries(root.ValueAsJsonObject(DependencyContextStrings.LibrariesPropertyName)); var runtimeFallbacks = ReadRuntimes(root.ValueAsJsonObject(DependencyContextStrings.RuntimesPropertyName)); if (compilationOptions == null) { compilationOptions = CompilationOptions.Default; } Target runtimeTarget = SelectRuntimeTarget(targets, runtimeTargetName); runtimeTargetName = runtimeTarget?.Name; if (runtimeTargetName != null) { var seperatorIndex = runtimeTargetName.IndexOf(DependencyContextStrings.VersionSeperator); if (seperatorIndex > -1 && seperatorIndex < runtimeTargetName.Length) { runtime = runtimeTargetName.Substring(seperatorIndex + 1); framework = runtimeTargetName.Substring(0, seperatorIndex); isPortable = false; } else { framework = runtimeTargetName; } } Target compileTarget = null; var ridlessTarget = targets.FirstOrDefault(t => !IsRuntimeTarget(t.Name)); if (ridlessTarget != null) { compileTarget = ridlessTarget; if (runtimeTarget == null) { runtimeTarget = compileTarget; framework = ridlessTarget.Name; } } if (runtimeTarget == null) { throw new FormatException("No runtime target found"); } return(new DependencyContext( new TargetInfo(framework, runtime, runtimeSignature, isPortable), compilationOptions, CreateLibraries(compileTarget?.Libraries, false, libraryStubs).Cast <CompilationLibrary>().ToArray(), CreateLibraries(runtimeTarget.Libraries, true, libraryStubs).Cast <RuntimeLibrary>().ToArray(), runtimeFallbacks ?? Enumerable.Empty <RuntimeFallbacks>())); }
/// <summary> /// Returns a list of Efforts on a Ride. The response includes the Id of the Effort, the elapsed time of the Effort, and the Id and Name of the Segment associated with the Effort. /// </summary> /// <param name="id">Required. The Id of the Ride.</param> /// <returns>List of Efforts on the specified Ride</returns> public RideEfforts Efforts(int id) { var response = Client.Download(string.Format("rides/{0}/efforts", id)); return(JsonDeserializer.Deserialize <RideEfforts>(response)); }
public bool Successful(IRestResponse restResponse, out Error error) { error = null; if (restResponse == null) { error = new Error { Code = "RestSharp error", Status = 500, Message = "No response was received.", }; } else if (restResponse.ErrorException != null) { error = new Error { Code = "RestSharp error", Status = 500, Message = restResponse.ErrorException.Message, }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.InternalServerError)) { error = new Error { Code = "Internal Server Error", Status = 500 }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.BadGateway)) { error = new Error { Code = "Bad Gateway", Status = 502 }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.Unauthorized)) { error = new Error { Code = "Unauthorized", Status = 401 }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.Forbidden)) { error = new Error { Code = "Forbidden", Status = 403 }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.NotModified)) { error = new Error { Code = "Not Modified", Status = 304, HelpUrl = "http://developers.box.com/docs/#if-match" }; } else if (restResponse.StatusCode.Equals(HttpStatusCode.Accepted)) { Parameter retryAfter = restResponse.Headers.SingleOrDefault(h => h.Name.Equals("Retry-After", StringComparison.InvariantCultureIgnoreCase)); if (retryAfter != null) { error = new Error { Code = "Download Not Ready", Message = "This file is not yet ready to be downloaded. Please wait and try again.", HelpUrl = "http://developers.box.com/docs/#files-download-a-file", Status = 202, RetryAfter = int.Parse((string)retryAfter.Value) }; } } else if (restResponse.ContentType.Equals(JsonMimeType)) { var jsonDeserializer = new JsonDeserializer(); if (restResponse.Content.Contains(@"""type"":""error""")) { error = TryGetSingleError(restResponse, jsonDeserializer) ?? TryGetFirstErrorFromCollection(restResponse, jsonDeserializer); } else if (restResponse.Content.Contains(@"""error"":")) { var authError = jsonDeserializer.Deserialize <AuthError>(restResponse); error = new Error { Code = authError.Error, Status = 400, Message = authError.ErrorDescription, Type = ResourceType.Error }; } } return(error == null); }
public void DeserializeSimpleObject() { // Do not format the following 12 lines. The position of every charactor position in the // JSON sample is referenced in following test. var content = @" { ""key1"": ""value1"", ""key2"": 99, ""key3"": true, ""key4"": [""str1"", ""str2"", ""str3""], ""key5"": { ""subkey1"": ""subvalue1"", ""subkey2"": [1, 2] }, ""key6"": null }"; using (var reader = GetReader(content)) { var raw = JsonDeserializer.Deserialize(reader); Assert.NotNull(raw); var jobject = raw as JsonObject; Assert.NotNull(jobject); Assert.Equal("value1", jobject.ValueAsString("key1")); Assert.Equal(99, FromJsonNumberToInt(jobject.Value("key2"))); Assert.Equal(true, jobject.ValueAsBoolean("key3")); Assert.Equal(2, jobject.Line); Assert.Equal(13, jobject.Column); var list = jobject.ValueAsStringArray("key4"); Assert.NotNull(list); Assert.Equal(3, list.Length); Assert.Equal("str1", list[0]); Assert.Equal("str2", list[1]); Assert.Equal("str3", list[2]); var rawList = jobject.Value("key4") as JsonArray; Assert.NotNull(rawList); Assert.NotNull(rawList); Assert.Equal(6, rawList.Line); Assert.Equal(25, rawList.Column); var subObject = jobject.ValueAsJsonObject("key5"); Assert.NotNull(subObject); Assert.Equal("subvalue1", subObject.ValueAsString("subkey1")); var subArray = subObject.Value("subkey2") as JsonArray; Assert.NotNull(subArray); Assert.Equal(2, subArray.Length); Assert.Equal(1, FromJsonNumberToInt(subArray[0])); Assert.Equal(2, FromJsonNumberToInt(subArray[1])); Assert.Equal(9, subArray.Line); Assert.Equal(32, subArray.Column); var nullValue = jobject.Value("key6"); Assert.NotNull(nullValue); Assert.True(nullValue is JsonNull); } }
public bool exp_orders(int StartID, ref ws_rec_orders OrdersData) { try { var client = new RestClient(_OrdersUrl); if (!String.IsNullOrEmpty(this._ProxyUser)) { client.Proxy = new WebProxy(_ProxyHost, _ProxyPort); client.Proxy.Credentials = new NetworkCredential(_ProxyUser, _ProxyPassword); } // Estraggo gli ordini (50 alla volta) // --------------------------------------------------------------- // http://test.giessedati.it/appmanager/api/v1/progetti/iorder.test2/exportPaginazione/ordini?authKey=E24EFDA3-9878-42D8-90FE-C00F847FE434&format=json&lastID=1&count=0&limit=50 var request = new RestRequest(Method.GET); request.AddParameter("authKey", this.AuthKeyAM); request.AddParameter("format", "json"); request.AddParameter("offset", 0); request.AddParameter("limit", 30); // quanti ne elaboro al massimo ? request.AddParameter("count", 0); // count = 0 ritorna i dati. Se = 1 ritorna solo alcune statistiche request.AddParameter("lastID", StartID); // request.RequestFormat = DataFormat.Json; // request.JsonSerializer = new RestSharpJsonNetSerializer(); //Console.WriteLine("1" + _OrdersUrl + "-" + this.AuthKeyAM); //request.AddParameter("lastDateImport", ""); // var response = client.Execute<ws_rec_orders>(request); var response = client.Execute(request); if (response.ResponseStatus != ResponseStatus.Completed) { throw new Exception("ResponseStatus: " + response.ErrorMessage); } if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("StatusCode: " + response.StatusCode + ", Content: " + response.Content); } if (response.ErrorException != null) { throw new Exception("Error retrieving response 2. Check inner details for more info."); } // La serializzazione di RestSharp scazza le date con il .net framework 2.0. // Faccio la deserializzazione in 2 modi diversi. // Nel primo caso uso JsonConvert della vecchia libreria RestShar compilata col framework 2.0 // (in cui ho rinominato i namespace per un conflitto con l'installazione su Business) // Nel secondo caso uso il deserializzatore di RestSharp #if NET20 var myDeserializedData = JsonConvert.DeserializeObject <ws_rec_orders>(response.Content); #endif #if NET35 || NET40 JsonDeserializer deserial = new JsonDeserializer(); var myDeserializedData = deserial.Deserialize <ws_rec_orders>(response); #endif _ResponseURI = response.ResponseUri.ToString(); if (myDeserializedData.testate.Count == 0) { _InfoMessage = "Data not found"; return(false); } OrdersData = myDeserializedData; } catch (Exception ex) { //Console.WriteLine(ex.Message); //Console.WriteLine(_InfoMessage); throw new Exception("exp_orders: Uri:" + _ResponseURI + ", Message:" + ex.Message, ex); } return(true); }
private Error TryGetFirstErrorFromCollection(IRestResponse restResponse, JsonDeserializer jsonDeserializer) { var deserialized = jsonDeserializer.Deserialize <ErrorCollection>(restResponse); return((deserialized.Entries != null) ? deserialized.Entries.First() : null); }
public override void JsonDehydrate(JsonDeserializer jsonDeserializer) { base.JsonDehydrate(jsonDeserializer); this.neuraliumIntermediaryElectionResultsimplementation.JsonDehydrate(jsonDeserializer); }
public AccountRepository(string apiKey, JsonDeserializer deserializer, JsonRetriever retriever) : base(apiKey, deserializer, retriever) { }
public CharacterRepository(string apiKey, JsonDeserializer deserializer, JsonRetriever retriever) : base(apiKey, deserializer, retriever) { }
private static Error TryGetSingleError(IRestResponse restResponse, JsonDeserializer jsonDeserializer) { var deserialized = jsonDeserializer.Deserialize <Error>(restResponse); return(deserialized.Type.Equals(ResourceType.Error) ? deserialized : null); }
public OccupancyAutomationTests() { _client = new RestClient("http://localhost:5000/api"); _deserializer = new JsonDeserializer(); }
/// <summary> /// Returns extended information for a Club. /// </summary> /// <param name="id">Required. The Id of the Club.</param> /// <returns>Club for the specified id with extended information.</returns> public Club Show(int id) { var response = Client.Download(string.Format("clubs/{0}", id)); return(JsonDeserializer.Deserialize <ClubWrapper>(response).Club); }
public void InitializeTest() { this.provider = new RemoteJsonProvider(); this.deserializer = new JsonDeserializer(); }
public MonitoringTest() { _client = new RestClient("http://localhost:5000/api"); _deserializer = new JsonDeserializer(); }
public static void Main(string[] args) { //string url = "http://localhost:8080/"; //string url = "https://api.github.com/orgs/dotnet/repos"; string url = "https://api.github.com"; var client = new RestClient(url); //var request = new RestRequest("orgs/dotnet", Method.GET); //var request = new RestRequest(Method.GET); var request = new RestRequest("/orgs/dotnet/repos", Method.GET); //var request = new RestRequest("/orgs/dotnet", Method.GET); // //var request = new RestRequest("/tokenlifetime", Method.GET); //var request = new RestRequest("/", Method.GET); //var request = new RestRequest("item/125", Method.POST); //var request = new RestRequest("item/125", Method.PUT); //var request = new RestRequest("item/125", Method.DELETE); //var request = new RestRequest("/users", Method.GET); // //var request = new RestRequest("/", Method.GET); //var request = new RestRequest("/login", Method.POST); //request.AddParameter("name", "admin"); //request.AddParameter("password", "qwerty"); // //var request = new RestRequest("/tokenlifetime", Method.PUT); //request.AddParameter("token", "S3J851OE19VVZA44ZZRXI3PCPP0ONJLX"); //request.AddParameter("time", "800000"); // //request.RequestFormat = DataFormat.Json; // Add HTTP Headers //request.AddHeader("cache-control", "no-cache"); // IRestResponse response = client.Execute(request); //Thread.Sleep(5000); //var response = client.ExecuteTaskAsync<string>(request); var content = response.Content; Console.WriteLine("content: " + content); // JsonDeserializer deserial = new JsonDeserializer(); //var obj = deserial.Deserialize<RestResult>(response); //var obj = JsonConvert.DeserializeObject<RestResult2>(response.Content); var obj = JsonConvert.DeserializeObject <List <RestResult3> >(response.Content); //var obj = JsonConvert.DeserializeObject<RestResult4>(response.Content); //Console.WriteLine("Deserialize content: " + obj); Console.WriteLine("Deserialize content: " + obj[0]); foreach (RestResult3 current in obj) { Console.WriteLine("Deserialize content: " + current); } // //IRestResponse<RestResult> response2 = client.Execute<RestResult>(request); //Console.WriteLine("content: " + response2.Data.content); // // // Async Support //int i = 0; //Console.WriteLine("Start"); //var asyncHandle = client.ExecuteAsync(request, response => //{ // i = 1; // Console.Write("content: "); // Console.WriteLine(response.Content); // i = 2; //}); //Console.WriteLine("i= " + i); // // Async with Deserialization //var asyncHandle = client.ExecuteAsync<RestResult>(request, response => //{ // Console.Write("content: "); // Console.WriteLine(response.Data.content); //}); // // abort the request on demand //asyncHandle.Abort(); }
public Project ReadProject(Stream stream, string projectName, string projectPath, ICollection <DiagnosticMessage> diagnostics) { var project = new Project(); var reader = new StreamReader(stream); var rawProject = JsonDeserializer.Deserialize(reader) as JsonObject; if (rawProject == null) { throw FileFormatException.Create( "The JSON file can't be deserialized to a JSON object.", projectPath); } // Meta-data properties project.Name = rawProject.ValueAsString("name") ?? projectName; project.ProjectFilePath = Path.GetFullPath(projectPath); var version = rawProject.Value("version") as JsonString; if (version == null) { project.Version = new NuGetVersion("1.0.0"); } else { try { var buildVersion = Environment.GetEnvironmentVariable("DOTNET_BUILD_VERSION"); project.Version = SpecifySnapshot(version, buildVersion); } catch (Exception ex) { throw FileFormatException.Create(ex, version, project.ProjectFilePath); } } var fileVersion = Environment.GetEnvironmentVariable("DOTNET_ASSEMBLY_FILE_VERSION"); if (string.IsNullOrWhiteSpace(fileVersion)) { project.AssemblyFileVersion = project.Version.Version; } else { try { var simpleVersion = project.Version.Version; project.AssemblyFileVersion = new Version(simpleVersion.Major, simpleVersion.Minor, simpleVersion.Build, int.Parse(fileVersion)); } catch (FormatException ex) { throw new FormatException("The assembly file version is invalid: " + fileVersion, ex); } } project.Description = rawProject.ValueAsString("description"); project.Summary = rawProject.ValueAsString("summary"); project.Copyright = rawProject.ValueAsString("copyright"); project.Title = rawProject.ValueAsString("title"); project.EntryPoint = rawProject.ValueAsString("entryPoint"); project.ProjectUrl = rawProject.ValueAsString("projectUrl"); project.LicenseUrl = rawProject.ValueAsString("licenseUrl"); project.IconUrl = rawProject.ValueAsString("iconUrl"); project.CompilerName = rawProject.ValueAsString("compilerName"); project.Authors = rawProject.ValueAsStringArray("authors") ?? Array.Empty <string>(); project.Owners = rawProject.ValueAsStringArray("owners") ?? Array.Empty <string>(); project.Tags = rawProject.ValueAsStringArray("tags") ?? Array.Empty <string>(); project.Language = rawProject.ValueAsString("language"); project.ReleaseNotes = rawProject.ValueAsString("releaseNotes"); project.RequireLicenseAcceptance = rawProject.ValueAsBoolean("requireLicenseAcceptance", defaultValue: false); // REVIEW: Move this to the dependencies node? project.EmbedInteropTypes = rawProject.ValueAsBoolean("embedInteropTypes", defaultValue: false); project.Dependencies = new List <LibraryRange>(); // Project files project.Files = new ProjectFilesCollection(rawProject, project.ProjectDirectory, project.ProjectFilePath); var commands = rawProject.Value("commands") as JsonObject; if (commands != null) { foreach (var key in commands.Keys) { var value = commands.ValueAsString(key); if (value != null) { project.Commands[key] = value; } } } var scripts = rawProject.Value("scripts") as JsonObject; if (scripts != null) { foreach (var key in scripts.Keys) { var stringValue = scripts.ValueAsString(key); if (stringValue != null) { project.Scripts[key] = new string[] { stringValue }; continue; } var arrayValue = scripts.ValueAsStringArray(key); if (arrayValue != null) { project.Scripts[key] = arrayValue; continue; } throw FileFormatException.Create( string.Format("The value of a script in {0} can only be a string or an array of strings", Project.FileName), scripts.Value(key), project.ProjectFilePath); } } BuildTargetFrameworksAndConfigurations(project, rawProject, diagnostics); PopulateDependencies( project.ProjectFilePath, project.Dependencies, rawProject, "dependencies", isGacOrFrameworkReference: false); return(project); }
public Dictionary <string, string> SendWithAccessToken(String uri, String httpMethod, String accessToken, object data = null, Dictionary <string, string> headers = null, String signedParameters = null) { try { string url = getUrl(environment); url = String.Concat(url, uri); RestClient client = new RestClient(url); client.IgnoreResponseStatusCode = true; IRestResponse response = null; Config authConfig = new Config(httpMethod, url, this.clientId, this.clientSecret, accessToken, signedParameters); HttpMethod httpMethodObj = (httpMethod == null || httpMethod.Equals("")) ? HttpMethod.Get : new HttpMethod(httpMethod); var paymentRequests = new RestRequest(url, httpMethodObj); paymentRequests.AddHeader(Constants.Contenttype, "application/json"); paymentRequests.AddHeader("Signature", authConfig.Signature); paymentRequests.AddHeader("SignatureMethod", "SHA1"); paymentRequests.AddHeader("Timestamp", authConfig.TimeStamp); paymentRequests.AddHeader("Nonce", authConfig.Nonce); paymentRequests.AddHeader("Authorization", authConfig.Authorization); if (headers != null && headers.Count() > 0) { foreach (KeyValuePair <string, string> entry in headers) { paymentRequests.AddHeader(entry.Key, entry.Value); } } if (data != null) { paymentRequests.AddJsonBody(data); } ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; JsonDeserializer deserial = new JsonDeserializer(); //try //{ response = client.Execute(paymentRequests).Result; /* * } * catch (Exception ex) * { * Console.WriteLine(ex.StackTrace.ToString()); * throw ex; * } */ HttpStatusCode httpStatusCode = response.StatusCode; int numericStatusCode = (int)httpStatusCode; Dictionary <string, string> responseObject = new Dictionary <string, string>(); responseObject.Add(HTTP_CODE, numericStatusCode.ToString()); responseObject.Add(HTTP_RESPONSE, System.Text.Encoding.UTF8.GetString(response.RawBytes)); return(responseObject); } catch (Exception ex) { throw ex; } }
/// <summary> /// Get the objetc response from json response /// </summary> /// <returns></returns> public static T GetObjectResponse(IRestResponse response) { JsonDeserializer deserial = new JsonDeserializer(); return(deserial.Deserialize <T>(response)); }