private static List <SyntexModelPublicationResult> ParseModelPublishResponse(ApiCallResponse response) { var root = JsonDocument.Parse(response.Json).RootElement.GetProperty("d").GetProperty("Details").GetProperty("results"); var modelPublicationResults = DeserializeModelPublishResult(root.ToString()); return(modelPublicationResults); }
/// <summary> /// Adds or updates the entity on the server. /// </summary> /// <param name="entity">The entity to save</param> /// <returns></returns> public ApiCallResponse Update(IMutableEntity entity) { var pe = entity as ParaEntity; Folder folder = null; ApiCallResponse reply = null; if (pe == null) { folder = entity as Folder; if (folder == null) { throw new ArgumentException("You can only call this function on a Folder-derived or ParaEntity-derived object.", "entity"); } reply = ApiCallFactory.ObjectCreateUpdate(Credentials, folder.GetType().Name, XmlGenerator.GenerateXml(folder), folder.Id); } else { if (pe.Id == 0) { throw new ArgumentException("The update operation requires an existing object ID. Populate the entity ID to perform an update."); } reply = ApiCallFactory.ObjectCreateUpdate(Credentials, pe.GetType().Name, XmlGenerator.GenerateXml(pe), pe.Id); } return(reply); }
internal static IEnumerable <IChange> Deserialize(ApiCallResponse response, IDataModelParent parent, PnPContext context) { if (string.IsNullOrEmpty(response.Json)) { #pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(response.Json)); #pragma warning restore CA2208 // Instantiate argument exceptions correctly } var result = new List <IChange>(); var document = JsonSerializer.Deserialize <JsonElement>(response.Json); if (document.TryGetProperty("d", out JsonElement dRoot) && dRoot.TryGetProperty("results", out JsonElement dataRows)) { // No data returned, stop processing if (dataRows.GetArrayLength() == 0) { return(result); } foreach (var row in dataRows.EnumerateArray()) { var pnpObject = GetConcreteInstance(row); if (pnpObject != null) { ProcessChangeElement(pnpObject, parent, context, row, response.BatchRequestId); result.Add(pnpObject as IChange); } } } return(result); }
public static Tuple <T, ApiCallResponse> getData <T>(Response rawResponse) { ApiCallResponse apiCallResponse = new ApiCallResponse(rawResponse); T parsedData = default(T); if (apiCallResponse.success) { Newtonsoft.Json.Linq.JObject responseJson = Newtonsoft.Json.Linq.JObject.Parse(rawResponse.Content); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Error += delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) { throw args.ErrorContext.Error; }; if (responseJson != null) { try { apiCallResponse.meta = JsonConvert.DeserializeObject <Model.Meta>(responseJson["meta"].ToString(), settings); parsedData = JsonConvert.DeserializeObject <T>(responseJson["data"].ToString(), settings); } catch (Exception exp) { apiCallResponse.success = false; apiCallResponse.errorMessage = exp.Message; apiCallResponse.errorDescription = exp.StackTrace; } } } return(new Tuple <T, ApiCallResponse>(parsedData, apiCallResponse));; }
/// <summary> /// /// </summary> /// <param name="pagedData"></param> protected PagedData(PagedData pagedData) { TotalItems = pagedData.TotalItems; ResultsReturned = pagedData.ResultsReturned; PageSize = pagedData.PageSize; PageNumber = pagedData.PageNumber; ApiCallResponse = new ApiCallResponse(pagedData.ApiCallResponse); }
/// <summary> /// Throws exception in case of non successful HTTP status code. /// </summary> /// <param name="apiResponse"></param> private void EnsureSuccessfullApiResponse(ApiCallResponse apiResponse) { var unsuccessfulResponse = false == apiResponse.StatusCode.IsSuccessStatusCode(); if (unsuccessfulResponse) { throw new ApiCallException($"Api returned status code {(int)apiResponse.StatusCode}: {apiResponse.StringContent}"); } }
/// <summary> /// The call, with passing a binary file. /// </summary> static ApiCallResponse ApiMakeTheCall(string callurl, ParaEnums.ApiCallHttpMethod httpMethod, Attachment att) { const string boundary = "--ParaBoundary"; const string lineBreak = "\r\n"; var contentDisposition = String.Format("Content-Disposition: {0}; name=\"{1}\"; filename=\"{1}\"", att.ContentType.MediaType, att.ContentType.Name); var ac = new ApiCallResponse(); var uriAddress = new Uri(callurl); var req = WebRequest.Create(uriAddress) as HttpWebRequest; req.Method = ApiHttpPostProvider(httpMethod); req.KeepAlive = false; ac.HttpCallMethod = req.Method; req.AllowWriteStreamBuffering = true; req.ReadWriteTimeout = 10 * 60 * 1000; req.Timeout = -1; //Provide a way for the user to configure the connection -> proxy, timeout, etc ApiRequestSettings.GlobalPreRequest(req); req.ContentType = att.ContentType.MediaType + "; boundary:" + boundary;; var filebytes = new byte[Convert.ToInt32(att.ContentStream.Length - 1) + 1]; att.ContentStream.Read(filebytes, 0, filebytes.Length); var sb = new StringBuilder(); sb.AppendLine(boundary); sb.AppendLine(contentDisposition); sb.AppendLine("Content-Type: " + att.ContentType.MediaType); sb.AppendLine(""); string header = sb.ToString(); string endboundary = lineBreak + boundary + "--"; byte[] footerBytes = Encoding.ASCII.GetBytes(endboundary); byte[] headBytes = Encoding.ASCII.GetBytes(header); req.ContentLength = headBytes.Length + filebytes.Length + footerBytes.Length; var reqStreamTest = req.GetRequestStream(); // String to Byte Array var totalRequest = new byte[headBytes.Length + filebytes.Length + footerBytes.Length]; headBytes.CopyTo(totalRequest, 0); filebytes.CopyTo(totalRequest, headBytes.Length); footerBytes.CopyTo(totalRequest, headBytes.Length + filebytes.Length); reqStreamTest.Write(totalRequest, 0, totalRequest.Length); reqStreamTest.Close(); ac.HasException = false; ac.CalledUrl = callurl; return(ApiHttpRequestProcessor(ac, req)); }
protected async Task <IPersonProperties> ParsePersonPropertiesResultAsync(ApiCallResponse response) { var results = new List <IPersonProperties>(); var json = JsonSerializer.Deserialize <JsonElement>(response.Json); var entityInfo = EntityManager.Instance.GetStaticClassInfo(typeof(PersonProperties)); var prop = new PersonProperties(); await JsonMappingHelper.FromJson(prop, entityInfo, new ApiResponse(new ApiCall(String.Empty, ApiType.SPORest), json, Guid.Empty)).ConfigureAwait(false); return(prop); }
public static T ThrowIfErrorResponse <T>(this ApiCallResponse <T> response) where T : ApiResponse { if (response == null) { throw new ArgumentNullException(nameof(response)); } if (!(response.IsSuccessful && response.Data.Success)) { throw new ApiCallResponseException <T>(response); } return(response.Data); }
private static ISyntexModelPublicationResult ProcessModelPublishResponse(ApiCallResponse response) { if (!string.IsNullOrEmpty(response.Json)) { List <SyntexModelPublicationResult> modelPublicationResults = ParseModelPublishResponse(response.Json); var modelPublicationResult = modelPublicationResults.FirstOrDefault(); if (modelPublicationResult is ISyntexModelPublicationResult syntexModelPublicationResult) { return(syntexModelPublicationResult); } } return(null); }
void backgroundWorkerPersonalStream_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (e != null) { switch (e.ProgressPercentage) { case 50: ApnItem item = e.UserState as ApnItem; if (item != null) { PersonalStream.Add(item); if (showNotifications) { AppController.Current.sendNotification("App.net " + username + " personal stream", item.AuthorName, item.Text, item.Avatar, item); } } break; case 99: ApiCallResponse apiCallResponse = e.UserState as ApiCallResponse; streamMarkerMyStreamUpdateComplete = true; if (apiCallResponse != null) { if (apiCallResponse.meta != null) { if (apiCallResponse.meta.marker != null) { storeMarkerIdMyStream = apiCallResponse.meta.marker.id; storeMarkerVersionMyStream = apiCallResponse.meta.marker.version; } } } if (PersonalStream.Count > 0) { InitialUpdateForPersonalStream = true; } streamMarkerMyStreamUpdateComplete = true; break; } } }
/// <summary> /// The true call is being made by this method. /// </summary> static ApiCallResponse ApiMakeTheCall(string callurl, ParaEnums.ApiCallHttpMethod httpMethod, XmlDocument xmlPosted) { var ac = new ApiCallResponse(); var uriAddress = new Uri(callurl); var req = WebRequest.Create(uriAddress) as HttpWebRequest; req.Method = ApiHttpPostProvider(httpMethod); ac.HttpCallMethod = req.Method; req.KeepAlive = false; //2 minutes request timeout req.Timeout = 120 * 1000; if (xmlPosted != null) { req.ContentType = "application/x-www-form-urlencoded"; // Create a byte array of the data we want to send var bytedata = Encoding.UTF8.GetBytes(xmlPosted.OuterXml); // Set the content length in the request headers req.ContentLength = bytedata.Length; //Provide a way for the user to configure the connection -> proxy, timeout, etc ApiRequestSettings.GlobalPreRequest(req); // Write data using (Stream postStream = req.GetRequestStream()) { postStream.Write(bytedata, 0, bytedata.Length); } ac.XmlSent = xmlPosted; } else { ac.XmlSent = null; } ac.HasException = false; ac.CalledUrl = callurl; return(ApiHttpRequestProcessor(ac, req)); }
private static ApiCallResponse ApiMakeTheCall(string apiCallUrl, ParaEnums.ApiCallHttpMethod httpMethod) { var ac = new ApiCallResponse(); var uriAddress = new Uri(apiCallUrl); var req = WebRequest.Create(uriAddress) as HttpWebRequest; req.Method = ApiHttpPostProvider(httpMethod); ac.HttpCallMethod = req.Method; req.KeepAlive = false; //2 minutes request timeout req.Timeout = 120 * 1000; //Provide a way for the user to configure the connection -> proxy, timeout, etc ApiRequestSettings.GlobalPreRequest(req); ac.XmlSent = null; ac.HasException = false; ac.CalledUrl = apiCallUrl; return(ApiHttpRequestProcessor(ac, req)); }
public IActionResult Handle([FromQuery] string pairingId, [FromQuery][JsonConverter(typeof(StringEnumConverter))] HandshakeResourceType resource, [FromBody] string data) { (string, PairingSession)pairingSession; switch (resource) { case HandshakeResourceType.None: return(BadRequest("no resource given")); case HandshakeResourceType.ServerHello: pairingSession = IsValidPairingSession(pairingId); if (pairingSession.Item2 == null) { pairingSession.Item1 = "OK"; pairingSession.Item2 = new PairingSession(pairingId); _sessions.Add(pairingSession.Item2); } if (pairingSession.Item2.Step != HandshakeResourceType.None) { return(BadRequest("the pairing session has not reached a valid state to do that")); } if (pairingSession.Item1 == "OK") { var returnData = pairingSession.Item2.GenerateServerHello(data); var apiCallResponse = new ApiCallResponse(ApiCallMethod.POST, Constants.Step1Url, JsonConvert.SerializeObject(returnData)); return(Ok(apiCallResponse)); } else { return(BadRequest(pairingSession.Item1)); } case HandshakeResourceType.ClientHello: pairingSession = IsValidPairingSession(pairingId, HandshakeResourceType.ClientHello); if (pairingSession.Item1 == "OK") { var returnAckData = pairingSession.Item2.ParseClientHello(data); return(Accepted(returnAckData)); } else { return(BadRequest(pairingSession.Item1)); } case HandshakeResourceType.ServerAck: pairingSession = IsValidPairingSession(pairingId, HandshakeResourceType.ServerAck); if (pairingSession.Item1 == "OK") { var ackData = pairingSession.Item2.GenerateServerAck(); var ackCallResponse = new ApiCallResponse(ApiCallMethod.POST, Constants.Step2Url, JsonConvert.SerializeObject(ackData)); return(Ok(ackCallResponse)); } else { return(BadRequest(pairingSession.Item1)); } case HandshakeResourceType.ClientAck: pairingSession = IsValidPairingSession(pairingId, HandshakeResourceType.ClientAck); if (pairingSession.Item1 == "OK") { var returnAckData = pairingSession.Item2.ParseClientAck(data); return(Accepted(returnAckData)); } else { return(BadRequest(pairingSession.Item1)); } case HandshakeResourceType.Session: pairingSession = IsValidPairingSession(pairingId, HandshakeResourceType.Session); if (pairingSession.Item1 == "OK") { var returnSessionData = pairingSession.Item2.GetKey(); return(Accepted(new KeyWrapper(Convert.ToBase64String(returnSessionData)))); } else { return(BadRequest(pairingSession.Item1)); } default: return(BadRequest("no resource given")); } }
public static ItemsPage <DynamoItemListResponse> AsPage(this ApiCallResponse <DynamoItemListResponse> response, FluentClient client) { return(AsPage(response, client.LowLevelClient)); }
public static ItemsPage <DynamoItemListResponse> AsPage(this ApiCallResponse <DynamoItemListResponse> response, Client client) { return(new ItemsPage <DynamoItemListResponse>(client, response)); }
public CallbackHandler() { this.handler.ServiceIdentifierKey = SI_KEY; this.handler.Subscribe(delegate(Com.Mobicage.Rogerthat.Messaging.FlowMemberResultRequest request) { using (SqlCeConnection db = new SqlCeConnection(DB_CONNECTION_STRING)) { db.Open(); if (request.Tag == MeetingRoomBooking.NEW_MEETING) return MeetingRoomBooking.BookMeetingRoom(db, request); return null; } }); this.handler.Subscribe(delegate(Com.Mobicage.Rogerthat.Friend.InReachRequest request) { using (SqlCeConnection db = new SqlCeConnection(DB_CONNECTION_STRING)) { db.Open(); MeetingRoomBooking.UserInReach(db, request.UserDetails, request.Beacon, request.Proximity); return null; } }); this.handler.Subscribe(delegate(ApiCallRequest request) { switch (request.Method) { case MeetingRoomBooking.GET_SCHEDULE: using (SqlCeConnection db = new SqlCeConnection(DB_CONNECTION_STRING)) { db.Open(); ApiCallResponse result = new ApiCallResponse(); result.Result = MeetingRoomBooking.GetSchedule(db); result.Error = null; return result; } case MeetingRoomBooking.CANCEL_BOOKING: using (SqlCeConnection db = new SqlCeConnection(DB_CONNECTION_STRING)) { db.Open(); var parameters = new { meeting_room_booking_id = 0L }; MeetingRoomBooking.Cancel(db, JsonConvert.DeserializeAnonymousType(request.Params, parameters).meeting_room_booking_id); ApiCallResponse result = new ApiCallResponse(); result.Result = null; result.Error = null; return result; } case MeetingRoomBooking.WARN_ME_WHEN_PEOPLE_ARRIVE: using (SqlCeConnection db = new SqlCeConnection(DB_CONNECTION_STRING)) { db.Open(); var parameters = new { meeting_room_booking_id = 0L }; MeetingRoomBooking.WarnMeWhenPeopleArrive(db, JsonConvert.DeserializeAnonymousType(request.Params, parameters).meeting_room_booking_id, request.UserDetails.Email); ApiCallResponse result = new ApiCallResponse(); result.Result = null; result.Error = null; return result; } default: return null; } }); }
private static List <ISyntexModelPublicationResult> ProcessModelPublishResponseMultiple(ApiCallResponse response) { if (!string.IsNullOrEmpty(response.Json)) { return(ParseModelPublishResponse(response.Json).Cast <ISyntexModelPublicationResult>().ToList()); } return(null); }
public ApiCallResponseException(ApiCallResponse <T> response) : base(string.IsNullOrEmpty(response.ErrorMessage) ? response.Data.Error : response.ErrorMessage) { Response = response; }
/// <summary> /// Performs the http web request for all ApiMakeCall methods. /// </summary> /// <param name="ac"> /// Api Call response, this object is partially filled in the ApiMakeCall methods, this method will just be adding /// certain data to it and return it. /// </param> /// <param name="req"> /// The http web Request object. Each ApiMakeCall method will have its own http webrequest information. This method will make /// the http call with the request object passed to it. /// </param> /// <returns></returns> static ApiCallResponse ApiHttpRequestProcessor(ApiCallResponse ac, HttpWebRequest req) { var responseFromServer = ""; try { using (var httpWResp = req.GetResponse() as HttpWebResponse) { try { ac.HttpResponseCode = (int)httpWResp.StatusCode; } catch (Exception exRespCode) { ac.HttpResponseCode = -1; } var reader = new StreamReader(httpWResp.GetResponseStream()); responseFromServer = reader.ReadToEnd(); reader.Close(); try { ac.XmlReceived.LoadXml(responseFromServer); } catch (Exception ex) { ac.XmlReceived = null; } try { ac.HttpResponseCode = (int)httpWResp.StatusCode; if (ac.HttpResponseCode == 201) { try { ac.Id = Int64.Parse(ac.XmlReceived.DocumentElement.Attributes["id"].Value); } catch (Exception exx) { ac.Id = 0; } } } catch (Exception exx) { ac.HttpResponseCode = -1; } ac.HasException = false; ac.ExceptionDetails = ""; } } catch (WebException ex) { try { ac.HttpResponseCode = (int)((((HttpWebResponse)ex.Response).StatusCode)); ac.ExceptionDetails = ex.Message; } catch {} ac.HasException = true; if (String.IsNullOrEmpty(ac.ExceptionDetails) == true) { ac.ExceptionDetails = ex.ToString(); } if (String.IsNullOrEmpty(responseFromServer) == false) { ac.ExceptionDetails = "Response from server: " + responseFromServer; } string exresponseFromServer = ""; try { var exreader = new StreamReader(ex.Response.GetResponseStream()); exresponseFromServer = exreader.ReadToEnd().ToString(); exreader.Close(); if (String.IsNullOrEmpty(exresponseFromServer) == false) { ac.ExceptionDetails = ac.ExceptionDetails + Environment.NewLine + "Exception response:" + exresponseFromServer; } } catch (Exception exread) { if (ac.HttpResponseCode == 0) { ac.HttpResponseCode = 503; } } if (String.IsNullOrEmpty(exresponseFromServer) == false) { try { ac.XmlReceived.LoadXml(exresponseFromServer); XmlNode mainnode = ac.XmlReceived.DocumentElement; if (mainnode.LocalName.ToLower() == "error") { if (mainnode.Attributes["code"].InnerText.ToLower() != "") { ac.HttpResponseCode = Int32.Parse(mainnode.Attributes["code"].InnerText.ToString()); } if (mainnode.Attributes["message"].InnerText.ToLower() != "") { ac.ExceptionDetails = mainnode.Attributes["message"].InnerText.ToString(); } } } catch (Exception exp) { ac.XmlReceived = null; } } else { ac.XmlReceived = null; } } finally { // xml sent and xml received cleanup // TEMP FIX if (ac.XmlReceived != null && String.IsNullOrEmpty(ac.XmlReceived.InnerXml)) { ac.XmlReceived = null; } if (ac.XmlSent != null && String.IsNullOrEmpty(ac.XmlSent.InnerXml)) { ac.XmlSent = null; } } return(ac); }
public void showErrorMessage(ApiCallResponse apiCallResponse) { showErrorMessage(apiCallResponse.errorMessage, apiCallResponse.errorDescription, ""); }