/// <summary>Gets the success response.</summary> /// <returns>The response.</returns> protected KeyValuePair <string, SwaggerResponse> GetSuccessResponse() { if (_operation.ActualResponses.Any(r => r.Key == "200")) { return(new KeyValuePair <string, SwaggerResponse>("200", _operation.ActualResponses.Single(r => r.Key == "200").Value)); } var response = _operation.ActualResponses.FirstOrDefault(r => HttpUtilities.IsSuccessStatusCode(r.Key)); if (response.Value != null) { return(new KeyValuePair <string, SwaggerResponse>(response.Key, response.Value)); } return(new KeyValuePair <string, SwaggerResponse>("default", _operation.ActualResponses.FirstOrDefault(r => r.Key == "default").Value)); }
/// <summary>Gets the success response.</summary> /// <returns>The response.</returns> protected SwaggerResponse GetSuccessResponse() { if (_operation.ActualResponses.Any(r => r.Key == "200")) { return(_operation.ActualResponses.Single(r => r.Key == "200").Value); } var response = _operation.ActualResponses.FirstOrDefault(r => HttpUtilities.IsSuccessStatusCode(r.Key)).Value; if (response != null) { return(response); } return(_operation.ActualResponses.FirstOrDefault(r => r.Key == "default").Value); }
/// <summary> /// Determines whether an item by the specified path is published. /// </summary> /// <param name="path">The path of the item.</param> public void IsPublishedAsync(string path) { try { var request = HttpUtilities.CreateRequest(this.accessToken, path); request.Method = WebdavResources.PropfindMethod; var requestState = new RequestState { Request = request, RequestArgument = WebdavResources.CheckPublishingBody }; HttpUtilities.SendFullRequest(requestState, this.ProcessIsPublishedResponse); } catch (Exception ex) { this.IsPublishedCompleted.SafeInvoke(this, new GenericSdkEventArgs <string>(HttpUtilities.ProcessException(ex))); } }
/// <summary> /// UnPublishes an item by the specified path. /// </summary> /// <param name="path">The path of the item.</param> public void UnpublishAsync(string path) { try { var request = HttpUtilities.CreateRequest(this.accessToken, path); request.Method = WebdavResources.ProppatchMethod; var requestState = new RequestState { Request = request, RequestArgument = WebdavResources.UnpublishBody }; HttpUtilities.SendFullRequest(requestState, this.ProcessUnpublishResponse); } catch (Exception ex) { this.UnpublishCompleted.SafeInvoke(this, new SdkEventArgs(HttpUtilities.ProcessException(ex))); } }
/// <summary> /// Gets the disk item's information. /// </summary> /// <param name="path">The path to the specified item.</param> public void GetItemInfoAsync(string path) { try { var request = HttpUtilities.CreateRequest(this.accessToken, path); request.Method = WebdavResources.PropfindMethod; var requestState = new RequestState { Request = request, ResponseArgument = path, RequestArgument = WebdavResources.ItemDetailsBody }; HttpUtilities.SendFullRequest(requestState, this.ProcessGetItemInfoResponse); } catch (Exception ex) { this.GetItemInfoCompleted.SafeInvoke(this, new GenericSdkEventArgs <DiskItemInfo>(HttpUtilities.ProcessException(ex))); } }
internal SwaggerResponse GetSuccessResponse(SwaggerOperation operation) { if (operation.Responses.Any(r => r.Key == "200")) { return(operation.Responses.Single(r => r.Key == "200").Value); } var response = operation.Responses.FirstOrDefault(r => HttpUtilities.IsSuccessStatusCode(r.Key)).Value; if (response != null) { return(response); } return(operation.Responses.FirstOrDefault(r => r.Key == "default").Value); }
/// <summary> /// Converts this HTTP request into a CloudEvent object, with the given extensions, /// overriding the formatter. /// </summary> /// <param name="httpRequest">HTTP request</param> /// <param name="formatter">The event formatter to use to process the request body.</param> /// <param name="extensions">List of extension instances</param> /// <returns>A CloudEvent instance or 'null' if the request message doesn't hold a CloudEvent</returns> public static async ValueTask <CloudEvent> ReadCloudEventAsync(this HttpRequest httpRequest, ICloudEventFormatter formatter, params CloudEventAttribute[] extensionAttributes) { if (HasCloudEventsContentType(httpRequest)) { // TODO: Handle formatter being null return(await formatter.DecodeStructuredEventAsync(httpRequest.Body, extensionAttributes).ConfigureAwait(false)); } else { var headers = httpRequest.Headers; CloudEventsSpecVersion version = CloudEventsSpecVersion.Default; if (headers.TryGetValue(HttpUtilities.SpecVersionHttpHeader, out var values)) { string versionId = values.First(); version = CloudEventsSpecVersion.FromVersionId(versionId); } var cloudEvent = new CloudEvent(version, extensionAttributes); foreach (var header in headers) { string attributeName = HttpUtilities.GetAttributeNameFromHeaderName(header.Key); if (attributeName is null || attributeName == CloudEventsSpecVersion.SpecVersionAttribute.Name) { continue; } string attributeValue = HttpUtilities.DecodeHeaderValue(header.Value.First()); cloudEvent.SetAttributeFromString(attributeName, attributeValue); } cloudEvent.DataContentType = httpRequest.ContentType; if (httpRequest.Body is Stream body) { // TODO: This is a bit ugly. var memoryStream = new MemoryStream(); await body.CopyToAsync(memoryStream).ConfigureAwait(false); if (memoryStream.Length != 0) { cloudEvent.Data = formatter.DecodeData(memoryStream.ToArray(), cloudEvent.DataContentType); } } return(cloudEvent); } }
/// <summary> /// Converts this HTTP request into a CloudEvent object. /// </summary> /// <param name="httpRequest">The HTTP request to decode. Must not be null.</param> /// <param name="formatter">The event formatter to use to process the request body. Must not be null.</param> /// <param name="extensionAttributes">The extension attributes to use when populating the CloudEvent. May be null.</param> /// <returns>The decoded CloudEvent.</returns> /// <exception cref="ArgumentException">The request does not contain a CloudEvent.</exception> public static async Task <CloudEvent> ToCloudEventAsync( this HttpRequest httpRequest, CloudEventFormatter formatter, IEnumerable <CloudEventAttribute> extensionAttributes) { Validation.CheckNotNull(httpRequest, nameof(httpRequest)); Validation.CheckNotNull(formatter, nameof(formatter)); if (HasCloudEventsContentType(httpRequest)) { var contentType = MimeUtilities.CreateContentTypeOrNull(httpRequest.ContentType); return(await formatter.DecodeStructuredModeMessageAsync(httpRequest.Body, contentType, extensionAttributes).ConfigureAwait(false)); } else { var headers = httpRequest.Headers; headers.TryGetValue(HttpUtilities.SpecVersionHttpHeader, out var versionId); var version = CloudEventsSpecVersion.FromVersionId(versionId.FirstOrDefault()) ?? throw new ArgumentException($"Unknown CloudEvents spec version '{versionId}'", nameof(httpRequest)); if (version is null) { throw new ArgumentException($"Unsupported CloudEvents spec version '{versionId.First()}'"); } var cloudEvent = new CloudEvent(version, extensionAttributes); foreach (var header in headers) { string attributeName = HttpUtilities.GetAttributeNameFromHeaderName(header.Key); if (attributeName is null || attributeName == CloudEventsSpecVersion.SpecVersionAttribute.Name) { continue; } string attributeValue = HttpUtilities.DecodeHeaderValue(header.Value.First()); cloudEvent.SetAttributeFromString(attributeName, attributeValue); } cloudEvent.DataContentType = httpRequest.ContentType; if (httpRequest.Body is Stream body) { byte[] data = await BinaryDataUtilities.ToByteArrayAsync(body).ConfigureAwait(false); formatter.DecodeBinaryModeEventData(data, cloudEvent); } return(Validation.CheckCloudEventArgument(cloudEvent, nameof(httpRequest))); } }
/// <summary> /// Calls the token endpoint to obtain an access token. /// </summary> /// <param name="body">The request body.</param> protected void CallTokenEndpoint(string body) { WebRequest request = HttpUtilities.BuildRequest(TOKEN_ENDPOINT, "POST", config); request.ContentType = "application/x-www-form-urlencoded"; LogEntry logEntry = new LogEntry(config, new DefaultDateTimeProvider()); WebResponse response = null; try { HttpUtilities.WritePostBodyAndLog(request, body, logEntry, REQUEST_HEADERS_TO_MASK); response = request.GetResponse(); string contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream()); logEntry.LogResponse(new ResponseInfo(response, contents), false, RESPONSE_FIELDS_TO_MASK, new JsonBodyFormatter()); logEntry.Flush(); Dictionary <string, string> values = ParseJsonObjectResponse(contents); this.AccessToken = CollectionUtilities.TryGetValue(values, "access_token", this.AccessToken); this.RefreshToken = CollectionUtilities.TryGetValue(values, "refresh_token", this.RefreshToken); this.tokenType = CollectionUtilities.TryGetValue(values, "token_type", this.tokenType); this.expiresIn = int.Parse( CollectionUtilities.TryGetValue(values, "expires_in", this.expiresIn.ToString())); this.updatedOn = DateTime.UtcNow; if (this.OnOAuthTokensObtained != null) { this.OnOAuthTokensObtained(this); } } catch (WebException e) { string contents = HttpUtilities.GetErrorResponseBody(e); logEntry.LogResponse(new ResponseInfo(response, contents), true, RESPONSE_FIELDS_TO_MASK, new JsonBodyFormatter()); logEntry.Flush(); throw new ApplicationException(contents, e); } finally { if (response != null) { response.Close(); } } }
public IHttpActionResult AssignUnAssignRolesToUser(RolesToUserRequest requestList) { try { string currentUserEmail = HttpUtilities.GetUserNameFromToken(this.Request); ValidationUtilities.ValidateAssignUnAssignRolesToUser(requestList); //Get Existing users of the role List <UserRoleMap> dbexistingRoles = context.UserRoleMaps.Where(i => i.UserId == requestList.UserId && i.Deleted == false).ToList(); foreach (var itemRole in requestList.RoleIds) { if (dbexistingRoles.FirstOrDefault(i => i.RoleId == itemRole && i.UserId == requestList.UserId) == null) { // if does not exists then only add it. context.UserRoleMaps.Add(new UserRoleMap() { Id = Guid.NewGuid().ToString(), RoleId = itemRole, UserId = requestList.UserId, CreatedBy = currentUserEmail }); } } //remove existing mapping if they dont exists in the input foreach (var itemRole in dbexistingRoles) { if (requestList != null && requestList.RoleIds != null) { if (!requestList.RoleIds.Contains(itemRole.RoleId)) { itemRole.Deleted = true; context.Entry(itemRole).State = System.Data.Entity.EntityState.Modified; } } } context.SaveChanges(); return(Ok()); } catch (HttpResponseException ex) { throw ex; } catch (Exception ex) { HttpUtilities.ServerError(ex, Request); return(null); } }
/// <summary> /// Builds an HTTP request for downloading reports. /// </summary> /// <param name="downloadUrl">The download url.</param> /// <param name="postBody">The POST body.</param> /// <param name="logEntry">The logEntry to write the HTTP logs.</param> /// <returns>A webrequest to download reports.</returns> private HttpWebRequest BuildRequest(string downloadUrl, string postBody, LogEntry logEntry) { AdWordsAppConfig config = this.User.Config as AdWordsAppConfig; HttpWebRequest request = (HttpWebRequest)HttpUtilities.BuildRequest(downloadUrl, "POST", config); request.Headers.Add("clientCustomerId: " + config.ClientCustomerId); request.ContentType = "application/x-www-form-urlencoded"; if (this.User.OAuthProvider != null) { request.Headers["Authorization"] = this.User.OAuthProvider.GetAuthHeader(); } else { throw new AdWordsApiException(null, AdWordsErrorMessages.OAuthProviderCannotBeNull); } request.Headers.Add("developerToken: " + config.DeveloperToken); // The client library will use only apiMode = true. request.Headers.Add("apiMode", "true"); request.Headers.Add("skipReportHeader", config.SkipReportHeader.ToString().ToLower()); request.Headers.Add("skipReportSummary", config.SkipReportSummary.ToString().ToLower()); request.Headers.Add("skipColumnHeader", config.SkipColumnHeader.ToString().ToLower()); // Send the includeZeroImpressions header only if the user explicitly // requested it through the config object. if (config.IncludeZeroImpressions.HasValue) { request.Headers.Add("includeZeroImpressions", config.IncludeZeroImpressions.ToString().ToLower()); } // Send the useRawEnumValues header only if the user explicitly // requested it through the config object. if (config.UseRawEnumValues.HasValue) { request.Headers.Add("useRawEnumValues", config.UseRawEnumValues.ToString().ToLower()); } HttpUtilities.WritePostBodyAndLog(request, postBody, "reportdownload", logEntry, HEADERS_TO_MASK); return(request); }
/// <summary> /// Downloads a report to stream. /// </summary> /// <param name="downloadUrl">The download url.</param> /// <param name="postBody">The POST body.</param> private ReportResponse DownloadReport(string downloadUrl, string postBody) { AdWordsErrorHandler errorHandler = new AdWordsErrorHandler(this.User as AdWordsUser); while (true) { WebResponse response = null; HttpWebRequest request = BuildRequest(downloadUrl, postBody); LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider()); logEntry.LogRequest(request, postBody, HEADERS_TO_MASK); try { response = request.GetResponse(); logEntry.LogResponse(response, false, "Response truncated."); logEntry.Flush(); return(new ReportResponse(response)); } catch (WebException e) { Exception reportsException = null; string contents = HttpUtilities.GetErrorResponseBody(e); logEntry.LogResponse(e.Response, true, contents); logEntry.Flush(); reportsException = ParseException(e, contents); if (AdWordsErrorHandler.IsOAuthTokenExpiredError(reportsException)) { reportsException = new AdWordsCredentialsExpiredException( request.Headers["Authorization"]); } if (errorHandler.ShouldRetry(reportsException)) { errorHandler.PrepareForRetry(reportsException); } else { throw reportsException; } } finally { featureUsageRegistry.Clear(); } } }
/// <summary> /// /// </summary> /// <param name="ctx"></param> /// <param name="parentID"></param> /// <returns></returns> public Message GetAllChildren(WebOperationContext ctx, string parentID) { Message responseMsg = null; try { List <EntityLinks> entityLinks = this.GetLookup <EntityLinks>("EntityLinks", null); entityLinks.RemoveAll(x => x.ParentID != int.Parse(parentID)); responseMsg = HttpUtilities.GenerateResponse <EntityLinks>(ctx, entityLinks, this.timer); } catch (Exception ex) { responseMsg = HttpUtilities.GenerateExceptionResponse(ctx, ex, "GET", HttpStatusCode.InternalServerError); } return(responseMsg); }
public async Task ThenAllValidAndInvalidStandardsAreReturned() { if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result)) { Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]"); } var model = await HttpUtilities.ReadContent <GetStandardsListResponse>(result.Content); var standardsList = new List <Standard>(); standardsList.AddRange(DbUtilities.GetValidTestStandards()); standardsList.AddRange(DbUtilities.GetInValidTestStandards()); model.Standards.Should().BeEquivalentTo(standardsList, StandardEquivalencyAssertionOptions); model.Total.Should().Be(standardsList.Count); }
public async Task TakeStartLineThrowsWhenMethodNotAllowed(string requestLine, int intAllowedMethod) { var allowedMethod = (HttpMethod)intAllowedMethod; await _application.Output.WriteAsync(Encoding.ASCII.GetBytes(requestLine)); var readableBuffer = (await _transport.Input.ReadAsync()).Buffer; #pragma warning disable CS0618 // Type or member is obsolete var exception = Assert.Throws <BadHttpRequestException>(() => #pragma warning restore CS0618 // Type or member is obsolete _http1Connection.TakeStartLine(readableBuffer, out _consumed, out _examined)); _transport.Input.AdvanceTo(_consumed, _examined); Assert.Equal(405, exception.StatusCode); Assert.Equal(CoreStrings.BadRequest_MethodNotAllowed, exception.Message); Assert.Equal(HttpUtilities.MethodToString(allowedMethod), exception.AllowedHeader); }
public IHttpActionResult SetRolePermissions(List <RolePermReq> requestList) { try { string currentUserEmail = HttpUtilities.GetUserNameFromToken(this.Request); foreach (var item in requestList) { var existingPerm = context.RolePermissions. FirstOrDefault(i => i.FeatureId == item.FeatureId && i.RoleId == item.RoleId); if (existingPerm != null) { existingPerm.CreatePermission = item.CreatePermission == true ? "A" : "N"; existingPerm.UpdatePermission = item.UpdatePermission == true ? "A" : "N"; existingPerm.ReadPermission = item.ReadPermission == true ? "A" : "N"; existingPerm.UpdatedAt = DateTime.UtcNow; existingPerm.ModifiedBy = currentUserEmail; context.Entry(existingPerm).State = System.Data.Entity.EntityState.Modified; } else { context.RolePermissions.Add( new RolePermission() { FeatureId = item.FeatureId, RoleId = item.RoleId, CreatePermission = item.CreatePermission == true ? "A" : "N", ReadPermission = item.ReadPermission == true ? "A" : "N", UpdatePermission = item.UpdatePermission == true ? "A" : "N", DeletePermission = "N", CreatedAt = DateTime.UtcNow, CreatedBy = currentUserEmail, Id = Guid.NewGuid().ToString() } ); } context.SaveChanges(); } return(Ok()); } catch (Exception ex) { HttpUtilities.ServerError(ex, Request); return(null); } }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { context.HttpContext.Items.Remove("CurrentUser"); var user = await _mediator.Send(new GetUserBySessionOrApiKeyQuery { Session = HttpUtilities.TryGetSession(context.HttpContext) }); if (user == null) { context.Result = new UnauthorizedResult(); } else { context.HttpContext.Items["CurrentUser"] = user; } }
public async Task ThenFrameworkIsReturned() { if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result)) { Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]"); } var model = await HttpUtilities.ReadContent <GetFrameworkResponse>(result.Content); var expected = DbUtilities.GetFramework("1"); model.Should().BeEquivalentTo(expected, options => options .Excluding(frm => frm.FundingPeriods) .Excluding(frm => frm.TypicalLengthFrom) .Excluding(frm => frm.TypicalLengthTo) .Excluding(frm => frm.TypicalLengthUnit) ); }
public async Task ShouldUpdateSubscription() { var updatedSubscription = new SubscriptionUpdateDto { Name = "UpdatedFromTest", SourceTypeId = 1, Parameters = "{}", CreatedDate = DateTimeOffset.Now }; var httpContent = HttpUtilities.GetHttpContent(updatedSubscription); var response = await _client.PutAsync("/api/subscriptions/1", httpContent); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); var storageSubscription = JsonConvert.DeserializeObject <SubscriptionDto>(content); storageSubscription.Should().NotBeNull(); storageSubscription.Name.Should().BeEquivalentTo(updatedSubscription.Name); }
public async Task <IActionResult> SignUpAsync([FromForm] RegisterModel model) { try { var longSession = CryptoRandomizer.GetRandomString(32); var fingerPrint = authService.GetFingerPrint(HttpUtilities.GetDataFromHeaders(HttpContext, HttpConstants.UserAgentHeaderName), longSession); var registerResult = await authService.RegisterAsync(model.UserName, model.Email, model.Password, fingerPrint, longSession); authService.MakeLongSessionCookies(registerResult.RefreshToken); return(Json(registerResult)); } catch (ApiError infoExcetpion) { return(Unauthorized(infoExcetpion.ex.Description)); } }
public async Task ShouldDeleteSubscription() { var newSubscription = new SubscriptionCreateDto { Name = "UpdatedFromTest", SourceTypeId = 1, Parameters = "{}" }; var httpContent = HttpUtilities.GetHttpContent(newSubscription); var response = await _client.PostAsync("/api/subscriptions", httpContent); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); var storageSubscription = JsonConvert.DeserializeObject <SubscriptionDto>(content); response = await _client.DeleteAsync($"/api/subscriptions/{storageSubscription.Id}"); response.EnsureSuccessStatusCode(); }
/// <summary> /// Starts to upload the file as an asynchronous operation. /// </summary> /// <param name="sdkClient">The SDK client.</param> /// <param name="path">The path to the file.</param> /// <param name="file">The file.</param> /// <param name="progress">The progress.</param> public static async Task StartUploadFileAsync(this IDiskSdkClient sdkClient, string path, IStorageFile file, IProgress progress) { try { var uri = new Uri(WebdavResources.ApiUrl + path); var uploader = new BackgroundUploader { Method = "PUT" }; uploader.SetRequestHeader("Authorization", "OAuth " + sdkClient.AccessToken); uploader.SetRequestHeader("X-Yandex-SDK-Version", "winui, 1.0"); var upload = uploader.CreateUpload(uri, file); await HandleUploadAsync(upload, progress, true); } catch (Exception ex) { throw HttpUtilities.ProcessException(ex); } }
public IHttpActionResult ForgotPassword(ActivationRequest request) { try { var user = DbUtilities.GetUserByEmail(request.Email); if (user != null) { string validStatus = ValidationUtilities.ValidateForActivation(request, user, true); if (validStatus == Constants.SUCCESS_MSG) { User account = _context.Users.Where(a => a.Email == request.Email).SingleOrDefault(); //if (IsPasswordCorrect(request.Password, account)) // return BadRequest(ErrorCodes.PASSWORD_ALREADY_USED.ToString()); byte[] pwdhash = AuthorizationUtilities.hash(request.Password, account.Salt); // account.UpdatedAt = DateTime.UtcNow; account.ModifiedBy = request.Email; account.IsActivated = true; account.OTPCode = ""; //add the new password to the database account.Password = pwdhash; account.PwdStartDate = DateTimeOffset.UtcNow; account.IsLocked = false; _context.SaveChanges(); return(Ok(HttpUtilities.CustomResp(ErrorCodes.PWD_UPDATED.ToString()))); } else { return(BadRequest(validStatus)); } } else { //user doesn't exists return(BadRequest(ErrorCodes.INVALID_USER.ToString())); } } catch (Exception ex) { LGSELogger.Error(ex); return(InternalServerError(ex)); } }
/// <summary> /// Checks for the user authorization /// </summary> /// <param name="actionContext"></param> /// <returns></returns> protected override bool IsAuthorized(HttpActionContext actionContext) { try { // return true; //traceWriter = actionContext.ControllerContext.Configuration.Services.GetTraceWriter(); //traceWriter.Info("Custom Authorization started"); using (var dbContext = new LGSE_APIContext()) { authManager = new AuthorizationManager(dbContext); string userEmail = HttpUtilities.GetUserNameFromToken(actionContext.Request); // Abhijeet - 30-10-2018 -Added role id string userRole = HttpUtilities.GetUserRoleAccessApi(actionContext.Request); if (authManager.IsUserExists(userEmail)) { return(authManager.AuthorizeUser(userEmail, userRole, HttpUtilities.GetRequestToken(actionContext.Request), Module, OperationType)); } else { HandleUnauthenticatedRequests(actionContext, "User Doesnt Exist"); return(false); } } } catch (UnauthorizedAccessException ex) { HandleUnauthorizedRequests(actionContext, ex.Message); return(true); } catch (Exception ex) { LGSELogger.Error(ex); // traceWriter.Error(ex, actionContext.Request,"CustomAuthorizeError"); //this.Configuration.Services.GetTraceWriter() //log error message //throw ex; return(false); } }
public WXActionResult WPTDev() { string msgFrom = Parameters["FromUserName"].ToString(); string msgTo = Parameters["ToUserName"].ToString(); string msgType = Parameters["MsgType"].ToString(); WXActionResult ar = new WXActionResult(); if (msgType == "text") { string content = Parameters["Content"].ToString(); string[] userConfig = GetUserConfig(msgFrom); if (Parameters.ContainsKey("echostr") && ValidateSignature(userConfig[0])) { ar.Result.Add("single", Parameters["echostr"]); } else { string resp = HttpUtilities.HttpGet("http://www.tuling123.com/openapi/api", "key=" + userConfig[1] + "&userid=" + msgFrom + "&info=" + content); string text = HandleResponse(resp); ar.Result.Add("single", String.Format(text, Parameters["FromUserName"].ToString(), Parameters["ToUserName"].ToString())); } } else if (msgType == "event") { string _event = Parameters["Event"].ToString(); if (_event == "subscribe") { string subscribeMsgModel = "<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{3}]]></Content></xml>"; string subscribeMsg = "欢迎关注“微平台开发”/:rose:\n无论您是想了解微信公众平台开发还是有开发公众平台的需求都可以关注我们,我们定期更新最新的IT动向,发布最新的移动互联网信息,让您在移动互联网时代快人一步,我们专业承接微信公众平台开发,欢迎前来洽谈。\n使用说明:\n/:heart回复任意内容可和智能客服聊天。/:rose\n/:heart查询天气:回复关键字“天气”,如“上海天气”,可查询当天上海天气情况。/:rose\n/:heart查询快递:回复关键字“快递查询”,可激活查询快递功能。/:rose\n/:heart查询菜谱:回复关键字“红烧肉”,可智能搜索多种红烧肉做法。/:rose\n/:heart成语接龙:回复关键字“成语接龙”,可激活成语接龙游戏。/:rose\n/:heart讲笑话,看新闻等等更过精彩内容等你去发掘。/:rose\n"; ar.Result.Add("single", String.Format(subscribeMsgModel, Parameters["FromUserName"].ToString(), Parameters["ToUserName"].ToString(), DateTime.Now.Ticks, subscribeMsg)); } } else { ar.Result.Add("single", "不支持的消息类型!"); } return(ar); }
/// <summary> /// Revokes the refresh token. /// </summary> /// <exception cref="ArgumentNullException">Thrown if one of the following /// OAuth2 parameters are empty: RefreshToken.</exception> public void RevokeRefreshToken() { // Mark the usage. featureUsageRegistry.MarkUsage(FEATURE_ID);; ValidateOAuth2Parameter("RefreshToken", RefreshToken); string url = string.Format("{0}?token={1}", REVOKE_ENDPOINT, RefreshToken); WebRequest request = HttpUtilities.BuildRequest(url, "GET", config); LogEntry logEntry = new LogEntry(this.Config, new DefaultDateTimeProvider()); logEntry.LogRequest(request, "", new HashSet <string>()); WebResponse response = null; try { response = request.GetResponse(); string contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream()); logEntry.LogResponse(response, false, contents); logEntry.Flush(); } catch (WebException e) { string contents = ""; response = e.Response; try { contents = MediaUtilities.GetStreamContentsAsString(response.GetResponseStream()); } catch { contents = e.Message; } logEntry.LogResponse(response, true, contents); logEntry.Flush(); throw new AdsOAuthException("Failed to revoke refresh token.\n" + contents, e); } finally { if (response != null) { response.Close(); } } }
public override void AppendLinkFormatResourceOptions(StringBuilder Output) { base.AppendLinkFormatResourceOptions(Output); LinkedList <KeyValuePair <string, Node> > Queue = new LinkedList <KeyValuePair <string, Node> >(); Node Node; string Prefix; foreach (EditableTreeNode Obj in Topology.Root.GetChildren(this.user, EditableObject.DefaultIdParameterId)) { if (Obj is Node) { Queue.AddLast(new KeyValuePair <string, Node>("Topology/" + HttpUtilities.UrlEncode(Obj.Id), (Node)Obj)); } } while (Queue.First != null) { Prefix = Queue.First.Value.Key; Node = Queue.First.Value.Value; Queue.RemoveFirst(); foreach (EditableTreeNode Obj in Node.GetChildren(this.user, EditableObject.DefaultIdParameterId)) { if (Obj is Node) { Queue.AddLast(new KeyValuePair <string, Node>(Prefix + "/" + HttpUtilities.UrlEncode(Obj.Id), (Node)Obj)); } } Output.Append(','); Output.Append('<'); Output.Append(Prefix); Output.Append('>'); if (!string.IsNullOrEmpty(((Node)Node).Name)) { Output.Append(";title=\""); Output.Append(this.Title.Replace("\"", "\\\"")); Output.Append("\""); } } }
protected override void Invoking(MessageReceivedEventArgs e, PlainText plainText, ComplexMessage elements) { e.Reply(Resources.Processing); if (HttpUtilities.HttpGet(string.Format(Resources.IPInfoApiURL, plainText), out string content)) { try { var json = JObject.Parse(content); if (json["status"].ToString() == "success") { e.Reply($"状态:获取成功\n" + $"IP {json["query"]} 信息:\n" + $"洲:{json["continent"]}({json["continentCode"]})\n" + $"国家:{json["country"]}({json["countryCode"]})\n" + $"地区:{json["regionName"]}({json["region"]})\n" + $"城市:{json["city"]}\n" + $"邮政编码:{json["zip"]}\n" + $"经纬度:{json["lat"]}, {json["lon"]}\n" + $"时区:{json["timezone"]}\n" + $"货币单位:{json["currency"]}\n" + $"ISP:{json["isp"]}\n" + $"所属组织:{json["org"]}\n" + $"AS:{json["asname"]}({json["as"]})\n" + $"反向DNS:{json["reverse"]}\n" + $"移动数据接入:{(json["mobile"].ToObject<bool>() ? "是" : "否")}\n" + $"代理:{(json["proxy"].ToObject<bool>() ? "是" : "否")}\n" + $"托管/数据中心:{(json["hosting"].ToObject<bool>() ? "是" : "否")}"); } else { e.Reply("获取 IP 信息失败" + (json.ContainsKey("message") ? ",错误原因:" + json["message"] : string.Empty)); } } catch { e.Reply("信息处理失败了 (;´д`)ゞ"); } } else { e.Reply("请求失败了 (;´д`)ゞ"); } }
public void GetsKnownVersion(string input, bool expectedResult, string expectedKnownString, HttpVersion version) { // Arrange var block = new Span <byte>(Encoding.ASCII.GetBytes(input)); // Act HttpVersion knownVersion; var result = block.GetKnownVersion(out knownVersion, out var length); string toString = null; if (knownVersion != HttpVersion.Unknown) { toString = HttpUtilities.VersionToString(knownVersion); } // Assert Assert.Equal(expectedResult, result); Assert.Equal(expectedKnownString, toString); Assert.Equal(expectedKnownString?.Length ?? 0, length); }
/// <summary> /// Uploads a chunk of data for the batch job. /// </summary> /// <param name="url">The resumable upload URL.</param> /// <param name="postBody">The post body.</param> /// <param name="start">The start of range of bytes to be uploaded.</param> /// <param name="end">The end of range of bytes to be uploaded.</param> private void UploadChunk(string url, byte[] postBody, int start, int end) { BulkJobErrorHandler errorHandler = new BulkJobErrorHandler(user); while (true) { WebResponse response = null; LogEntry logEntry = new LogEntry(User.Config, new DefaultDateTimeProvider()); int bytesToWrite = end - start + 1; HttpWebRequest request = (HttpWebRequest)HttpUtilities.BuildRangeRequest( url, bytesToWrite, string.Format("bytes {0}-{1}/{2}", start, end, postBody.Length), user.Config); request.ContentType = "application/xml"; try { using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(postBody, start, bytesToWrite); } logEntry.LogRequest(request, "Truncated", HEADERS_TO_MASK); response = request.GetResponse(); logEntry.LogResponse(response, true, ""); logEntry.Flush(); return; } catch (WebException e) { response = e.Response; if (IsPartialUploadSuccessResponse(e)) { logEntry.LogResponse(e.Response, true, ""); logEntry.Flush(); return; } else { HandleCloudException(errorHandler, logEntry, e); } } } }