public void ConnectMsg(string msg, string id, Newtonsoft.Json.Linq.JContainer data) { //Program.awaitingPlayersID.Add(id); UserVoter newplayer; if (!Program.ConnIDtoUser.TryGetValue(id, out newplayer)) { newplayer = new UserVoter(id, data["workerId"] != null ? data["workerId"].ToString() : "", data["assignmentId"] != null ? data["assignmentId"].ToString() : ""); Program.ConnIDtoUser.Add(id, newplayer); } if (WaitingRoom.joinWaitingRnStart(newplayer)) { foreach (Game playingGame in Program.PlayingGames.Where(playingGame => playingGame.status != "playing")) { sendStartToPlayers(playingGame); } } if (newplayer.CurrGame == null) { Clients.Client(id).StartGameMsg("wait"); waitingRoomStats(); } }
private static Parameter CreateParameterFromGrouping(IEnumerable <ParameterTransformation> grouping, Method method, ServiceClient serviceClient) { var properties = new List <Property>(); string parameterGroupName = null; foreach (var parameter in grouping.Select(g => g.OutputParameter)) { Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as Newtonsoft.Json.Linq.JContainer; string specifiedGroupName = extensionObject.Value <string>("name"); if (specifiedGroupName == null) { string postfix = extensionObject.Value <string>("postfix") ?? "Parameters"; parameterGroupName = method.Group + "-" + method.Name + "-" + postfix; } else { parameterGroupName = specifiedGroupName; } Property groupProperty = new Property() { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = null //Parameter is never serialized directly }; properties.Add(groupProperty); } var parameterGroupType = new CompositeType() { Name = parameterGroupName, Documentation = "Additional parameters for the " + method.Name + " operation." }; //Add to the service client serviceClient.ModelTypes.Add(parameterGroupType); foreach (Property property in properties) { parameterGroupType.Properties.Add(property); } bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type return(new Parameter() { Name = parameterGroupName, IsRequired = isGroupParameterRequired, Location = ParameterLocation.None, SerializedName = string.Empty, Type = parameterGroupType, Documentation = "Additional parameters for the operation" }); }
public string PostOP([FromForm] string op, [FromForm] string jsnInData) { int HttpStatusCodeOK = (int)HttpStatusCode.OK; int HttpStatusCodeInternalServerError = (int)HttpStatusCode.InternalServerError; try { Newtonsoft.Json.Linq.JContainer OInData = null; if (jsnInData != null) { OInData = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(jsnInData); } switch (op) { case "Set_Price": clsApp.g_price = Double.Parse((string)OInData["Price"]); return("{\"StatusCode\":\"" + HttpStatusCodeOK.ToString() + "\",\"jsnDataOut\":{ }}"); } string ErrorDesc = $"DTLMT4Controller.PostOP op = { op }, jsnInData={jsnInData},error.Message =op { op } not supported"; return("{\"StatusCode\":\"" + HttpStatusCodeInternalServerError.ToString() + "\",\"ErrorDescription\":" + ErrorDesc + "}"); } catch (Exception e) { string ErrorDesc = $"DTLMT4Controller.PostOP op = { op }, jsnInData={jsnInData},error.Message = { e.Message }"; ErrorDesc = ErrorDesc.Replace("\"", "'"); return("{\"StatusCode\":\"" + HttpStatusCodeInternalServerError.ToString() + "\",\"ErrorDescription\":\"" + ErrorDesc + "\"}"); } }
public WorkItemPatchResponse.WorkItem DeleteWorkItem(string id) { WorkItemPatchResponse.WorkItem viewModel = new WorkItemPatchResponse.WorkItem(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); var method = new HttpMethod("DELETE"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/workitems/" + id + "?api-version=2.2"); var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
public static string GetClientRequestIdString(Method method) { if (method == null) { throw new ArgumentNullException("method"); } string clientRequestIdName = "x-ms-client-request-id"; foreach (Parameter parameter in method.Parameters) { if (parameter.Extensions.ContainsKey(ClientRequestIdExtension)) { Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ClientRequestIdExtension] as Newtonsoft.Json.Linq.JContainer; if (extensionObject != null) { bool useParamAsClientRequestId = (bool)extensionObject["value"]; if (useParamAsClientRequestId) { //TODO: Need to do something if they specify two ClientRequestIdExtensions for the same method...? clientRequestIdName = parameter.SerializedName; break; } } } } return(clientRequestIdName); }
private void dadosPublicos() { while (true) { try { var client = new RestClient("https://quantum.atlasquantum.com/api/volume"); client.Timeout = -1; var request = new RestRequest(Method.GET); IRestResponse response = client.Execute(request); var jsonAsString = response.Content; Newtonsoft.Json.Linq.JContainer json = (Newtonsoft.Json.Linq.JContainer)JsonConvert.DeserializeObject(jsonAsString); this.Text = "Cotação atual BTCQ: " + json[0]["last"].ToString() + " BTC - " + DateTime.Now.ToString(); lblLast.Text = json[0]["last"].ToString() + " BTC"; lbl24btc.Text = json[0]["baseVolume"].ToString() + " BTC"; lbl24btcq.Text = json[0]["quoteVolume"].ToString() + " BTCQ"; lblmaior.Text = json[0]["high24hr"].ToString() + " BTC"; lblmenor.Text = json[0]["low24hr"].ToString() + " BTC"; lblUpdate.Text = "Última atualização: " + DateTime.Now.ToString(); } catch { } Thread.Sleep(3000); } }
public ViewModels.WorkItemTracking.AttachmentReference UploadAttachmentBinaryFile(string filePath) { Byte[] bytes = File.ReadAllBytes(@filePath); String[] breakApart = filePath.Split('\\'); int length = breakApart.Length; string fileName = breakApart[length - 1]; ViewModels.WorkItemTracking.AttachmentReference viewModel = new ViewModels.WorkItemTracking.AttachmentReference(); using (var client = new HttpClient()) { client.BaseAddress = new Uri(_configuration.UriString); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); ByteArrayContent content = new ByteArrayContent(bytes); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); HttpResponseMessage response = client.PostAsync("_apis/wit/attachments?fileName=" + fileName + "&api-version=2.2", content).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <ViewModels.WorkItemTracking.AttachmentReference>().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
/// <summary> /// Add hyperlink to work item /// </summary> /// <param name="id"></param> /// <returns>WorkItemPatchResponse.WorkItem</returns> public WorkItemPatchResponse.WorkItem AddCommitLink(string id) { WorkItemPatchResponse.WorkItem viewModel = new WorkItemPatchResponse.WorkItem(); WorkItemPatch.Field[] fields = new WorkItemPatch.Field[1]; // change some values on a few fields fields[0] = new WorkItemPatch.Field() { op = "add", path = "/relations/-", value = new WorkItemPatch.Value() { rel = "ArtifactLink", url = "vstfs:///Git/Commit/1435ac99-ba45-43e7-9c3d-0e879e7f2691%2Fd00dd2d9-55dd-46fc-ad00-706891dfbc48%2F3fefa488aac46898a25464ca96009cf05a6426e3", attributes = new WorkItemPatch.Attributes() { name = "Fixed in Commit" } } }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(fields), Encoding.UTF8, "application/json-patch+json"); // mediaType needs to be application/json-patch+json for a patch call // set the httpmethod to Patch var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/workitems/" + id + "?api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <WorkItemPatchResponse.WorkItem>().Result; viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
/// <summary> /// Add hyperlink to work item /// </summary> /// <param name="id"></param> /// <returns>WorkItemPatchResponse.WorkItem</returns> public WorkItemPatchResponse.WorkItem AddHyperLink(string id) { WorkItemPatchResponse.WorkItem viewModel = new WorkItemPatchResponse.WorkItem(); WorkItemPatch.Field[] fields = new WorkItemPatch.Field[1]; // change some values on a few fields fields[0] = new WorkItemPatch.Field() { op = "add", path = "/relations/-", value = new WorkItemPatch.Value() { rel = "Hyperlink", url = "http://www.visualstudio.com/team-services", attributes = new WorkItemPatch.Attributes() { comment = "Visual Studio Team Services" } } }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(fields), Encoding.UTF8, "application/json-patch+json"); // mediaType needs to be application/json-patch+json for a patch call // set the httpmethod to Patch var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/workitems/" + id + "?api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <WorkItemPatchResponse.WorkItem>().Result; viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
/// <summary> /// Update Iteration Dates /// </summary> /// <param name="project"></param> /// <param name="path"></param> /// <param name="startDate"></param> /// <param name="finishDate"></param> /// <returns></returns> public GetNodeResponse.Node UpdateIterationDates(string project, string path, DateTime startDate, DateTime finishDate) { try { CreateUpdateNodeViewModel.Node node = new CreateUpdateNodeViewModel.Node() { //name = path, attributes = new CreateUpdateNodeViewModel.Attributes() { startDate = startDate, finishDate = finishDate } }; GetNodeResponse.Node viewModel = new GetNodeResponse.Node(); using (var client = GetHttpClient()) { // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(node), Encoding.UTF8, "application/json"); var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, project + "/_apis/wit/classificationNodes/iterations/" + path + "?api-version=" + _configuration.VersionNumber) { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <GetNodeResponse.Node>().Result; viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); var errorMessage = response.Content.ReadAsStringAsync(); string error = Utility.GeterroMessage(errorMessage.Result.ToString()); this.LastFailureMessage = error; } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } } catch (Exception ex) { logger.Debug(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + "\t" + ex.Message + "\t" + "\n" + ex.StackTrace + "\n"); } return(new GetNodeResponse.Node()); }
public GetRestoreMultipleWorkItemsResponse.Items PeremenentlyDeleteMultipleItems(string[] ids) { GetRestoreMultipleWorkItemsResponse.Items viewModel = new GetRestoreMultipleWorkItemsResponse.Items(); WorkItemBatchPost.BatchRequest[] postDocument = new WorkItemBatchPost.BatchRequest[3]; Dictionary <string, string> headers = new Dictionary <string, string>() { { "Content-Type", "application/json-patch+json" } }; var i = 0; foreach (var id in ids) { postDocument[i] = new WorkItemBatchPost.BatchRequest { method = "DELETE", uri = "/_apis/wit/recyclebin/" + id + "?api-version=3.0-preview", headers = headers }; i = i + 1; } ; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); var postValue = new StringContent(JsonConvert.SerializeObject(postDocument), Encoding.UTF8, "application/json"); var method = new HttpMethod("POST"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/$batch?api-version=3.0-preview") { Content = postValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <GetRestoreMultipleWorkItemsResponse.Items>().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
private ShipStatistics ParseStatistics(Newtonsoft.Json.Linq.JContainer stats, bool isRetrofit) { var ship = new ShipStatistics(); var applicableStats = isRetrofit ? stats.Where(s => s["title"].ToString().Contains("Retrofit")) : stats.Where(s => !s["title"].ToString().Contains("Retrofit")); ship.Level100 = applicableStats.FirstOrDefault(s => s["title"].ToString().StartsWith("Level 100"))?.ToStatistics(); ship.Level120 = applicableStats.FirstOrDefault(s => s["title"].ToString().StartsWith("Level 120"))?.ToStatistics(); ship.Base = isRetrofit ? null : stats.FirstOrDefault(s => s["title"].ToString().Contains("Base")).ToStatistics(); return(ship); }
public GetOperationResponse.Operation CreateTeamProject(string name) { GetOperationResponse.Operation operation = new GetOperationResponse.Operation(); Object teamProject = new { name = name, description = "VanDelay Industries travel app", capabilities = new { versioncontrol = new { sourceControlType = "Git" }, processTemplate = new { templateTypeId = "6b724908-ef14-45cf-84f8-768b5384da45" } } }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(teamProject), Encoding.UTF8, "application/json"); var method = new HttpMethod("POST"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/projects?api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { operation = response.Content.ReadAsAsync <GetOperationResponse.Operation>().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; operation.Message = msg.ToString(); } operation.HttpStatusCode = response.StatusCode; return(operation); } }
private static void config() { String configJson = System.IO.File.ReadAllText($"{AppDomain.CurrentDomain.BaseDirectory}config.json"); Newtonsoft.Json.Linq.JContainer jContainer = (Newtonsoft.Json.Linq.JContainer)JsonConvert.DeserializeObject(configJson); Key.key = Environment.GetEnvironmentVariable("binanceApiKey"); Key.secret = Environment.GetEnvironmentVariable("binanceApiSecret"); initialValue = decimal.Parse(jContainer["initialValue"].ToString(), System.Globalization.NumberStyles.Float); percValue = decimal.Parse(jContainer["percValue"].ToString(), System.Globalization.NumberStyles.Float); }
/// <summary> /// Update Iteration Dates /// </summary> /// <param name="project"></param> /// <param name="path"></param> /// <param name="startDate"></param> /// <param name="finishDate"></param> /// <returns></returns> public GetNodeResponse.Node UpdateIterationDates(string project, string path, DateTime startDate, DateTime finishDate) { CreateUpdateNodeViewModel.Node node = new CreateUpdateNodeViewModel.Node() { //name = path, attributes = new CreateUpdateNodeViewModel.Attributes() { startDate = startDate, finishDate = finishDate } }; GetNodeResponse.Node viewModel = new GetNodeResponse.Node(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(node), Encoding.UTF8, "application/json"); var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + project + "/_apis/wit/classificationNodes/iterations/" + path + "?api-version=" + _configuration.VersionNumber) { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <GetNodeResponse.Node>().Result; viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); var errorMessage = response.Content.ReadAsStringAsync(); string error = Utility.GeterroMessage(errorMessage.Result.ToString()); this.LastFailureMessage = error; } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
public GetNodeResponse.Node CreateIteration(string project, string path) { CreateUpdateNodeViewModel.Node node = new CreateUpdateNodeViewModel.Node() { name = path //attributes = new CreateUpdateNodeViewModel.Attributes() //{ // startDate = startDate, // finishDate = finishDate //} }; GetNodeResponse.Node viewModel = new GetNodeResponse.Node(); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var postValue = new StringContent(JsonConvert.SerializeObject(node), Encoding.UTF8, "application/json"); var method = new HttpMethod("POST"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + project + "/_apis/wit/classificationNodes/iterations?api-version=2.2") { Content = postValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <GetNodeResponse.Node>().Result; viewModel.Message = "success"; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
public string CreateBugByPassingRules() { var projectName = _configuration.Project; Object[] patchDocument = new Object[6]; patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Imported bug from my other system (rest api)" }; patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http:// msdn.microsoft.com/en-us/library/live/hh826547.aspx" }; patchDocument[2] = new { op = "add", path = "/fields/System.CreatedBy", value = "Some User" }; patchDocument[3] = new { op = "add", path = "/fields/System.ChangedBy", value = "Some User" }; patchDocument[4] = new { op = "add", path = "/fields/System.CreatedDate", value = "4/15/2016" }; patchDocument[5] = new { op = "add", path = "/fields/System.History", value = "Data imported from source" }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json"); // mediaType needs to be application/json-patch+json for a patch call // set the httpmethod to Patch var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + projectName + "/_apis/wit/workitems/$Bug?bypassRules=true&api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; patchDocument = null; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; return("success"); } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; return(msg.ToString()); } } }
private void RebuildList() { m_content.Controls.Clear(); if (string.IsNullOrEmpty(m_jsonResult)) { return; } try { Newtonsoft.Json.Linq.JContainer collection = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JContainer>(m_jsonResult); if (collection.Type == Newtonsoft.Json.Linq.JTokenType.Array && m_collectionType == CollectionPropertyEditorUtils.CollectionType.JsonArray) { Newtonsoft.Json.Linq.JArray arr = collection as Newtonsoft.Json.Linq.JArray; if (arr != null) { FieldContainer field; foreach (var item in arr) { field = new FieldContainer(this, m_collectionType, m_creator, item.ToString(Newtonsoft.Json.Formatting.None)); field.Width = m_content.Width; field.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; m_content.Controls.Add(field); } } } else if (collection.Type == Newtonsoft.Json.Linq.JTokenType.Object && m_collectionType == CollectionPropertyEditorUtils.CollectionType.JsonObject) { Newtonsoft.Json.Linq.JObject obj = collection as Newtonsoft.Json.Linq.JObject; if (obj != null) { FieldContainer field; foreach (var item in obj.Properties()) { field = new FieldContainer(this, m_collectionType, m_creator, item.Value.ToString(Newtonsoft.Json.Formatting.None), item.Name); field.Width = m_content.Width; field.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; m_content.Controls.Add(field); } } } } catch { } RepositionList(); }
public bool HttpPostWrapper(string p_Controller, string p_OP, string p_jsnInData, out Newtonsoft.Json.Linq.JToken p_jsnOutData, out string p_jsnError) { int HttpStatusCodeOK = (int)HttpStatusCode.OK; using (var client = new HttpClient()) { client.BaseAddress = new Uri(c_Baseuri); var keyValues = new List <KeyValuePair <string, string> >(); keyValues.Add(new KeyValuePair <string, string>("op", p_OP)); keyValues.Add(new KeyValuePair <string, string>("jsnInData", p_jsnInData)); var dataForHTTP = new FormUrlEncodedContent(keyValues); p_jsnOutData = ""; p_jsnError = ""; var response = client.PostAsync(p_Controller, dataForHTTP).Result; if (response.IsSuccessStatusCode) { string ServerResponseData = response.Content.ReadAsStringAsync().Result; Newtonsoft.Json.Linq.JContainer OServerData = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(ServerResponseData); string StatusCode = (string)OServerData["StatusCode"]; if (StatusCode != HttpStatusCodeOK.ToString()) { p_jsnError = (string)OServerData["ErrorDescription"]; return(false); } Newtonsoft.Json.Linq.JToken jsnDataOut = OServerData.Last; p_jsnOutData = jsnDataOut.First;; return(true); } else { p_jsnError = "{'Source:':'HttpPostWrapper','Message':' Http post failed with StatusCode:' " + response.StatusCode + " and ReasonPhrase:" + response.ReasonPhrase + "}"; return(false); } } }
public static string GetRequestIdString(Method method) { if (method == null) { throw new ArgumentNullException("method"); } string requestIdName = "x-ms-request-id"; if (method.Extensions.ContainsKey(RequestIdExtension)) { Newtonsoft.Json.Linq.JContainer extensionObject = method.Extensions[RequestIdExtension] as Newtonsoft.Json.Linq.JContainer; if (extensionObject != null) { requestIdName = extensionObject["value"].ToString(); } } return(requestIdName); }
public GetOperationResponse.Operation ChangeTeamProjectDescription(string projectId, string projectDescription) { GetOperationResponse.Operation opertion = new GetOperationResponse.Operation(); Object projectData = new { description = projectDescription }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(projectData), Encoding.UTF8, "application/json"); var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/projects/" + projectId + "?api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { opertion = response.Content.ReadAsAsync <GetOperationResponse.Operation>().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; opertion.Message = msg.ToString(); } opertion.HttpStatusCode = response.StatusCode; return(opertion); } }
public HttpStatusCode PermenentlyDeleteItem(string id) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); var method = new HttpMethod("DELETE"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/recyclebin/" + id + "?api-version=3.0-preview"); var response = client.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; } return(response.StatusCode); } }
static public Newtonsoft.Json.Linq.JContainer ReadBook(string isbncode) { /* API詳細 http://blog.livedoor.jp/dankogai/archives/51227901.html * 個人サービスなので接続は保障しかねる * 楽天APIの方が楽そう */ string url = "http://api.dan.co.jp/asin/" + Amazon.isbn2asin(isbncode) + "/amazon"; string jsondata = ""; try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream st = wc.OpenRead(url); System.IO.StreamReader sr = new System.IO.StreamReader(st, System.Text.Encoding.GetEncoding("UTF-8")); jsondata = sr.ReadToEnd(); st.Close(); wc.Dispose(); } catch (Exception ex) { MessageBox.Show("書籍情報取得エラー " + ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } /* 厳密にはJSONデータではなくJSONPデータなので * "amazon(JSONデータ);\n" の形式がjsondata変数に入ってる * よって不要な部分をsubstring. */ jsondata = jsondata.Substring(0, jsondata.Length - 3).Substring(7); Newtonsoft.Json.Linq.JContainer jobj = Newtonsoft.Json.JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JContainer>(jsondata); return(jobj); }
public GetRestoredWorkItemResponse.WorkItem RestoreItem(string id) { GetRestoredWorkItemResponse.WorkItem viewModel = new GetRestoredWorkItemResponse.WorkItem(); var patchDocument = new { IsDeleted = false }; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json"); var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/recyclebin/" + id + "?api-version=3.0-preview") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { viewModel = response.Content.ReadAsAsync <GetRestoredWorkItemResponse.WorkItem>().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; viewModel.Message = msg.ToString(); } viewModel.HttpStatusCode = response.StatusCode; return(viewModel); } }
//SetOptions is called on every Tool.Down //I haven't figured a better way for converting anon json objects. protected override void SetOptions(Newtonsoft.Json.Linq.JContainer o) { base.options = o.ToObject <Options>(); }
/// <summary> /// /// </summary> /// <returns></returns> public MsgData GetBodyData() { MsgData msgdata = null; try { Newtonsoft.Json.Linq.JContainer data = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JContainer>(this.Body); msgdata = new MsgData(); msgdata.from = data["from"].ToString(); msgdata.to = data["to"].ToString(); msgdata.ext = data["ext"]; Newtonsoft.Json.Linq.JContainer bodies = data.Value <Newtonsoft.Json.Linq.JContainer>("bodies"); msgdata.bodies = new BodyBase[bodies.Count]; for (int i = 0; i < bodies.Count; i++) { string type = bodies[i]["type"].ToString(); switch (type) { case "img": msgdata.bodies[i] = JsonConvert.DeserializeObject <ImageBody>(bodies[i].ToString()); break; case "txt": msgdata.bodies[i] = JsonConvert.DeserializeObject <TextBody>(bodies[i].ToString()); break; case "audio": msgdata.bodies[i] = JsonConvert.DeserializeObject <AudioBody>(bodies[i].ToString()); break; case "video": msgdata.bodies[i] = JsonConvert.DeserializeObject <VideoBody>(bodies[i].ToString()); break; case "loc": msgdata.bodies[i] = JsonConvert.DeserializeObject <LocationBody>(bodies[i].ToString()); break; case "file": msgdata.bodies[i] = JsonConvert.DeserializeObject <FileBody>(bodies[i].ToString()); break; default: //msgdata.bodies[i] = JsonConvert.DeserializeObject<FileBody>(bodies[i].ToString()); break; } } //msgdata = JsonConvert.DeserializeObject<MsgData>(this.Body); } catch (Exception ex) { } if (msgdata != null) { } return(msgdata); }
public string PostOP([FromForm] string op, [FromForm] string jsnInData) { int HttpStatusCodeOK = (int)HttpStatusCode.OK; int HttpStatusCodeInternalServerError = (int)HttpStatusCode.InternalServerError; try { Newtonsoft.Json.Linq.JContainer OInData = null; if (jsnInData != null) { OInData = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(jsnInData); } mdDataFromServerResponse mdServerData = new mdDataFromServerResponse(); switch (op) { case "Get_Status": Random random = new Random(); int value = random.Next(0, 10); double newIndexValue = clsApp.g_index; string EnergyStarAnimation = "Resize"; newIndexValue += Convert.ToDouble(value) / 10 - 0.5; if (newIndexValue > 10) { newIndexValue -= 5; EnergyStarAnimation = "ExplodeAndResize"; } if (newIndexValue < 0) { newIndexValue = +5; EnergyStarAnimation = "ShrinkAndResize"; } clsApp.g_index = newIndexValue; mdGetStatusDataFromServerResponse mdStatusData = new mdGetStatusDataFromServerResponse(); mdStatusData.EnergyStarSize = newIndexValue.ToString(); mdStatusData.EnergyStarAnimation = EnergyStarAnimation; string jsnStatusData = Newtonsoft.Json.JsonConvert.SerializeObject(mdStatusData); mdServerData.StatusCode = HttpStatusCodeOK.ToString(); mdServerData.jsnDataOut = jsnStatusData; return(Newtonsoft.Json.JsonConvert.SerializeObject(mdServerData)); case "Set_ResetEnergyStarSize": clsApp.g_index = Double.Parse((string)OInData["EnergyStarSize"]); mdServerData.StatusCode = HttpStatusCodeOK.ToString(); mdServerData.jsnDataOut = ""; return(Newtonsoft.Json.JsonConvert.SerializeObject(mdServerData)); } throw new Exception($"Op { op } not supported"); } catch (Exception e) { mdErrorFromServerResponse mdErrorFromServer = new mdErrorFromServerResponse(); mdErrorFromServer.Function = "DTLGameController.PostOP"; mdErrorFromServer.Op = op; mdErrorFromServer.jsnInData = jsnInData; mdErrorFromServer.ErrorMessage = e.Message; string jsnErrorData = Newtonsoft.Json.JsonConvert.SerializeObject(mdErrorFromServer); mdDataFromServerResponse mdServerDataError = new mdDataFromServerResponse(); mdServerDataError.StatusCode = HttpStatusCodeInternalServerError.ToString(); mdServerDataError.jsnDataOut = jsnErrorData; return(Newtonsoft.Json.JsonConvert.SerializeObject(mdServerDataError)); } }
protected void WriteToSqlById(string ordercode) { // Dictionary<string, string> dic_send = new Dictionary<string, string>(); string Ord_Detail = api.getOrderDetail(ordercode); // dic_send.Add("ordercode", ordercode); Order order = new Order(); order = JsonConvert.DeserializeObject <Order>(Ord_Detail); Dictionary <string, Object> _dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(Ord_Detail); Newtonsoft.Json.Linq.JArray _arry = (Newtonsoft.Json.Linq.JArray)_dic["childOrderList"]; int count = _arry.Count; for (int i = 0; i < count; i++) { string temp123321 = _arry[i].ToString(); Dictionary <string, string> dic_send = new Dictionary <string, string>(); dic_send.Add("ordercode", ordercode); //基础信息 #region string sellname = _dic["sellerSignerFullname"].ToString(); dic_send.Add("sellerSignerFullname", sellname); dic_send.Add("orderstatus", "等待您发货"); //付款时间 string gmtPaySuccess = _dic["gmtPaySuccess"].ToString(); gmtPaySuccess = api.timeConvert(gmtPaySuccess); dic_send.Add("paydt", gmtPaySuccess); //下单时间 string gmtCreate = _dic["gmtCreate"].ToString(); gmtCreate = api.timeConvert(gmtCreate); dic_send.Add("orderdt", gmtCreate); //买家名称 string buyername = _dic["buyerSignerFullname"].ToString(); dic_send.Add("mj_name", buyername);//有疑问 //收货地址 Dictionary <string, Object> _receiptAddress = JsonConvert.DeserializeObject <Dictionary <string, object> >(_dic["receiptAddress"].ToString()); if (_receiptAddress.ContainsKey("mobileNo")) { string mobileNo = _receiptAddress["mobileNo"].ToString();//手机 dic_send.Add("mobile", mobileNo); } string contractPerson = _receiptAddress["contactPerson"].ToString(); dic_send.Add("contactPerson", contractPerson); string country = _receiptAddress["country"].ToString(); dic_send.Add("nation", country); string city = _receiptAddress["city"].ToString(); dic_send.Add("city", city); string province = _receiptAddress["province"].ToString(); dic_send.Add("province", province); if (_receiptAddress.ContainsKey("phoneNumber")) { string phoneNumber = _receiptAddress["phoneNumber"].ToString(); //联系电话 string phoneCountry = _receiptAddress["phoneCountry"].ToString(); string phoneArea = ""; if (_receiptAddress.ContainsKey("phoneArea")) { phoneArea = _receiptAddress["phoneArea"].ToString(); } dic_send.Add("phone", phoneCountry + "-" + phoneArea + phoneNumber); } string zip = _receiptAddress["zip"].ToString(); //邮编 dic_send.Add("code", zip); //邮政编码 string contactPerson = _receiptAddress["contactPerson"].ToString(); //联系人 dic_send.Add("shr", contactPerson); string detailAddress; if (_receiptAddress.ContainsKey("address2")) { detailAddress = _receiptAddress["detailAddress"].ToString() + " " + _receiptAddress["address2"].ToString(); //详细地址 } else { detailAddress = _receiptAddress["detailAddress"].ToString(); //详细地址 } dic_send.Add("addr", detailAddress); dic_send.Add("shaddr", detailAddress + "、" + city + "、" + province + "、" + country); //买家信息 Dictionary <string, object> _buyerInfo = JsonConvert.DeserializeObject <Dictionary <string, object> >(_dic["buyerInfo"].ToString()); string email = _buyerInfo["email"].ToString(); dic_send.Add("mj_email", email); //物流费用 Dictionary <string, object> _logisticsAmount = JsonConvert.DeserializeObject <Dictionary <string, object> >(_dic["logisticsAmount"].ToString()); string logistic_amount = _logisticsAmount["amount"].ToString(); dic_send.Add("wlfy", logistic_amount); #endregion //子订单信息组合 #region string productName = api.arrayJson(_dic["childOrderList"], "productName", i); //projects 拼装 string productBh = productName.Substring(0, productName.IndexOf(" ")); dic_send.Add("item_bh", productBh); string probh = "(商家编码:" + productBh + ")"; //订单价格 Dictionary <string, object> _orderAmount = JsonConvert.DeserializeObject <Dictionary <string, object> >(_dic["orderAmount"].ToString()); string order_amount = _orderAmount["amount"].ToString();//订单金额 dic_send.Add("all_sum", order_amount); //产品总价格 Dictionary <string, object> _initOderAmount = JsonConvert.DeserializeObject <Dictionary <string, object> >(_dic["initOderAmount"].ToString()); // string item_amount = _initOderAmount["amount"].ToString();//订单金额 dic_send.Add("ln_no", (i + 1).ToString());//序号 string lotNum = api.arrayJson(_dic["childOrderList"], "lotNum", i); string proCount = api.arrayJson(_dic["childOrderList"], "productCount", i); string UnitName = api.arrayJson(_dic["childOrderList"], "productUnit", i); string initOrderAmt = api.arrayJson(_dic["childOrderList"], "initOrderAmt", i); string skuCode = api.arrayJson(_dic["childOrderList"], "skuCode", i); Dictionary <string, object> _childList = JsonConvert.DeserializeObject <Dictionary <string, object> >(initOrderAmt); string item_amount = _childList["amount"].ToString(); string proNum = "(产品数量:" + lotNum + " " + UnitName + ")"; dic_send.Add("unit", UnitName); dic_send.Add("amount", proCount); dic_send.Add("item_sum", item_amount); dic_send.Add("skuCode", skuCode); dic_send.Add("lotNum", lotNum); string productAttributes = api.arrayJson(_dic["childOrderList"], "productAttributes", i); Dictionary <string, object> _productAttributes = JsonConvert.DeserializeObject <Dictionary <string, object> >(productAttributes); Newtonsoft.Json.Linq.JContainer jc = (Newtonsoft.Json.Linq.JContainer)_productAttributes["sku"]; // string ordertemp = jc.First.Value<string>("order").ToString(); string temp = ""; string ProSX = ""; if (jc.Count > 0) { string Name1 = jc.First.Value <string>("pName").ToString(); string value1 = ""; value1 = jc.First.Value <string>("selfDefineValue").ToString(); if (value1 == "") { value1 = jc.First.Value <string>("pValue").ToString(); } dic_send.Add(Name1.ToLower(), value1); string Name2 = ""; string value2 = ""; string Name3 = ""; string value3 = ""; string Name4 = ""; string value4 = ""; if (jc.Count == 2) { Name2 = jc.Last.Value <string>("pName").ToString().ToLower(); value2 = jc.Last.Value <string>("pValue").ToString(); string selfvalue = jc.Last.Value <string>("selfDefineValue").ToString(); if (selfvalue != "") { value2 = selfvalue; } dic_send.Add(Name2, value2); } else if (jc.Count > 2) { if (jc.First.Next.HasValues) //if (jc.Next.HasValues) { Name2 = jc.First.Next.Value <string>("pName").ToString().ToLower(); value2 = jc.First.Next.Value <string>("pValue").ToString(); string selfvalue = jc.First.Next.Value <string>("selfDefineValue").ToString(); if (selfvalue != "") { value2 = selfvalue; } dic_send.Add(Name2, value2); } if (jc.First.Next.Next.HasValues) { Name3 = jc.First.Next.Next.Value <string>("pName").ToString().ToLower(); value3 = jc.First.Next.Next.Value <string>("pValue").ToString(); string selfvalue = jc.First.Next.Next.Value <string>("selfDefineValue").ToString(); if (selfvalue != "") { value3 = selfvalue; } dic_send.Add(Name3, value3); } } if (value3 != "") { ProSX = "(产品属性" + Name1 + ":" + value1 + "、" + Name2 + ":" + value2 + "、" + Name3 + ": " + value3 + ")"; } else { ProSX = "(产品属性" + Name1 + ":" + value1 + "、" + Name2 + ":" + value2 + ")"; } } temp = "【" + (i + 1).ToString() + "】" + productName + ProSX + proNum; string Unit = api.arrayJson(_dic["childOrderList"], "productUnit", i); //单位 string productCount = api.arrayJson(_dic["childOrderList"], "productCount", i); //单位 dic_send.Add("projects", temp); dic_send.Add("deptid", shopName); //产品属性 string jihe = _dicAtt[ordercode]; int flag = jihe.IndexOf("|"); string memo; string wlname = jihe.Substring(0, flag); if (flag == jihe.Length) { memo = ""; } else { memo = jihe.Substring(flag + 1); } dic_send.Add("mjxzwl", wlname); dic_send.Add("memo", memo); #endregion db.ClassToSQL(dic_send); dic_send.Clear(); } }
public string AddAttachmentToBug() { string _id = _configuration.WorkItemId; string _filePath = _configuration.FilePath; // get the file name from the full path String[] breakApart = _filePath.Split('\\'); int length = breakApart.Length; string fileName = breakApart[length - 1]; Byte[] bytes; try { bytes = System.IO.File.ReadAllBytes(@_filePath); } catch (System.IO.FileNotFoundException) { return(@"file not found: " + _filePath); } using (var client = new HttpClient()) { client.BaseAddress = new Uri(_configuration.UriString); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); ByteArrayContent content = new ByteArrayContent(bytes); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); HttpResponseMessage uploadResponse = client.PostAsync("_apis/wit/attachments?fileName=" + fileName + "&api-version=2.2", content).Result; if (uploadResponse.IsSuccessStatusCode) { var attachmentReference = uploadResponse.Content.ReadAsAsync <AttachmentReference>().Result; Object[] patchDocument = new Object[1]; // add required attachment values patchDocument[0] = new { op = "add", path = "/relations/-", value = new { rel = "AttachedFile", url = attachmentReference.url, // url from uploadresult attributes = new { comment = "adding attachment to bug" } } }; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials); // serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json"); // mediaType needs to be application/json-patch+json for a patch call // set the httpmethod to Patch var method = new HttpMethod("PATCH"); // send the request var request = new HttpRequestMessage(method, _configuration.UriString + "_apis/wit/workitems/" + _id + "?api-version=2.2") { Content = patchValue }; var response = client.SendAsync(request).Result; if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; } else { dynamic responseForInvalidStatusCode = response.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; return(msg.ToString()); } return("success"); } else { dynamic responseForInvalidStatusCode = uploadResponse.Content.ReadAsAsync <dynamic>(); Newtonsoft.Json.Linq.JContainer msg = responseForInvalidStatusCode.Result; return(msg.ToString()); } } }
private void BarcodeForm_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 2) { //2がバーコード読み取り開始 this.isReading = true; this.strBarcode = ""; //初期化 } else if (e.KeyChar == 3) { //3がバーコード読み取り終了 this.isReading = false; if (strBarcode.Length != 13) { MessageBox.Show("ISBNコードではないようです。", "新規登録/編集", MessageBoxButtons.OK); return; } if (strBarcode.Substring(0, 2) == "19") { MessageBox.Show("本上段のバーコードを読み取ってください。", "新規登録/編集", MessageBoxButtons.OK); return; } if (((BookForm1)this.Owner).dataTable.Rows.Find(strBarcode) != null) { MessageBox.Show("すでにその本は登録されてます。", "新規登録/編集", MessageBoxButtons.OK); return; } if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { MessageBox.Show("ネットワークに接続されてないので本情報を取得できません", "新規登録/編集", MessageBoxButtons.OK); return; } //Amazon APIに問い合わせ Newtonsoft.Json.Linq.JContainer d = Amazon.ReadBook(strBarcode); if (d["Error"] != null) { MessageBox.Show("書籍情報がネットワークから取得できませんでした。", "新規登録/編集", MessageBoxButtons.OK); return; } string isbn = d["ItemAttributes"]["EANList"]["EANListElement"].ToString(); string bookname = d["ItemAttributes"]["Title"].ToString(); string onsale = d["ItemAttributes"]["PublicationDate"].ToString(); string publisher = d["ItemAttributes"]["Publisher"].ToString(); string url = "http://www.amazon.co.jp/dp/" + d["ASIN"].ToString() + "/"; string tag = ""; string author; //著者が二人以上なら最初の一人のみ登録 if (d["ItemAttributes"]["Author"].Count() > 1) { author = d["ItemAttributes"]["Author"][0].ToString(); } else { author = d["ItemAttributes"]["Author"].ToString(); } DataRow workRow = ((BookForm1)this.Owner).dataTable.NewRow(); workRow["BOOK_ISBN"] = isbn; workRow["BOOK_NAME"] = bookname; workRow["BOOK_AUTHOR"] = author; workRow["BOOK_ONSALE"] = onsale; workRow["BOOK_PUBLISHER"] = publisher; workRow["BOOK_URL"] = url; workRow["BOOK_TAG"] = tag; workRow["BOOK_LENDINGPERIOD"] = Settings.LendingPeriod; ((BookForm1)this.Owner).dataTable.Rows.Add(workRow); ((BookForm1)this.Owner).editFlag = true; //本タイトルがフォームラベルに収まるように15文字以上は省略する if (bookname.Length > 15) { bookname = bookname.Substring(0, 15) + "..."; } this.ResultLabel.Text = "「" + bookname + "」を読み取りました"; //Amazon APIリクエスト制限を守る System.Threading.Thread.Sleep(Settings.AmazonRequestInterval); } else { //読み取り途中の場合 if (this.isReading == true) { this.strBarcode += e.KeyChar.ToString(); e.Handled = true; } } }