/// <summary> /// Sends an <see cref="HttpRequestMessage"/>. /// </summary> /// <param name="client">The client.</param> /// <param name="request">The request.</param> /// <param name="headers">Optional request headers.</param> /// <param name="completionOption"> /// Optionally specifies when the operation should complete (as soon as a response is available or after /// reading the whole response content). /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="activity">Optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The response.</returns> /// <exception cref="ArgumentNullException">Thrown when a required argument is <c>null</c>.</exception> /// <exception cref="InvalidOperationException">Thrown when the request has already been sent by the <see cref="HttpClient"/> class.</exception> public static async Task <HttpResponseMessage> SendAsync( this HttpClient client, HttpRequestMessage request, ArgDictionary headers = null, HttpCompletionOption completionOption = default, CancellationToken cancellationToken = default, LogActivity activity = default) { await SyncContext.ClearAsync; if (!string.IsNullOrEmpty(activity.Id)) { request.Headers.Add(LogActivity.HttpHeader, activity.Id); } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value.ToString()); } } return(await client.SendAsync(request, completionOption, cancellationToken)); }
/// <summary> /// Returns all data from an api endpoint from all pages. /// </summary> /// <param name="url"></param> /// <param name="cancellationToken"></param> /// <param name="args"></param> /// <returns></returns> public async Task <IEnumerable <T> > GetListAsync <T>(string url, ArgDictionary args = null, CancellationToken cancellationToken = default(CancellationToken)) { var data = new List <T>(); var response = await _jsonClient.GetAsync <dynamic>(url, args, cancellationToken : cancellationToken); while (response != null) { foreach (dynamic elem in response.data) { T elemObject = JsonConvert.DeserializeObject <T>(Convert.ToString(elem)); data.Add(elemObject); } var nextPage = (string)response.next_href; // get the next page if (string.IsNullOrWhiteSpace(nextPage) == false) { response = await _jsonClient.GetAsync <dynamic>(nextPage, cancellationToken : cancellationToken); } else { response = null; } } return(data); }
/// <summary> /// Performs an HTTP <b>GET</b> without ensuring that a success code was returned. /// </summary> /// <param name="uri">The URI</param> /// <param name="args">The optional query arguments.</param> /// <param name="headers">The Optional HTTP headers.</param> /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param> /// <param name="logActivity">The optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The <see cref="JsonResponse"/>.</returns> /// <exception cref="SocketException">Thrown for network connectivity issues.</exception> public async Task <JsonResponse> GetUnsafeAsync( string uri, ArgDictionary args = null, ArgDictionary headers = null, CancellationToken cancellationToken = default, LogActivity logActivity = default) { await SyncContext.ClearAsync; Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(uri), nameof(uri)); return(await unsafeRetryPolicy.InvokeAsync( async() => { var requestUri = FormatUri(uri, args); try { var client = this.HttpClient; if (client == null) { throw new ObjectDisposedException(nameof(JsonClient)); } var httpResponse = await client.GetAsync(requestUri, cancellationToken: cancellationToken, headers: headers, activity: logActivity); return new JsonResponse(requestUri, httpResponse, await httpResponse.Content.ReadAsStringAsync()); } catch (HttpRequestException e) { throw new HttpException(e, requestUri); } })); }
/// <summary> /// Sends a GET request to a <see cref="Uri"/> and returns the response as a string. /// </summary> /// <param name="client">The client.</param> /// <param name="requestUri">The request URI.</param> /// <param name="headers">Optional request headers.</param> /// <param name="activity">Optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The response string.</returns> /// <exception cref="ArgumentNullException">Thrown when a required argument is <c>null</c>.</exception> public static async Task <string> GetStringAsync( this HttpClient client, Uri requestUri, ArgDictionary headers = null, LogActivity activity = default) { await SyncContext.ClearAsync; var request = new HttpRequestMessage(HttpMethod.Get, requestUri); if (!string.IsNullOrEmpty(activity.Id)) { request.Headers.Add(LogActivity.HttpHeader, activity.Id); } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value.ToString()); } } var response = await client.SendAsync(request); return(await response.Content.ReadAsStringAsync()); }
private void SetOptionsFromJson() { var searchOptionsDict = JsonSerializer.Deserialize <SearchOptionsDictionary>(_searchOptionsResource); var optionDicts = searchOptionsDict["searchoptions"]; foreach (var optionDict in optionDicts) { var longArg = optionDict["long"]; var shortArg = optionDict.ContainsKey("short") ? optionDict["short"] : null; var desc = optionDict["desc"]; if (ArgActionDictionary.ContainsKey(longArg)) { var option = new SearchArgOption(shortArg, longArg, ArgActionDictionary[longArg], desc); Options.Add(option); ArgDictionary.Add(longArg, option); if (!string.IsNullOrWhiteSpace(shortArg)) { ArgDictionary.Add(shortArg, option); } } else if (BoolFlagActionDictionary.ContainsKey(longArg)) { var option = new SearchFlagOption(shortArg, longArg, BoolFlagActionDictionary[longArg], desc); Options.Add(option); FlagDictionary.Add(longArg, option); if (!string.IsNullOrWhiteSpace(shortArg)) { FlagDictionary.Add(shortArg, option); } } } }
private void SetOptionsFromXml() { var doc = XDocument.Parse(_searchOptionsResource); foreach (var f in doc.Descendants("searchoption")) { var longArg = f.Attributes("long").First().Value; var shortArg = f.Attributes("short").First().Value; var desc = f.Value.Trim(); if (ArgActionDictionary.ContainsKey(longArg)) { var option = new SearchArgOption(shortArg, longArg, ArgActionDictionary[longArg], desc); Options.Add(option); ArgDictionary.Add(longArg, option); if (!string.IsNullOrWhiteSpace(shortArg)) { ArgDictionary.Add(shortArg, option); } } else if (BoolFlagActionDictionary.ContainsKey(longArg)) { var option = new SearchFlagOption(shortArg, longArg, BoolFlagActionDictionary[longArg], desc); Options.Add(option); FlagDictionary.Add(longArg, option); if (!string.IsNullOrWhiteSpace(shortArg)) { FlagDictionary.Add(shortArg, option); } } } }
public static IArgDictionary<string, string[]> Parse(string[] args) { IArgDictionary<string, string[]> parsedArgs = new ArgDictionary<string, string[]>(); int numberOfArguments = args.Length; string lastOption = ""; List<string> lastArguments = new List<string>(); int i = 0; while (i < numberOfArguments) { if (IsShortOption(args[i])) { parsedArgs.Add(lastOption, lastArguments.ToArray()); lastOption = IsLongOption(args[i]) ? args[i].Substring(2) : args[i].Substring(1); lastArguments = new List<string>(); } else { lastArguments.Add(args[i]); } i++; } parsedArgs.Add(lastOption, lastArguments.ToArray()); return parsedArgs; }
/// <summary> /// 建構式,傳入精靈參數 /// </summary> /// <param name="args"></param> public SelectFields(ArgDictionary args) : base(args) { InitializeComponent(); NextButtonTitle = "開始驗證"; mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["EMBA.ImportWizard"] as ImportWizard; mSelectableFields = mArgs["SelectableFields"] as List<string>; mImportOption.SelectedFields.Clear(); this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名稱(目前頁數/總頁數) RefreshFields(); chkSelectAll.CheckedChanged += (sender,e) => { foreach (ListViewItem Item in lvSourceFieldList.Items) { Item.Checked = chkSelectAll.Checked; } }; //若是沒有使用者可選擇的欄位,則直接跳到下個畫面;目前設這會有問題... //if (mSelectableFields.Count == 0) // this.OnNextButtonClick(); }
/// <summary> /// Sends a HEAD request to a <see cref="Uri"/>. /// </summary> /// <param name="client">The client.</param> /// <param name="requestUri">The request URI.</param> /// <param name="content">The content to be sent to the server.</param> /// <param name="headers">Optional request headers.</param> /// <param name="completionOption"> /// Optionally specifies when the operation should complete (as soon as a response is available or after /// reading the whole response content). /// </param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="activity">Optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The response.</returns> /// <exception cref="ArgumentNullException">Thrown when a required argument is <c>null</c>.</exception> public static async Task <HttpResponseMessage> HeadAsync( this HttpClient client, Uri requestUri, HttpContent content = null, ArgDictionary headers = null, HttpCompletionOption completionOption = default, CancellationToken cancellationToken = default, LogActivity activity = default) { var request = new HttpRequestMessage(headMethod, requestUri); if (content != null) { request.Content = content; } if (!string.IsNullOrEmpty(activity.Id)) { request.Headers.Add(LogActivity.HttpHeader, activity.Id); } if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value.ToString()); } } return(await client.SendAsync(request, completionOption, cancellationToken)); }
/// <summary> /// 建构式,传入精灵参数 /// </summary> /// <param name="args"></param> public SelectFields(ArgDictionary args) : base(args) { InitializeComponent(); NextButtonTitle = "开始验证"; mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["ImportWizard"] as ImportWizard; mSelectableFields = mArgs["SelectableFields"] as List<string>; this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名称(目前页数/总页数) RefreshFields(); chkSelectAll.CheckedChanged += (sender, e) => { foreach (ListViewItem Item in lvSourceFieldList.Items) { Item.Checked = chkSelectAll.Checked; } }; //若是没有使用者可选择的字段,则直接跳到下个画面;目前设这会有问题... //if (mSelectableFields.Count == 0) // this.OnNextButtonClick(); }
/// <summary> /// Gets a result from the Prometheus API. /// </summary> /// <param name="path"></param> /// <param name="args"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <T> GetAsync <T>( string path, ArgDictionary args, CancellationToken cancellationToken = default) { return(await JsonClient.GetAsync <T>(path, args, cancellationToken : cancellationToken)); }
public void AddTest(string key, string value1, string value2=null) { string[] testValues = value2 == null ? new[] { value1 } : new[] { value1, value2 }; ArgDictionary<string, string[]> testObject = new ArgDictionary<string, string[]>(); testObject.Add(key, testValues); Assert.IsTrue(testObject.Keys.Contains(key)); Assert.IsTrue(testObject.Values.Contains(testValues)); }
public void RemoveTest(string key, string values) { ArgDictionary<string, string[]> testObject = new ArgDictionary<string, string[]>(); testObject.Add(key, new[]{values}); Assert.IsTrue(testObject.Keys.Contains(key)); testObject.Remove(key); Assert.IsFalse(testObject.Keys.Contains(key)); }
/// <summary> /// Gets the ongoing deliveries for the customer. /// </summary> /// <param name="cancellationToken">The optional cancellation token.</param> /// <returns></returns> public async Task <IEnumerable <PostmatesDelivery> > GetOngoingDeliveriesAsync(CancellationToken cancellationToken = default) { var arguments = new ArgDictionary { { "filter", "ongoing" } }; return(await GetListAsync <PostmatesDelivery>(FormatPath("deliveries"), arguments, cancellationToken : cancellationToken)); }
public void ContainsTest(string returnKey, bool expected) { ArgDictionary<string, string[]> testObject = new ArgDictionary<string, string[]>(); for (int i = 0; i < 3; i++) { testObject.Add(i.ToString(), new[] { i.ToString() }); } Assert.AreEqual(expected, testObject.ContainsKey(returnKey)); }
public void IndexTest(int addedOptions, int returnedPosition, string expected) { ArgDictionary<string, string[]> testObject = new ArgDictionary<string, string[]>(); for (int i = 0; i < addedOptions; i++) { testObject.Add(i.ToString(), new[] { i.ToString() }); } Assert.AreEqual(expected == null ? null : new[]{expected}, testObject[returnedPosition.ToString()]); }
/// <summary> /// Gets a regular query from the Prometheus API. /// </summary> /// <param name="query"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <PrometheusResponse <PrometheusVectorResult> > QueryAsync( string query, CancellationToken cancellationToken = default) { var args = new ArgDictionary(); args.Add("query", query); return(await GetAsync <PrometheusResponse <PrometheusVectorResult> >("api/v1/query", args, cancellationToken)); }
public void CountTest(int addedOptions) { ArgDictionary<string, string[]> testObject = new ArgDictionary<string, string[]>(); for (int i = 0; i < addedOptions; i++) { testObject.Add(i.ToString(), new[]{"abc"}); } int result = testObject.Count; Assert.AreEqual(addedOptions, result); }
public WizardForm(ArgDictionary args) { InitializeComponent(); Arguments = args; CurrentStep = Arguments.TryGetInteger("CurrentStep", 1); TotalStep = Arguments.TryGetInteger("TotalStep", 1); if (TotalStep == 1 || CurrentStep == 1) btnPrevious.Enabled = false; if (CurrentStep == TotalStep) btnNext.Text = "完成"; }
/// <summary> /// Formats the URI by appending query arguments as required. /// </summary> /// <param name="uri">The base URI.</param> /// <param name="args">The query arguments.</param> /// <returns>The formatted URI.</returns> private string FormatUri(string uri, ArgDictionary args) { if (args == null || args.Count == 0) { return(AbsoluteUri(uri)); } var sb = new StringBuilder(uri); var first = true; foreach (var arg in args) { if (first) { sb.Append('?'); first = false; } else { sb.Append('&'); } string value; if (arg.Value == null) { // Don't serialize NULL values. Their absence // will indicate their NULL-ness. continue; } else if (arg.Value is bool) { value = NeonHelper.ToBoolString((bool)arg.Value); } else if (arg.Value != null && typeToConverter.TryGetValue(arg.Value.GetType(), out var converter)) { value = converter.ToSimpleString(arg.Value); } else { value = arg.Value.ToString(); } sb.Append($"{arg.Key}={Uri.EscapeDataString(value)}"); } return(AbsoluteUri(sb.ToString())); }
public async Task GetUnsafeAsync_Args() { // Ensure that GET with query arguments work. using (new MockHttpServer(baseUri, async context => { var request = context.Request; var response = context.Response; if (request.Method != "GET") { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } if (request.Path.ToString() != "/info") { response.StatusCode = (int)HttpStatusCode.NotFound; return; } var output = new ReplyDoc() { Value1 = request.QueryGet("arg1"), Value2 = request.QueryGet("arg2") }; response.ContentType = "application/json"; await response.WriteAsync(NeonHelper.JsonSerialize(output)); })) { using (var jsonClient = new JsonClient()) { var args = new ArgDictionary() { { "arg1", "test1" }, { "arg2", "test2" } }; var reply = (await jsonClient.GetUnsafeAsync(baseUri + "info", args: args)).As <ReplyDoc>(); Assert.Equal("test1", reply.Value1); Assert.Equal("test2", reply.Value2); } }; }
public async Task DeleteAsync_Headers() { // Ensure that DELETE with headers work. using (new MockHttpServer(baseUri, async context => { var request = context.Request; var response = context.Response; if (request.Method != "DELETE") { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } if (request.Path.ToString() != "/info") { response.StatusCode = (int)HttpStatusCode.NotFound; return; } var output = new ReplyDoc() { Value1 = request.Headers["arg1"], Value2 = request.Headers["arg2"] }; response.ContentType = "application/json"; await response.WriteAsync(NeonHelper.JsonSerialize(output)); })) { using (var jsonClient = new JsonClient()) { var headers = new ArgDictionary() { { "arg1", "test1" }, { "arg2", "test2" } }; var reply = (await jsonClient.DeleteAsync(baseUri + "info", headers: headers)).As <ReplyDoc>(); Assert.Equal("test1", reply.Value1); Assert.Equal("test2", reply.Value2); } } }
/// <summary> /// Gets a range query result from the Prometheus API. /// </summary> /// <param name="query"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="stepSize"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <PrometheusResponse <PrometheusMatrixResult> > QueryRangeAsync( string query, DateTime start, DateTime end, string stepSize = "15s", CancellationToken cancellationToken = default) { var args = new ArgDictionary(); args.Add("query", query); args.Add("start", start.ToString("yyyy-MM-dd'T'HH:mm:ss.fffZ", DateTimeFormatInfo.InvariantInfo)); args.Add("end", end.ToString("yyyy-MM-dd'T'HH:mm:ss.fffZ", DateTimeFormatInfo.InvariantInfo)); args.Add("step", stepSize); return(await GetAsync <PrometheusResponse <PrometheusMatrixResult> >("api/v1/query_range", args, cancellationToken)); }
/// <summary> /// Returns all data from an api endpoint from all pages. /// </summary> /// <param name="url"></param> /// <param name="cancellationToken"></param> /// <param name="args"></param> /// <returns></returns> public async Task <IEnumerable <T> > GetListAsync <T>(string url, ArgDictionary args = null, CancellationToken cancellationToken = default(CancellationToken)) { if (args == null) { args = new ArgDictionary(); } if (args.ContainsKey("limit")) { args.Remove("limit"); } args.Add("limit", pageSize); var data = new List <T>(); var response = await _jsonClient.GetAsync <dynamic>(url, args, cancellationToken : cancellationToken); var total = (int)response.total_count; while (response != null) { var s = NeonHelper.JsonSerialize(response); foreach (dynamic elem in response.data) { T elemObject = JsonConvert.DeserializeObject <T>(Convert.ToString(elem)); data.Add(elemObject); } // get the next page if (total > data.Count) { if (args.ContainsKey("offset")) { args.Remove("offset"); } args.Add("offset", data.Count.ToString()); response = await _jsonClient.GetAsync <dynamic>(url, args, cancellationToken : cancellationToken); } else { response = null; } } return(data); }
public void Parse(BehaviorConfiguration config, params string[] args) { map = new ArgDictionary<BehaviorConfiguration>(config) { {"resultfile", (b,a) => b.ResultFile = Split(a)}, {"include", (b,a) => b.IncludeTags = Split(a).Split(",".ToCharArray()).ToList()}, {"exclude", (b,a) => b.ExcludeTags = Split(a).Split(",".ToCharArray()).ToList()}, {"datapath", (b,a) => b.DataPath = Split(a)}, {"host", (b,a) => b.Host = Split(a)}, {"fixture", (b,a) => b.FixtureType = Split(a)}, {"context", (b,a) => b.FixtureContext = Split(a)}, {"delay", (b,a) => b.GuiDelay = Split(a)}, {"islocal", (b,a) => b.IsLocal = SplitBool(a)} }; map.ParseAndExecute(args); AddTestVariables(config, args); }
public WizardForm(ArgDictionary args) { InitializeComponent(); Arguments = args; CurrentStep = Arguments.TryGetInteger("CurrentStep", 1); TotalStep = Arguments.TryGetInteger("TotalStep", 1); // 若某個匯入程式不使用「進階設定」的畫面,則匯入精靈的畫面之總數要減「1」 ImportWizard mImportWizard = Arguments["EMBA.ImportWizard"] as ImportWizard; //if (mImportWizard.ShowAdvancedForm == false) TotalStep -= 1; if (TotalStep == 1 || CurrentStep == 1) btnPrevious.Enabled = false; if (CurrentStep == TotalStep) btnNext.Text = "完成"; }
/// <summary> /// 建构式,传入精灵参数 /// </summary> /// <param name="args"></param> public SelectValidate(ArgDictionary args) : base(args) { InitializeComponent(); //接口初始化设定 NextButtonTitle = "开始汇入"; NextButtonEnabled = false; btnViewResult.Enabled = false; //将精灵参数存起来用 mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["ImportWizard"] as ImportWizard; mImportWizard.ImportOption = mImportOption; mImportWizard.LoadRule(); mImportWizard.ValidateRule.Save(Constants.ValidationRulePath); mResultFilename = Path.Combine(Constants.ValidationReportsFolder, Path.GetFileNameWithoutExtension(mImportOption.SelectedDataFile) + "(验证报告).xls"); this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名称(目前页数/总页数) #region 初始化事件 //加入可停止执行的事件内容 lnkCancelValid.Click += (sender, e) => worker.CancelAsync(); //加入检查验证结果程序代码 btnViewResult.Click += (sender, e) => { try { Process.Start(mResultFilename); } catch (Exception ex) { FISCA.Presentation.Controls.MsgBox.Show(ex.Message); } }; #endregion StartValidate(); }
/// <summary> /// Performs an HTTP <b>PATCH</b> using a specific <see cref="IRetryPolicy"/> and ensuring that /// a success code was returned. /// </summary> /// <param name="retryPolicy">The retry policy or <c>null</c> to disable retries.</param> /// <param name="uri">The URI</param> /// <param name="document">The optional object to be uploaded as the request payload.</param> /// <param name="args">The optional query arguments.</param> /// <param name="headers">The Optional HTTP headers.</param> /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param> /// <param name="logActivity">The optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The <see cref="JsonResponse"/>.</returns> /// <exception cref="SocketException">Thrown for network connectivity issues.</exception> /// <exception cref="HttpException">Thrown when the server responds with an HTTP error status code.</exception> public async Task <JsonResponse> PatchAsync( IRetryPolicy retryPolicy, string uri, object document = null, ArgDictionary args = null, ArgDictionary headers = null, CancellationToken cancellationToken = default, LogActivity logActivity = default) { await SyncContext.ClearAsync; Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(uri), nameof(uri)); retryPolicy = retryPolicy ?? NoRetryPolicy.Instance; return(await retryPolicy.InvokeAsync( async() => { var requestUri = FormatUri(uri, args); try { var client = this.HttpClient; if (client == null) { throw new ObjectDisposedException(nameof(JsonClient)); } var httpResponse = await client.PatchAsync(requestUri, CreateContent(document), cancellationToken: cancellationToken, headers: headers, activity: logActivity); var jsonResponse = new JsonResponse(requestUri, httpResponse, await httpResponse.Content.ReadAsStringAsync()); jsonResponse.EnsureSuccess(); return jsonResponse; } catch (HttpRequestException e) { throw new HttpException(e, requestUri); } })); }
/// <summary> /// 建构式,传入精灵参数 /// </summary> /// <param name="args"></param> public SelectImport(ArgDictionary args) : base(args) { InitializeComponent(); this.PreviousButtonVisible = false; this.NextButtonTitle = "完成"; this.NextButtonEnabled = false; //将精灵参数存起来用 mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["ImportWizard"] as ImportWizard; mValidatedInfo = mArgs["ValidatedInfo"] as ValidatedInfo; mImportName = mImportWizard.ValidateRule.Root.GetAttributeText("Name"); this.Text = mImportName + "-" + this.Text; this.Text += "(5/5)"; //功能名称(目前页数/总页数) //this.TitleText += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名称(目前页数/总页数) }
/// <summary> /// Performs an HTTP <b>DELETE</b> returning a specific type and ensuring that a success cxode was returned. /// </summary> /// <typeparam name="TResult">The desired result type.</typeparam> /// <param name="uri">The URI</param> /// <param name="args">The optional query arguments.</param> /// <param name="headers">The Optional HTTP headers.</param> /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param> /// <param name="logActivity">The optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The <see cref="JsonResponse"/>.</returns> /// <exception cref="SocketException">Thrown for network connectivity issues.</exception> /// <exception cref="HttpException">Thrown when the server responds with an HTTP error status code.</exception> public async Task <TResult> DeleteAsync <TResult>( string uri, ArgDictionary args = null, ArgDictionary headers = null, CancellationToken cancellationToken = default, LogActivity logActivity = default) { await SyncContext.Clear; Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(uri), nameof(uri)); var result = await safeRetryPolicy.InvokeAsync( async() => { var requestUri = FormatUri(uri, args); try { var client = this.HttpClient; if (client == null) { throw new ObjectDisposedException(nameof(JsonClient)); } var httpResponse = await client.DeleteAsync(requestUri, cancellationToken: cancellationToken, headers: headers, activity: logActivity); var jsonResponse = new JsonResponse(requestUri, "DELETE", httpResponse, await httpResponse.Content.ReadAsStringAsync()); jsonResponse.EnsureSuccess(); return(jsonResponse); } catch (HttpRequestException e) { throw new HttpException(e, "DELETE", requestUri); } }); return(result.As <TResult>()); }
/// <summary> /// 建構式,傳入精靈參數 /// </summary> /// <param name="args"></param> public SelectValidate(ArgDictionary args) : base(args) { InitializeComponent(); //將精靈參數存起來用 mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["EMBA.ImportWizard"] as ImportWizard; mResultFilename = Path.Combine(Constants.ValidationReportsFolder, Path.GetFileNameWithoutExtension(mImportOption.SelectedDataFile) + "(驗證報告).xls"); this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名稱(目前頁數/總頁數) // 若某個匯入程式不使用「進階設定」的畫面,則「下一步」要變更為「開始匯入」 if (!mImportWizard.ShowAdvancedForm) NextButtonTitle = "開始匯入"; NextButtonEnabled = false; btnViewResult.Enabled = false; #region 初始化事件 //加入可停止執行的事件內容 lnkCancelValid.Click += (sender, e) => worker.CancelAsync(); //加入檢查驗證結果程式碼 btnViewResult.Click += (sender, e) => { try { Process.Start(mResultFilename); } catch (Exception ex) { FISCA.Presentation.Controls.MsgBox.Show(ex.Message); } }; #endregion StartValidate(); }
/// <summary> /// Performs an HTTP <b>HEAD</b> ensuring that a success code was returned. /// </summary> /// <param name="uri">The URI</param> /// <param name="document">The optional object to be uploaded as the request payload.</param> /// <param name="args">The optional query arguments.</param> /// <param name="headers">The Optional HTTP headers.</param> /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param> /// <param name="logActivity">The optional <see cref="LogActivity"/> whose ID is to be included in the request.</param> /// <returns>The tracking <see cref="Task"/>.</returns> /// <exception cref="SocketException">Thrown for network connectivity issues.</exception> /// <exception cref="HttpException">Thrown when the server responds with an HTTP error status code.</exception> public async Task HeadAsync( string uri, object document = null, ArgDictionary args = null, ArgDictionary headers = null, CancellationToken cancellationToken = default, LogActivity logActivity = default) { Covenant.Requires <ArgumentNullException>(!string.IsNullOrEmpty(uri)); await safeRetryPolicy.InvokeAsync( async() => { var requestUri = FormatUri(uri, args); try { var client = this.HttpClient; if (client == null) { throw new ObjectDisposedException(nameof(JsonClient)); } var httpResponse = await client.HeadAsync(requestUri, CreateContent(document), cancellationToken: cancellationToken, headers: headers, activity: logActivity); var jsonResponse = new JsonResponse(requestUri, httpResponse, null); jsonResponse.EnsureSuccess(); return(jsonResponse); } catch (HttpRequestException e) { throw new HttpException(e, requestUri); } }); }
/// <summary> /// 建構式,傳入精靈參數 /// </summary> /// <param name="args"></param> public SelectImport(ArgDictionary args) : base(args) { InitializeComponent(); this.PreviousButtonVisible = false; this.NextButtonTitle = "完成"; this.NextButtonEnabled = false; //將精靈參數存起來用 mArgs = args; mImportOption = mArgs["ImportOption"] as ImportFullOption; mImportWizard = mArgs["EMBA.ImportWizard"] as ImportWizard; mValidatedInfo = mArgs["ValidatedInfo"] as ValidatedInfo; mImportName = mImportWizard.ValidateRule.Root.GetAttributeText("Name"); this.Text = mImportName + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名稱(目前頁數/總頁數) this.txtResult.Text = "匯入中…"; this.btnViewResult.Visible = false; this.btnAgent.Visible = false; //this.TitleText += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名稱(目前頁數/總頁數) }
/// <summary> /// 建构式,传入精灵选项 /// </summary> /// <param name="args"></param> public SelectSource(ArgDictionary args) : base(args) { InitializeComponent(); //初始化参数 mArgs = args; mImportWizard = args["ImportWizard"] as ImportWizard; mImportOption = TryGetOption(); mImportName = mImportWizard.ValidateRule.Root.GetAttributeText("Name"); mImportWizard.ImportOption = mImportOption; this.Text = mImportName + "-选择档案与汇入方式" + "(" + CurrentStep + "/" + TotalStep + ")"; //加载验证规则及XSLT LoadValudateRule(); //在使用者选择数据表时,将数据表的字段都记录下来 lstSheetNames.SelectedIndexChanged += (sender, e) => { mSheetHelper.SwitchSeet("" + lstSheetNames.SelectedItem); mImportOption.SelectedSheetName = "" + lstSheetNames.SelectedItem; mImportOption.SheetFields = mSheetHelper.Fields; this.NextButtonEnabled = ValidateNext(); }; //检视验证规则 btnViewRule.Click += (sender, e) => { XmlViewForm ViewForm = new XmlViewForm(); ViewForm.PopXml(mImportName, mImportOption.SelectedValidateFile); ViewForm.ShowDialog(); }; //检视填表说明 btnViewRuleExcel.Click += (sender, e) => { Workbook book = new Workbook(); string BookAndSheetName = mImportName + "(空白表格)"; if (!string.IsNullOrEmpty(BookAndSheetName)) book.Worksheets[0].Name = BookAndSheetName; int Position = 0; foreach (XElement Element in mImportWizard.ValidateRule.Root.Element("FieldList").Elements("Field")) { StringBuilder strCommentBuilder = new StringBuilder(); string Name = Element.GetAttributeText("Name"); bool Required = Element.GetAttributeBool("Required", false); book.Worksheets[0].Cells[0, Position].PutValue(Name); book.Worksheets[0].Cells[0, Position].Style.HorizontalAlignment = TextAlignmentType.Center; book.Worksheets[0].Cells[0, Position].Style.VerticalAlignment = TextAlignmentType.Center; if (Required) { book.Worksheets[0].Cells[0, Position].Style.BackgroundColor = System.Drawing.Color.Red; strCommentBuilder.AppendLine("此为必要字段。"); } foreach (XElement SubElement in Element.Elements("Validate")) strCommentBuilder.AppendLine(SubElement.GetAttributeText("Description")); book.Worksheets[0].Comments.Add(0, (byte)Position); book.Worksheets[0].Comments[0, Position].Note = strCommentBuilder.ToString(); book.Worksheets[0].Comments[0, Position].WidthInch = 3; Position++; } book.Worksheets[0].AutoFitColumns(); Campus.Report.ReportSaver.SaveWorkbook(book, Path.Combine(Constants.ValidationReportsFolder, BookAndSheetName)); }; //选择源数据档案 btnSelectFile.Click += (sender, e) => { DialogResult dr = SelectSourceFileDialog.ShowDialog(); if (dr == DialogResult.OK) { try { //记录来源文件名 string FileName = SelectSourceFileDialog.FileName; txtSourceFile.Text = SelectSourceFileDialog.FileName; mImportOption.SelectedDataFile = FileName; mSheetHelper = new SheetHelper(FileName); //将数据表列表显示在画面上 lstSheetNames.Items.Clear(); foreach (Worksheet sheet in mSheetHelper.Book.Worksheets) lstSheetNames.Items.Add(sheet.Name); lstSheetNames.SelectedIndex = 0; } catch (Exception ve) { MsgBox.Show(ve.Message); } } }; //将前一步不出现,下一步先失效 this.PreviousButtonVisible = false; this.NextButtonEnabled = false; }
public StudentBrief(ArgDictionary args) : base(args) { InitializeComponent(); XmlData = null; }
public StudentTransferAPI.WizardForm CreateForm(ArgDictionary ars) { return(new StudentBrief(ars)); }
/// <summary> /// 執行匯入功能 /// </summary> public void Execute() { try { ImportOption = new ImportOption(); LoadRule(); mFieldProcessor = new FieldProcessor(mValidateRule.Root); } catch (Exception e) { MessageBox.Show("下載驗證規則時發生錯誤,以下為詳細訊息:"+ System.Environment.NewLine +e.Message); return; } try { ArgDictionary args = new ArgDictionary(); args.SetValue("ImportWizard", this); Features.Invoke(args, mCommands.ToArray()); } catch (Exception e) { MessageBox.Show("開啟匯入表單時發生錯誤,以下為詳細訊息:"+System.Environment.NewLine+e.Message); return; } }
/// <summary> /// 建构式,传入精灵参数 /// </summary> /// <param name="args"></param> public SelectKey(ArgDictionary args) : base(args) { InitializeComponent(); mArgs = args; mImportOption = args["ImportOption"] as ImportFullOption; mImportWizard = args["ImportWizard"] as ImportWizard; this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名称(目前页数/总页数) #region 将用户可选择的键值显示在画面上 mSelectableKeyFields = args["SelectableKeyFields"] as Dictionary<string, List<string>>; int cboIdFieldLen = cboIdField.Width; foreach (List<string> KeyFields in mSelectableKeyFields.Values) { string NewItem = string.Join(",", KeyFields.ToArray()); cboIdField.Items.Add(NewItem); if (NewItem.Length > cboIdFieldLen) cboIdFieldLen = NewItem.Length; } if (cboIdField.Items.Count > 0) { cboIdField.SelectedIndex = 0; //cboIdField.Width = cboIdFieldLen; } #endregion #region 将用户可选择的数据动作 ImportAction Actions = mImportWizard.GetSupportActions(); bool IsInsert = (Actions & ImportAction.Insert) == ImportAction.Insert; bool IsUpdate = (Actions & ImportAction.Update) == ImportAction.Update; bool IsInsertOrUpdate = (Actions & ImportAction.InsertOrUpdate) == ImportAction.InsertOrUpdate; bool IsCover = (Actions & ImportAction.Cover) == ImportAction.Cover; bool IsDelete = (Actions & ImportAction.Delete) == ImportAction.Delete; if (IsInsert) lstActions.Items.Add("新增资料"); if (IsUpdate) lstActions.Items.Add("更新数据"); if (IsInsertOrUpdate) lstActions.Items.Add("新增或更新数据"); if (IsCover) lstActions.Items.Add("覆盖数据"); lstActions.SelectedIndexChanged += (sender, e) => { switch ("" + lstActions.SelectedItem) { case "新增资料": lblImportActionMessage.Text = "此选项是将所有数据新增到数据库中,不会对现有的数据进行任何修改动作。"; break; case "更新数据": lblImportActionMessage.Text = "此选项将修改数据库中的现有数据,会依据您所指定的识别栏修改数据库中具有相同识别的数据。"; break; case "新增或更新数据": lblImportActionMessage.Text = "此选项是将数据新增或更新到数据库中,会针对您的数据来自动判断新增或更新。"; break; case "覆盖数据": lblImportActionMessage.Text = "此选项是将数据库中的数据都先删除再全部新增"; break; case "删除数据": lblImportActionMessage.Text = "此选项将依汇入数据中的键值删除数据库中的现有数据,请您务必小心谨慎使用。"; break; }; }; lstActions.KeyDown += (sender, e) => { if (e.KeyData == System.Windows.Forms.Keys.Delete) if (IsDelete) lstActions.Items.Add("删除数据"); }; lstActions.SelectedIndex = 0; #endregion }
public void Validate2NumArgsTest(bool valid) { DefArgs defArgs = new DefArgs(); Arg newArg = new Arg("", true, 0, false); defArgs.Add(newArg, false); IArgDictionary<string,string[]> args = new ArgDictionary<string, string[]>(); args.Add("", valid ? new string[] { } : new[] { "abc" }); Assert.AreEqual(valid, defArgs.Validate(args)); }
public async Task PostUnsafeAsync_Headers() { // Ensure that POST with query arguments work. RequestDoc requestDoc = null; using (new MockHttpServer(baseUri, async context => { var request = context.Request; var response = context.Response; if (request.Method != "POST") { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } if (request.Path.ToString() != "/info") { response.StatusCode = (int)HttpStatusCode.NotFound; return; } requestDoc = NeonHelper.JsonDeserialize <RequestDoc>(request.GetBodyText()); var output = new ReplyDoc() { Value1 = request.Headers["arg1"], Value2 = request.Headers["arg2"] }; response.ContentType = "application/json"; await response.WriteAsync(NeonHelper.JsonSerialize(output)); })) { using (var jsonClient = new JsonClient()) { var headers = new ArgDictionary() { { "arg1", "test1" }, { "arg2", "test2" } }; var doc = new RequestDoc() { Operation = "FOO", Arg0 = "Hello", Arg1 = "World" }; var reply = (await jsonClient.PostUnsafeAsync(baseUri + "info", doc, headers: headers)).As <ReplyDoc>(); Assert.Equal("test1", reply.Value1); Assert.Equal("test2", reply.Value2); Assert.Equal("FOO", requestDoc.Operation); Assert.Equal("Hello", requestDoc.Arg0); Assert.Equal("World", requestDoc.Arg1); } }; }
/// <summary> /// 建構式,傳入精靈參數 /// </summary> /// <param name="args"></param> public SelectKey(ArgDictionary args) : base(args) { InitializeComponent(); mArgs = args; mImportOption = args["ImportOption"] as ImportFullOption; mImportWizard = args["EMBA.ImportWizard"] as ImportWizard; this.Text = mImportWizard.ValidateRule.Root.GetAttributeText("Name") + "-" + this.Text; this.Text += "(" + CurrentStep + "/" + TotalStep + ")"; //功能名稱(目前頁數/總頁數) #region 將使用者可選擇的鍵值顯示在畫面上 mSelectableKeyFields = args["SelectableKeyFields"] as Dictionary<string, List<string>>; int cboIdFieldLen = cboIdField.Width; foreach (string key in mSelectableKeyFields.Keys) { ComboItem item = new ComboItem(key); item.Tag = mSelectableKeyFields[key]; cboIdField.Items.Add(item); if (key.Length > cboIdFieldLen) cboIdFieldLen = key.Length; } if (cboIdField.Items.Count > 0) { cboIdField.SelectedIndex = 0; //cboIdField.Width = cboIdFieldLen; } #endregion #region 將使用者可選擇的資料動作 ImportAction Actions = mImportWizard.GetSupportActions(); bool IsInsert = (Actions & ImportAction.Insert) == ImportAction.Insert; bool IsUpdate = (Actions & ImportAction.Update) == ImportAction.Update; bool IsInsertOrUpdate = (Actions & ImportAction.InsertOrUpdate) == ImportAction.InsertOrUpdate; bool IsCover = (Actions & ImportAction.Cover) == ImportAction.Cover; bool IsDelete = (Actions & ImportAction.Delete) == ImportAction.Delete; if (IsInsert) lstActions.Items.Add("新增資料"); if (IsUpdate) lstActions.Items.Add("更新資料"); if (IsInsertOrUpdate) lstActions.Items.Add("新增或更新資料"); if (IsCover) lstActions.Items.Add("覆蓋資料"); lstActions.SelectedIndexChanged += (sender, e) => { switch ("" + lstActions.SelectedItem) { case "新增資料": lblImportActionMessage.Text = "此選項是將所有資料新增到資料庫中,不會對現有的資料進行任何修改動作。"; break; case "更新資料": lblImportActionMessage.Text = "此選項將修改資料庫中的現有資料,會依據您所指定的識別欄修改資料庫中具有相同識別的資料。"; break; case "新增或更新資料": lblImportActionMessage.Text = "此選項是將資料新增或更新到資料庫中,會針對您的資料來自動判斷新增或更新。"; break; case "覆蓋資料": lblImportActionMessage.Text = "此選項是將資料庫中的資料都先刪除再全部新增"; break; case "刪除資料": lblImportActionMessage.Text = "此選項將依匯入資料中的鍵值刪除資料庫中的現有資料,請您務必小心謹慎使用。"; break; }; }; lstActions.KeyDown += (sender, e) => { if (e.KeyData == System.Windows.Forms.Keys.Delete) if (IsDelete) lstActions.Items.Add("刪除資料"); }; lstActions.SelectedIndex = 0; #endregion }
public SearchSettings SettingsFromArgs(IEnumerable <string> args) { // default to PrintResults = true since this is called from CLI functionality var settings = new SearchSettings { PrintResults = true }; var queue = new Queue <string>(args); while (queue.Count > 0) { var s = queue.Dequeue(); if (s.StartsWith("-")) { try { while (s.StartsWith("-")) { s = s.Substring(1); } } catch (InvalidOperationException e) { throw new SearchException(e.Message); } if (string.IsNullOrWhiteSpace(s)) { throw new SearchException("Invalid option: -"); } if (ArgDictionary.ContainsKey(s)) { try { ((SearchArgOption)ArgDictionary[s]).Action(queue.Dequeue(), settings); } catch (InvalidOperationException e) { throw new SearchException(e.Message); } } else if (FlagDictionary.ContainsKey(s)) { try { ((SearchFlagOption)FlagDictionary[s]).Action(true, settings); } catch (InvalidOperationException e) { throw new SearchException(e.Message); } } else { throw new SearchException("Invalid option: " + s); } } else { settings.StartPath = s; } } return(settings); }
/// <summary> /// 建構式,傳入精靈選項 /// </summary> /// <param name="args"></param> public SelectSource(ArgDictionary args) : base(args) { InitializeComponent(); //初始化參數 mArgs = args; mImportWizard = args["EMBA.ImportWizard"] as ImportWizard; mImportOption = TryGetOption(); mImportName = mImportWizard.ValidateRule.Root.GetAttributeText("Name"); this.Text = mImportName + "-選擇檔案與匯入方式" + "(" + CurrentStep + "/" + TotalStep + ")"; //載入驗證規則及XSLT LoadValudateRule(); //在使用者選擇資料表時,將資料表的欄位都記錄下來 lstSheetNames.SelectedIndexChanged += (sender, e) => { mSheetHelper.SwitchSeet("" + lstSheetNames.SelectedItem); mImportOption.SelectedSheetName = "" + lstSheetNames.SelectedItem; mImportOption.SheetFields = mSheetHelper.Fields; this.NextButtonEnabled = ValidateNext(); }; //檢視驗證規則 btnViewRule.Click += (sender, e) => { XmlViewForm ViewForm = new XmlViewForm(); ViewForm.PopXml(mImportName,mImportOption.SelectedValidateFile); ViewForm.ShowDialog(); }; //檢視填表說明 btnViewRuleExcel.Click += (sender, e) => { Workbook book = new Workbook(); string BookAndSheetName = mImportName +"(空白表格)"; if (!string.IsNullOrEmpty(BookAndSheetName)) book.Worksheets[0].Name = BookAndSheetName; int Position = 0; foreach (XElement Element in mImportWizard.ValidateRule.Root.Element("FieldList").Elements("Field")) { StringBuilder strCommentBuilder = new StringBuilder(); string Name = Element.GetAttributeText("Name"); bool Required = Element.GetAttributeBool("Required",false); book.Worksheets[0].Cells[0, Position].PutValue(Name); book.Worksheets[0].Cells[0, Position].Style.HorizontalAlignment = TextAlignmentType.Center; book.Worksheets[0].Cells[0, Position].Style.VerticalAlignment = TextAlignmentType.Center; if (Required) { book.Worksheets[0].Cells[0, Position].Style.BackgroundColor = System.Drawing.Color.Red; strCommentBuilder.AppendLine("此為必要欄位。"); } foreach(XElement SubElement in Element.Elements("Validate")) strCommentBuilder.AppendLine(SubElement.GetAttributeText("Description")); book.Worksheets[0].Comments.Add(0,(byte)Position); book.Worksheets[0].Comments[0,Position].Note = strCommentBuilder.ToString() ; book.Worksheets[0].Comments[0, Position].WidthInch = 3; Position++; } book.Worksheets[0].AutoFitColumns(); // 開啟「空白格式」匯入檔 string emptyTemplateFile = Path.Combine(Constants.ValidationReportsFolder, BookAndSheetName + ".xls"); try { book.Save(emptyTemplateFile); Process.Start(emptyTemplateFile); } catch (Exception ex) { FISCA.Presentation.Controls.MsgBox.Show(ex.Message); } }; //選擇來源資料檔案 btnSelectFile.Click += (sender, e) => { DialogResult dr = SelectSourceFileDialog.ShowDialog(); if (dr == DialogResult.OK) { try { //記錄來源檔案名稱 string FileName = SelectSourceFileDialog.FileName; txtSourceFile.Text = SelectSourceFileDialog.FileName; mImportOption.SelectedDataFile = FileName; mSheetHelper = new SheetHelper(FileName); //將資料表列表顯示在畫面上 lstSheetNames.Items.Clear(); foreach (Worksheet sheet in mSheetHelper.Book.Worksheets) lstSheetNames.Items.Add(sheet.Name); lstSheetNames.SelectedIndex = 0; } catch (Exception ve) { MsgBox.Show(ve.Message); } } }; //將前一步不出現,下一步先失效 this.PreviousButtonVisible = false; this.NextButtonEnabled = false; }
public void Validate2RequiredTest(bool valid) { DefArgs defArgs = new DefArgs(); Arg newArg = new Arg("p", !valid, 0, false); defArgs.Add(newArg, false); IArgDictionary<string, string[]> args = new ArgDictionary<string, string[]>(); args.Add("", new string[] { }); Assert.AreEqual(valid, defArgs.Validate(args)); }