private async Task<Boolean> CreateToken(string csrfToken) { var request = new HttpRequestMessage(HttpMethod.Post, CommonData.BaseUri + "/session/token"); request.Headers.Add("X-SB1-Rest-Version", "1.0.0"); request.Headers.Add("X-CSRFToken", csrfToken); request.Content = new StringContent( JsonConvert.SerializeObject(new { description = "klokkebank" }), Encoding.UTF8, "application/json"); var response = await Client.SendAsync(request); if (!response.IsSuccessStatusCode) { LastError = "Kunne ikke opprette token"; return false; } var token = JsonConvert.DeserializeObject<JObject>(await response.Content.ReadAsStringAsync()); Token = (string)token["token"]; SaveSettings(); return true; }
private async void Launch_Click(object sender, RoutedEventArgs e) { if (FacebookClientID.Text == "") { rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage); return; } var uri = new Uri("https://graph.facebook.com/me"); HttpClient httpClient = GetAutoPickerHttpClient(FacebookClientID.Text); DebugPrint("Getting data from facebook...."); var request = new HttpRequestMessage(HttpMethod.Get, uri); try { var response = await httpClient.SendRequestAsync(request); if (response.IsSuccessStatusCode) { string userInfo = await response.Content.ReadAsStringAsync(); DebugPrint(userInfo); } else { string str = ""; if (response.Content != null) str = await response.Content.ReadAsStringAsync(); DebugPrint("ERROR: " + response.StatusCode + " " + response.ReasonPhrase + "\r\n" + str); } } catch (Exception ex) { DebugPrint("EXCEPTION: " + ex.Message); } }
public async void Search(object parameter) { SongLabelVisibility = "Collapsed"; ArtistLabelVisibility = "Collapsed"; AlbumLabelVisibility = "Collapsed"; if (SearchQuery == "" || SearchQuery == null) { return; } HttpRequestMessage message = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("https://mclients.googleapis.com/sj/v1.11/query?q=" + SearchQuery + "&max-results=50", UriKind.Absolute) }; HttpResponseMessage returnString = await HttpCall.MakeGetCallAsync(message); var songString = await returnString.Content.ReadAsStringAsync(); AllHits = JsonParser.Parse(songString); if (AllHits.entries != null) { SongHits = Hits.GetSongHits(AllHits.entries, 5); ArtistHits = Hits.GetArtistHits(AllHits.entries, 5); AlbumHits = Hits.GetAlbumHits(AllHits.entries, 5); } if (SongHits != null && SongHits.Count != 0) { SongLabelVisibility = "Visible"; } if (ArtistHits != null &&ArtistHits.Count != 0) { ArtistLabelVisibility = "Visible"; } if (AlbumHits != null &&AlbumHits.Count != 0) { AlbumLabelVisibility = "Visible"; } OnPropertyChanged("SongHits"); OnPropertyChanged("ArtistHits"); OnPropertyChanged("AlbumHits"); OnPropertyChanged("SongLabelVisibility"); OnPropertyChanged("ArtistLabelVisibility"); OnPropertyChanged("AlbumLabelVisibility"); }
public async void SetupPushNotificationChannelForApplicationAsync(string token, string arguments) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentException("you should add you app token"); } //var encryptedArguments = Helper.Encrypt(arguments, "cnblogs", "somesalt"); _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair<string, string>("arguments", arguments), new KeyValuePair<string, string>("token", token), new KeyValuePair<string, string>("uri", _channel.Uri), new KeyValuePair<string, string>("uuid", GetUniqueDeviceId()) }); var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server)); request.Content = content; var client = new HttpClient(); var response = await client.SendRequestAsync(request); _channel.PushNotificationReceived += _channel_PushNotificationReceived; }
public async Task InvalidateAsync() { EncodeCredentials(); var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2InvalidateToken)); req.Headers.Add("Authorization", "Basic " + BasicToken); req.Headers.Add("User-Agent", UserAgent); req.Headers.Add("Expect", "100-continue"); req.Content = new HttpStringContent("access_token=" + BearerToken, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded"); var baseFilter = new HttpBaseProtocolFilter { AutomaticDecompression = true }; //var handler = new HttpClientHandler(); //if (handler.SupportsAutomaticDecompression) // handler.AutomaticDecompression = DecompressionMethods.GZip; //if (Proxy != null && handler.SupportsProxy) // handler.Proxy = Proxy; using (var client = new HttpClient(baseFilter)) { var msg = await client.SendRequestAsync(req); await TwitterErrorHandler.ThrowIfErrorAsync(msg); string response = await msg.Content.ReadAsStringAsync(); var responseJson = JsonMapper.ToObject(response); BearerToken = responseJson.GetValue<string>("access_token"); } }
public void Constructor_ReportsBytesWritten(int offset, int count) { // Arrange Mock<Stream> mockInnerStream = new Mock<Stream>(); object userState = new object(); IAsyncResult mockIAsyncResult = CreateMockCompletedAsyncResult(true, userState); mockInnerStream.Setup(s => s.BeginWrite(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<AsyncCallback>(), It.IsAny<object>())) .Returns(mockIAsyncResult); MockProgressEventHandler mockProgressHandler; ProgressMessageHandler progressMessageHandler = MockProgressEventHandler.CreateProgressMessageHandler(out mockProgressHandler, sendProgress: true); HttpRequestMessage request = new HttpRequestMessage(); ProgressStream progressStream = ProgressStreamTest.CreateProgressStream(progressMessageHandler: progressMessageHandler, request: request); // Act IAsyncResult result = new ProgressWriteAsyncResult( mockInnerStream.Object, progressStream, sampleData, offset, count, null, userState); // Assert Assert.True(mockProgressHandler.WasInvoked); Assert.Same(request, mockProgressHandler.Sender); Assert.Equal(count, mockProgressHandler.EventArgs.BytesTransferred); Assert.Same(userState, mockProgressHandler.EventArgs.UserState); }
public async void Execute(string token, string content) { Uri uri = new Uri(API_ADDRESS + path); var rootFilter = new HttpBaseProtocolFilter(); rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent; rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache; HttpClient client = new HttpClient(rootFilter); //client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString()); if(token != null) client.DefaultRequestHeaders.Add("x-access-token", token); System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000); HttpResponseMessage response = null; if (requestType == GET) { try { response = await client.GetAsync(uri).AsTask(source.Token); } catch (TaskCanceledException) { response = null; } }else if (requestType == POST) { HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri); if (content != null) { msg.Content = new HttpStringContent(content); msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json"); } try { response = await client.SendRequestAsync(msg).AsTask(source.Token); } catch (TaskCanceledException) { response = null; } } if (response == null) { if (listener != null) listener.onTaskCompleted(null, requestCode); } else { string answer = await response.Content.ReadAsStringAsync(); if(listener != null) listener.onTaskCompleted(answer, requestCode); } }
public async Task<bool> SendRemoteCommandAsync(string pressedKey) { bool succeeded = false; string address = String.Empty; if (!string.IsNullOrWhiteSpace(pressedKey) && !string.IsNullOrWhiteSpace(_ipAddress)) { address = "http://" + _ipAddress + "/RemoteControl/KeyHandling/sendKey?key=" + pressedKey; var uri = new Uri(address, UriKind.Absolute); using (HttpClient client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage(); request.RequestUri = new Uri(address); IHttpContent httpContent = new HttpStringContent(String.Empty); try { await client.PostAsync(uri, httpContent); } catch (Exception) { return succeeded = false; } return succeeded = true; } } return succeeded = false; }
// Post notification private static async Task SendNotificationAsync(string notificationXML) { using (var client = new HttpClient()) { try { var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri("https://login.live.com/accesstoken.srf")); request.Content = new HttpStringContent(string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", Constants.StoreClienId, Constants.StoreClientSecret), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded"); var res = await client.SendRequestAsync(request); if (res.IsSuccessStatusCode) { var tokenJson = await res.Content.ReadAsStringAsync(); var token = JsonConvert.DeserializeObject<Token>(tokenJson); request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(Constants.OwnerNotificationChannel)); request.Content = new HttpStringContent(notificationXML, Windows.Storage.Streams.UnicodeEncoding.Utf8, "text/xml"); (request.Content as HttpStringContent).Headers.ContentLength = Convert.ToUInt64(notificationXML.Length); request.Headers.Authorization = new HttpCredentialsHeaderValue(token.TokenType, token.AccessToken); request.Headers.Add("X-WNS-Type", "wns/toast"); await client.SendRequestAsync(request); } } catch (Exception ex) { } } }
// _perform_auth_request private async Task<Dictionary<string, string>> PerformAuthRequest(Dictionary<string, string> data) { HttpRequestMessage request = new HttpRequestMessage() { Method = HttpMethod.Post, RequestUri = new Uri("https://android.clients.google.com/auth", UriKind.Absolute) }; var keyValues = new List<KeyValuePair<string, string>>(); foreach(var kvp in data) { keyValues.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Value)); } request.Headers.Add("User-Agent", userAgent); string result = ""; try { request.Content = new HttpFormUrlEncodedContent(keyValues); HttpResponseMessage response = await client.SendRequestAsync(request); if (response.IsSuccessStatusCode == false) { throw new Exception(); } result = await response.Content.ReadAsStringAsync(); } catch (Exception e) { throw e; } return GoogleKeyUtils.ParseAuthResponse(result); }
public async Task<List<Notification>> GetNotifications() { HttpResponseMessage response = null; HttpRequestMessage request = null; using (var httpClient = new HttpClient()) { request = new HttpRequestMessage(HttpMethod.Get, new Uri(Const.UrlNotifyWithTimeStamp)); response = await httpClient.SendRequestAsync(request); } var respList = (JObject)JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); List<Notification> notList = new List<Notification>(); if (respList.HasValues) { var c = respList.First.First; for (int i = 0; i < c.Count(); i++) { var ele = (JProperty)c.ElementAt(i); Notification n = JsonConvert.DeserializeObject<Notification>(ele.Value.ToString()); n.AddedDate = new DateTime(1970, 1, 1).AddMilliseconds((long)(((JValue)ele.Value["Data"]).Value)); n.PublicationId = ele.Name.Split(':')[0]; n.Id = ele.Name.Split(':')[1]; n.TypeValue = Enum.ParseToNotificationType(((JValue)ele.Value["Type"]).Value.ToString()); notList.Add(n); } } notList = notList.OrderBy(n => n.Status).ThenByDescending(n => n.AddedDate).ToList(); return notList; }
public async Task<Tuple<bool, DateTime?>> SetSessionCookie(string login, string password) { HttpResponseMessage response = null; HttpRequestMessage request = null; using (var httpClient = new HttpClient()) { request = new HttpRequestMessage(HttpMethod.Post, new Uri(Const.UrlLogin)); request.Content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair<string, string>("what", "login"), new KeyValuePair<string, string>("login", login), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("persistent", "true"), }); try { response = await httpClient.SendRequestAsync(request); } catch (Exception) { return new Tuple<bool, DateTime?>(false, null); } } var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); var expireDate = httpFilter.CookieManager.GetCookies(new Uri(Const.UrlFullAddress)).First().Expires ?? DateTime.Now; return new Tuple<bool, DateTime?>(response.StatusCode == Windows.Web.Http.HttpStatusCode.Ok, expireDate.DateTime); }
public override async void receive_file(String devicename, String add, int not) { try { _httpurl = new Uri(add); _httpprogress = new Progress<HttpProgress>(ProgressHandler); HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; _httpclient = new HttpClient(filter); _cancel_token_source = new CancellationTokenSource(); _cancel_token = _cancel_token_source.Token; scan_network_speed(); _stopwatch.Start(); _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress); StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting); IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite); IOutputStream filewriter = filestream.GetOutputStreamAt(0); _datawriter = new DataWriter(filewriter); _timer.Cancel(); _transferspeed /= 1024; _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s"); this.callback.on_transfer_speed_change(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _stopwatch.Stop(); _buffer = await _httpresponse.Content.ReadAsBufferAsync(); _datawriter.WriteBuffer(_buffer); await _datawriter.StoreAsync(); _datawriter.Dispose(); filewriter.Dispose(); filestream.Dispose(); _httpresponse.Content.Dispose(); _httpresponse.Dispose(); _httpclient.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, ""); } }
private static HttpRequestMessage generateUploadRequest(string address, string fileName, string fileContents, string mimeType, Dictionary<string, string> parameters) { var rnd = new Random(); long boundarySeed = (long)(rnd.NextDouble() * 1000000000); string boundary = boundarySeed.ToString(); string contentType = "multipart/form-data; boundary=" + boundary; string partBoundary = "--" + boundary; string requestBody = "\r\n" + partBoundary + "\r\n"; requestBody += "Content-Disposition: form-data; name=\"" + POSTKeys.POST_UPLOADED_FILE + "\"; filename=\"" + fileName + "\"\r\n"; requestBody += "Content-Type: " + mimeType + "\r\n\r\n"; requestBody += fileContents + "\r\n"; foreach (var parameter in parameters) { requestBody += partBoundary + "\r\n"; requestBody += "Content-Disposition: form-data; name=\"" + parameter.Key + "\"\r\n\r\n"; requestBody += parameter.Value + "\r\n"; } requestBody += "--" + boundary + "--"; HttpRequestMessage uploadRequest = new HttpRequestMessage(HttpMethod.Post, new Uri(address)); uploadRequest.Content = new HttpStringContent(requestBody); uploadRequest.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(contentType); uploadRequest.Content.Headers.ContentLength = (ulong?)requestBody.Length; return uploadRequest; }
async Task GetBearerTokenAsync() { var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2Token)); req.Headers.Add("Authorization", "Basic " + BasicToken); req.Headers.Add("User-Agent", UserAgent); req.Headers.Add("Expect", "100-continue"); req.Content = new HttpStringContent("grant_type=client_credentials", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded"); var baseFilter = new HttpBaseProtocolFilter { AutomaticDecompression = SupportsCompression, ProxyCredential = ProxyCredential, UseProxy = UseProxy }; using (var client = new HttpClient(baseFilter)) { var msg = await client.SendRequestAsync(req); await TwitterErrorHandler.ThrowIfErrorAsync(msg); string response = await msg.Content.ReadAsStringAsync(); var responseJson = JsonMapper.ToObject(response); BearerToken = responseJson.GetValue<string>("access_token"); } }
public TestBase() { Request = new HttpRequestMessage(); HttpConfiguration = new HttpConfiguration(); ContainerBuilder = new ContainerBuilder(); ContainerBuilder.RegisterApiControllers(typeof(AddressesController).Assembly); }
/// <summary> /// Raises the <see cref="HttpReceiveProgress"/> event. /// </summary> /// <param name="request">The request.</param> /// <param name="e">The <see cref="HttpProgressEventArgs"/> instance containing the event data.</param> protected internal virtual void OnHttpResponseProgress(HttpRequestMessage request, HttpProgressEventArgs e) { if (HttpReceiveProgress != null) { HttpReceiveProgress(request, e); } }
public static async void HttpPost(string phone, string password) { try { HttpClient httpClient = new HttpClient(); string posturi = Config.apiUserRegister; string date = DateTime.Now.Date.Year.ToString() + "-" + DateTime.Now.Date.Month.ToString() + "-" + DateTime.Now.Date.Day.ToString(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("phone", phone),//手机号 new KeyValuePair<string, string>("password", password),//密码 new KeyValuePair<string, string>("date", date),//注册日期 } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); string responseString = await response.Content.ReadAsStringAsync(); JsonObject register = JsonObject.Parse(responseString); try { int code = (int)register.GetNamedNumber("code"); switch (code) { case 0: { JsonObject user = register.GetNamedObject("user"); Config.UserPhone = user.GetNamedString("phone"); NavigationHelp.NavigateTo(typeof(UserData)); break; } case 1: HelpMethods.Msg("手机号已注册!"); break; case 2: HelpMethods.Msg("未知错误!"); break; default: break; } } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
public static async void HttpPost(string phone, string password) { try { HttpClient httpClient = new HttpClient(); string posturi = Config.apiUserLogin; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("phone", phone),//手机 new KeyValuePair<string, string>("password", password),//密码 } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); string responseString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(responseString); JsonObject login = JsonObject.Parse(responseString); try { int code = (int)login.GetNamedNumber("code"); switch (code) { case 0: { JsonObject user = login.GetNamedObject("user"); Config.UserName = user.GetNamedString("name") ; Config.UserImage = Config.apiFile + user.GetNamedString("image"); Config.UserPhone = user.GetNamedString("phone") ; Config.UserDream = user.GetNamedString("dream") ; Config.UserTag = user.GetNamedString("tag"); NavigationHelp.NavigateTo(typeof(Main)); break; } case 1: HelpMethods.Msg("手机号未注册!"); break; case 2: HelpMethods.Msg("密码错误!"); break; default: break; } } catch (Exception ex) { HelpMethods.Msg("服务器出错!"); Debug.WriteLine(ex.Message.ToString()); } } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
public async static Task<HttpResponseMessage> SendHeadRequestAsync(Uri url) { var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache; using (var httpClient = new HttpClient(filter)) { try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url); HttpResponseMessage response = await httpClient.SendRequestAsync(request); #if DEBUG Logger.Log("Sending head request with: " + url); #endif return response; } catch (Exception e) { #if DEBUG Logger.Log("GetBufferAsync exception for url: " + url + " HRESULT 0x" + e.HResult.ToString("x")); #endif return null; } } }
public HttpException(HttpResponseMessage response, COMException innerException, string message = null) : this(GetResponseExceptionMessage(response, message), innerException) { HResult = innerException.HResult; _request = response?.RequestMessage; _response = response; }
public static async void HttpPost(string cid, string cname, string cimage, string cdream, string fid, string fname,string fimage,string fdream) { try { HttpClient httpClient = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(Config.apiUserFollow)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("cphone", cid), new KeyValuePair<string, string>("cname", cname), new KeyValuePair<string, string>("cimage", cimage), new KeyValuePair<string, string>("cdream", cdream), new KeyValuePair<string, string>("fphone", fid), new KeyValuePair<string, string>("fname", fname), new KeyValuePair<string, string>("fimage", fimage), new KeyValuePair<string, string>("fdream", fdream), } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); string responseString = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
public Task SendAsync_InsertsReceiveProgressWhenResponseEntityPresent(bool insertResponseEntity, bool addReceiveProgressHandler) { // Arrange HttpMessageInvoker invoker = CreateMessageInvoker(includeResponseEntity: insertResponseEntity, addSendProgressHandler: false, addReceiveProgressHandler: addReceiveProgressHandler); HttpRequestMessage request = new HttpRequestMessage(); // Act return invoker.SendAsync(request, CancellationToken.None).ContinueWith( task => { HttpResponseMessage response = task.Result; Assert.Equal(TaskStatus.RanToCompletion, task.Status); // Assert if (insertResponseEntity && addReceiveProgressHandler) { ValidateContentHeader(response.Content); Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.NotNull(response.Content); Assert.IsType<StreamContent>(response.Content); } else { if (insertResponseEntity) { Assert.IsType<StringContent>(response.Content); } else { Assert.Null(response.Content); } } }); }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { SendAsyncCount++; return Task.FromResult<HttpResponseMessage>(new HttpResponseMessage()); }
public static async void HttpPost(string id,string phone,string image, string name, string content, string time,string atName,string atPhone,string atImage) { try { HttpClient httpClient = new HttpClient(); string posturi = Config.apiCommentPublish; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(posturi)); HttpFormUrlEncodedContent postData = new HttpFormUrlEncodedContent( new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("id",id), new KeyValuePair<string,string>("phone",phone), new KeyValuePair<string, string>("image", image), new KeyValuePair<string, string>("name", name), new KeyValuePair<string, string>("content", content), new KeyValuePair<string, string>("time", time), new KeyValuePair<string, string>("atName", atName), new KeyValuePair<string, string>("atPhone", atPhone), new KeyValuePair<string, string>("atImage", atImage), } ); request.Content = postData; HttpResponseMessage response = await httpClient.SendRequestAsync(request); } catch (Exception ex) { HelpMethods.Msg(ex.Message.ToString()); } }
protected internal virtual void AddRequestHeaders(HttpRequestMessage request) { foreach (string requestHeaderKey in requestHeaders.Keys) { request.AddHeader(requestHeaderKey, requestHeaders.Get(requestHeaderKey).ToString ()); } }
public void Bind(Expression expression, HttpRequestMessage request) { var queryString = GetQueryString(expression); request.RequestUri = new Uri(request.RequestUri + ((request.RequestUri.ToString().IndexOf("?", StringComparison.InvariantCulture) >= 0) ? "&" : "?") + queryString, request.RequestUri.IsAbsoluteUri ? UriKind.Absolute : UriKind.Relative); }
private void AddRequestProgress(HttpRequestMessage request) { if (HttpSendProgress != null && request != null && request.Content != null) { HttpContent progressContent = new ProgressContent(request.Content, this, request); request.Content = progressContent; } }
/// <summary> /// Returns a value indicating whether the current <see cref="RequestHeaderMapping"/> /// instance can return a <see cref="MediaTypeHeaderValue"/> from <paramref name="request"/>. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to check.</param> /// <returns> /// The quality of the match. It must be between <c>0.0</c> and <c>1.0</c>. /// A value of <c>0.0</c> signifies no match. /// A value of <c>1.0</c> signifies a complete match. /// </returns> public override double TryMatchMediaType(HttpRequestMessage request) { if (request == null) { throw Error.ArgumentNull("request"); } return MatchHeaderValue(request, HeaderName, HeaderValue, HeaderValueComparison, IsValueSubstring); }
/// <summary> /// Adds user-defined metadata to the request as a single name-value pair. /// </summary> /// <param name="request">The web request.</param> /// <param name="name">The metadata name.</param> /// <param name="value">The metadata value.</param> public static void AddMetadata(HttpRequestMessage request, string name, string value) { HttpRequestMessageFactory.AddMetadata(request, name, value); }
public HttpResponseMessage GetBlogTagCloud(string id, HttpRequestMessage request) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); try { IBlogsService blogsService = ObjectFactory.GetInstance <IBlogsService>(); var blog = blogsService.Get(String.Format("blogs/{0}", id)); var tagCloud = blogsService.GetTagCloud(String.Format("blogs/{0}", id)); if (blog != null) { SyndicationFeed blogFeed = new SyndicationFeed { Title = new TextSyndicationContent("Blog tag cloud"), LastUpdatedTime = new DateTimeOffset(DateTime.Now) }; blogFeed.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); SyndicationItem item = new SyndicationItem(); List <SyndicationItem> itemList = new List <SyndicationItem> { item }; blogFeed.Items = itemList; item.Id = blog.Id; item.LastUpdatedTime = blog.updated; item.PublishDate = blog.published; item.Title = new TextSyndicationContent("Blog tag cloud"); item.Content = SyndicationContent.CreatePlaintextContent(BuildtagCloud(tagCloud)); item.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); SyndicationFeedFormatter formatter = null; if (this.ClientAcceptsMediaType("application/atom+xml", request)) { formatter = blogFeed.GetAtom10Formatter(); } else { if (this.ClientAcceptsMediaType("application/rss+xml", request)) { formatter = blogFeed.GetRss20Formatter(); } } response.Content = new ObjectContent(typeof(SyndicationFeedFormatter), formatter); } else { response.StatusCode = HttpStatusCode.NotFound; } } catch (Exception) { response.StatusCode = HttpStatusCode.InternalServerError; } return(response); }
/// <summary> /// Get adoxio_account_adoxio_licences_ProposedOperator from accounts /// </summary> /// <param name='accountid'> /// key: accountid of account /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection> > GetWithHttpMessagesAsync(string accountid, int?top = default(int?), int?skip = default(int?), string search = default(string), string filter = default(string), bool?count = default(bool?), IList <string> orderby = default(IList <string>), IList <string> select = default(IList <string>), IList <string> expand = default(IList <string>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("accountid", accountid); tracingParameters.Add("top", top); tracingParameters.Add("skip", skip); tracingParameters.Add("search", search); tracingParameters.Add("filter", filter); tracingParameters.Add("count", count); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "accounts({accountid})/adoxio_account_adoxio_licences_ProposedOperator").ToString(); _url = _url.Replace("{accountid}", System.Uri.EscapeDataString(accountid)); List <string> _queryParameters = new List <string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby)))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <MicrosoftDynamicsCRMadoxioLicencesCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <MicrosoftDynamicsCRMadoxioLicencesCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
// GET: api/Tests //public IQueryable<Test> GetTests() { public HttpResponseMessage GetTests(HttpRequestMessage request) { return(request.CreateResponse <Test[]>(HttpStatusCode.OK, db.Tests.ToArray())); }
public HttpResponseMessage GetComments(string blogId, string postId, HttpRequestMessage request, int pageIndex = 1, int pageSize = 10) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); try { ICommentsService commentsService = ObjectFactory.GetInstance <ICommentsService>(); var comments = commentsService.GetAllFromPost(String.Format("posts/{0}", postId), pageIndex, pageSize); if (comments != null) { if (this.ClientAcceptsMediaType("text/html", request)) { var commentsHtml = comments.GenerateCommentsHtml(); response.Content = new ObjectContent <string>(commentsHtml, "text/html"); } else { SyndicationFeed postCommentsFeed = new SyndicationFeed { Title = new TextSyndicationContent( String.Format("Post {0} comments", postId)), LastUpdatedTime = new DateTimeOffset(DateTime.Now) }; postCommentsFeed.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); List <SyndicationItem> itemList = new List <SyndicationItem>(); postCommentsFeed.Items = itemList; foreach (var comment in comments) { SyndicationItem item = new SyndicationItem { Id = comment.Id, LastUpdatedTime = comment.updated, PublishDate = comment.published }; item.Links.Add(SyndicationLink.CreateSelfLink(new Uri(String.Format("{0}/blogs/{1}/posts/{2}/{3}", this.serviceURI, blogId, postId, comment.Id)))); item.Links.Add(SyndicationLink.CreateAlternateLink(request.RequestUri, "text/html")); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/blogs/{1}/posts/{2}", this.serviceURI, blogId, postId)), "service.post", "Parent post", "application/atom+xml;type=feed", 0)); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/blogs/{1}/posts/{2}/{3}", this.serviceURI, blogId, postId, comment.Id)), "service.edit", "Edit comment", "application/atom+xml;type=feed", 0)); var pagingLinks = this.BuildPagingLinks(commentsService.Count(), pageIndex, pageSize, request.RequestUri); foreach (var link in pagingLinks) { item.Links.Add(link); } item.Authors.Add(new SyndicationPerson(string.Empty, comment.author, string.Empty)); item.Content = SyndicationContent.CreatePlaintextContent(comment.content); itemList.Add(item); } SyndicationFeedFormatter formatter = null; if (this.ClientAcceptsMediaType("application/atom+xml", request)) { formatter = postCommentsFeed.GetAtom10Formatter(); } else { if (this.ClientAcceptsMediaType("application/rss+xml", request)) { formatter = postCommentsFeed.GetRss20Formatter(); } } response.Content = new ObjectContent(typeof(SyndicationFeedFormatter), formatter); } } else { response.StatusCode = HttpStatusCode.NoContent; } } catch (Exception) { response.StatusCode = HttpStatusCode.InternalServerError; } return(response); }
/// <summary> /// http://fabric/app/service/#/partitionkey/any|primary|secondary/endpoint-name/api-path /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { ServicePartitionResolver resolver = ServicePartitionResolver.GetDefault(); ResolvedServicePartition partition = null; HttpServiceUriBuilder uriBuilder = new HttpServiceUriBuilder(request.RequestUri); int retries = MaxRetries; int retryDelay = InitialRetryDelayMs; bool resolveAddress = true; HttpResponseMessage lastResponse = null; Exception lastException = null; while (retries-- > 0) { lastResponse = null; cancellationToken.ThrowIfCancellationRequested(); if (resolveAddress) { partition = partition != null ? await resolver.ResolveAsync(partition, cancellationToken) : await resolver.ResolveAsync(uriBuilder.ServiceName, uriBuilder.PartitionKey, cancellationToken); string serviceEndpointJson; switch (uriBuilder.Target) { case HttpServiceUriTarget.Default: case HttpServiceUriTarget.Primary: serviceEndpointJson = partition.GetEndpoint().Address; break; case HttpServiceUriTarget.Secondary: serviceEndpointJson = partition.Endpoints.ElementAt(this.random.Next(1, partition.Endpoints.Count)).Address; break; case HttpServiceUriTarget.Any: default: serviceEndpointJson = partition.Endpoints.ElementAt(this.random.Next(0, partition.Endpoints.Count)).Address; break; } string endpointUrl = JObject.Parse(serviceEndpointJson)["Endpoints"][uriBuilder.EndpointName].Value <string>(); request.RequestUri = new Uri($"{endpointUrl.TrimEnd('/')}/{uriBuilder.ServicePathAndQuery.TrimStart('/')}", UriKind.Absolute); } try { lastResponse = await base.SendAsync(request, cancellationToken); if (lastResponse.StatusCode == HttpStatusCode.NotFound || lastResponse.StatusCode == HttpStatusCode.ServiceUnavailable) { resolveAddress = true; } else { return(lastResponse); } } catch (TimeoutException te) { lastException = te; resolveAddress = true; } catch (SocketException se) { lastException = se; resolveAddress = true; } catch (HttpRequestException hre) { lastException = hre; resolveAddress = true; } catch (Exception ex) { lastException = ex; WebException we = ex as WebException; if (we == null) { we = ex.InnerException as WebException; } if (we != null) { HttpWebResponse errorResponse = we.Response as HttpWebResponse; // the following assumes port sharing // where a port is shared by multiple replicas within a host process using a single web host (e.g., http.sys). if (we.Status == WebExceptionStatus.ProtocolError) { if (errorResponse.StatusCode == HttpStatusCode.NotFound || errorResponse.StatusCode == HttpStatusCode.ServiceUnavailable) { // This could either mean we requested an endpoint that does not exist in the service API (a user error) // or the address that was resolved by fabric client is stale (transient runtime error) in which we should re-resolve. resolveAddress = true; } // On any other HTTP status codes, re-throw the exception to the caller. throw; } if (we.Status == WebExceptionStatus.Timeout || we.Status == WebExceptionStatus.RequestCanceled || we.Status == WebExceptionStatus.ConnectionClosed || we.Status == WebExceptionStatus.ConnectFailure) { resolveAddress = true; } } else { throw; } } await Task.Delay(retryDelay); retryDelay += retryDelay; } if (lastResponse != null) { return(lastResponse); } else { throw lastException; } }
/// <summary> /// The List Metric Settings operation lists the metric settings for /// the resource. /// </summary> /// <param name='resourceId'> /// Required. The id of the resource. /// </param> /// <param name='metricNamespace'> /// Required. The namespace of the metrics. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The list metric settings operation response. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Monitoring.Metrics.Models.MetricSettingListResponse> ListAsync(string resourceId, string metricNamespace, CancellationToken cancellationToken) { // Validate if (resourceId == null) { throw new ArgumentNullException("resourceId"); } if (metricNamespace == null) { throw new ArgumentNullException("metricNamespace"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceId", resourceId); tracingParameters.Add("metricNamespace", metricNamespace); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/metricsettings?"; url = url + "&resourceId=" + Uri.EscapeDataString(resourceId.Trim()); url = url + "&namespace=" + Uri.EscapeDataString(metricNamespace.Trim()); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result MetricSettingListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricSettingListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricSettingCollection metricSettingCollectionInstance = new MetricSettingCollection(); result.MetricSettingCollection = metricSettingCollectionInstance; JToken valueArray = responseDoc["Value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { MetricSetting metricSettingInstance = new MetricSetting(); metricSettingCollectionInstance.Value.Add(metricSettingInstance); JToken resourceIdValue = valueValue["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricSettingInstance.ResourceId = resourceIdInstance; } JToken namespaceValue = valueValue["Namespace"]; if (namespaceValue != null && namespaceValue.Type != JTokenType.Null) { string namespaceInstance = ((string)namespaceValue); metricSettingInstance.Namespace = namespaceInstance; } JToken valueValue2 = valueValue["Value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string typeName = ((string)valueValue2["odata.type"]); if (typeName == "Microsoft.WindowsAzure.Management.Monitoring.Metrics.Models.AvailabilityMetricSettingValue") { AvailabilityMetricSettingValue availabilityMetricSettingValueInstance = new AvailabilityMetricSettingValue(); JToken availableLocationsArray = valueValue2["AvailableLocations"]; if (availableLocationsArray != null && availableLocationsArray.Type != JTokenType.Null) { foreach (JToken availableLocationsValue in ((JArray)availableLocationsArray)) { NameConfig nameConfigInstance = new NameConfig(); availabilityMetricSettingValueInstance.AvailableLocations.Add(nameConfigInstance); JToken nameValue = availableLocationsValue["Name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); nameConfigInstance.Name = nameInstance; } JToken displayNameValue = availableLocationsValue["DisplayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); nameConfigInstance.DisplayName = displayNameInstance; } } } JToken endpointsArray = valueValue2["Endpoints"]; if (endpointsArray != null && endpointsArray.Type != JTokenType.Null) { foreach (JToken endpointsValue in ((JArray)endpointsArray)) { EndpointConfig endpointConfigInstance = new EndpointConfig(); availabilityMetricSettingValueInstance.Endpoints.Add(endpointConfigInstance); JToken configIdValue = endpointsValue["ConfigId"]; if (configIdValue != null && configIdValue.Type != JTokenType.Null) { string configIdInstance = ((string)configIdValue); endpointConfigInstance.ConfigId = configIdInstance; } JToken nameValue2 = endpointsValue["Name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); endpointConfigInstance.Name = nameInstance2; } JToken locationValue = endpointsValue["Location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); endpointConfigInstance.Location = locationInstance; } JToken urlValue = endpointsValue["Url"]; if (urlValue != null && urlValue.Type != JTokenType.Null) { Uri urlInstance = TypeConversion.TryParseUri(((string)urlValue)); endpointConfigInstance.Url = urlInstance; } } } metricSettingInstance.Value = availabilityMetricSettingValueInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
public TextResult(string value, HttpRequestMessage request) { _value = value; _request = request; }
public override async Task <HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken) { ValidateRequest(request); IList <JsonRequestMessage> jsonRequests; try { jsonRequests = await SplitRequests(request); } catch { throw new HttpResponseException(request.CreateErrorResponse( HttpStatusCode.BadRequest, "Content is invalid")); } var requests = new List <HttpRequestMessage>(); var responses = new List <HttpResponseMessage>(); var jsonResponses = new JArray(); TransactionScope tx = null; var queries = request.GetQueryNameValuePairs(); if (queries.Any(kvp => kvp.Key == "transaction" && kvp.Value == "true")) { AzureConfiguration.SuspendExecutionStrategy = true; tx = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled); } try { var success = true; foreach (var jsonRequest in jsonRequests) { var subRequest = ParseRequest(request, jsonRequest, jsonResponses); requests.Add(subRequest); var response = await Invoker.SendAsync(subRequest, cancellationToken); responses.Add(response); var jsonResponse = await ToJsonResponse(response); jsonResponses.Add(jsonResponse.ToJObject()); if (!response.IsSuccessStatusCode) { success = false; break; } } if (success) { tx?.Complete(); } return(request.CreateResponse(success ? HttpStatusCode.OK : HttpStatusCode.BadRequest, jsonResponses)); } catch { foreach (var response in responses) { response?.Dispose(); } throw; } finally { foreach (var subRequest in requests) { request.RegisterForDispose(subRequest.GetResourcesForDisposal()); request.RegisterForDispose(subRequest); } tx?.Dispose(); AzureConfiguration.SuspendExecutionStrategy = false; } }
private static Dictionary <string, string> GetRequestHeaders(HttpRequestMessage request) { return(new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Request, request?.Headers, request?.Content?.Headers).ToDictionary()); }
private static async Task <string> GetRequestBodyAsync(HttpRequestMessage request) { return(request?.Content != null ? await request.Content.ReadAsStringAsync() : null); }
/// <summary> /// Generates a web request to return a listing of all blobs in the container. /// </summary> /// <param name="uri">The absolute URI to the container.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="listingContext">A set of parameters for the listing operation.</param> /// <returns>A web request to use to perform the operation.</returns> public static HttpRequestMessage ListBlobs(Uri uri, int?timeout, BlobListingContext listingContext, HttpContent content, OperationContext operationContext) { UriQueryBuilder builder = ContainerHttpRequestMessageFactory.GetContainerUriQueryBuilder(); builder.Add(Constants.QueryConstants.Component, "list"); if (listingContext != null) { if (listingContext.Prefix != null) { builder.Add("prefix", listingContext.Prefix); } if (listingContext.Delimiter != null) { builder.Add("delimiter", listingContext.Delimiter); } if (listingContext.Marker != null) { builder.Add("marker", listingContext.Marker); } if (listingContext.MaxResults != null) { builder.Add("maxresults", listingContext.MaxResults.ToString()); } if (listingContext.Details != BlobListingDetails.None) { StringBuilder sb = new StringBuilder(); bool started = false; if ((listingContext.Details & BlobListingDetails.Snapshots) == BlobListingDetails.Snapshots) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("snapshots"); } if ((listingContext.Details & BlobListingDetails.UncommittedBlobs) == BlobListingDetails.UncommittedBlobs) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("uncommittedblobs"); } if ((listingContext.Details & BlobListingDetails.Metadata) == BlobListingDetails.Metadata) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("metadata"); } if ((listingContext.Details & BlobListingDetails.Copy) == BlobListingDetails.Copy) { if (!started) { started = true; } else { sb.Append(","); } sb.Append("copy"); } builder.Add("include", sb.ToString()); } } HttpRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Get, uri, timeout, builder, content, operationContext); return(request); }
public static async Task RequestFailedAsync(ILogger logger, string typedClientName, string requestId, HttpRequestMessage request, TimeSpan duration, Exception exception) { using (LogContext.Push( new PropertyEnricher("RequestId", requestId), new PropertyEnricher("RequestType", request.GetType().Name), new PropertyEnricher("RequestHeaders", GetRequestHeaders(request), true), new PropertyEnricher("RequestBody", await GetRequestBodyAsync(request)), new PropertyEnricher("ResponseHeaders", string.Empty), new PropertyEnricher("ResponseBody", string.Empty))) { LogRequestError(logger, typedClientName, "Err", request.Method, request.RequestUri, duration.TotalMilliseconds, exception); } }
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { loggerfactory.AddConsole(LogLevel.Information); // Simple error page to avoid a repo dependency. app.Use(async(context, next) => { try { await next(); } catch (Exception ex) { if (context.Response.HasStarted) { throw; } context.Response.StatusCode = 500; await context.Response.WriteAsync(ex.ToString()); } }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, LoginPath = new PathString("/login") }); // You must first create an app with facebook and add it's ID and Secret to your config.json or user-secrets. // https://developers.facebook.com/apps/ app.UseFacebookAuthentication(new FacebookOptions { AppId = Configuration["facebook:appid"], AppSecret = Configuration["facebook:appsecret"], Scope = { "email" }, Fields = { "name", "email" }, SaveTokens = true, }); // See config.json app.UseOAuthAuthentication(new OAuthOptions { AuthenticationScheme = "Google-AccessToken", DisplayName = "Google-AccessToken", ClientId = Configuration["google:clientid"], ClientSecret = Configuration["google:clientsecret"], CallbackPath = new PathString("/signin-google-token"), AuthorizationEndpoint = GoogleDefaults.AuthorizationEndpoint, TokenEndpoint = GoogleDefaults.TokenEndpoint, Scope = { "openid", "profile", "email" }, SaveTokens = true }); // See config.json // https://console.developers.google.com/project app.UseGoogleAuthentication(new GoogleOptions { ClientId = Configuration["google:clientid"], ClientSecret = Configuration["google:clientsecret"], SaveTokens = true, Events = new OAuthEvents() { OnRemoteFailure = ctx => { ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); ctx.HandleResponse(); return(Task.FromResult(0)); } } }); // See config.json // https://apps.twitter.com/ app.UseTwitterAuthentication(new TwitterOptions { ConsumerKey = Configuration["twitter:consumerkey"], ConsumerSecret = Configuration["twitter:consumersecret"], // http://stackoverflow.com/questions/22627083/can-we-get-email-id-from-twitter-oauth-api/32852370#32852370 // http://stackoverflow.com/questions/36330675/get-users-email-from-twitter-api-for-external-login-authentication-asp-net-mvc?lq=1 RetrieveUserDetails = true, SaveTokens = true, Events = new TwitterEvents() { OnCreatingTicket = ctx => { var profilePic = ctx.User.Value <string>("profile_image_url"); ctx.Principal.Identities.First().AddClaim(new Claim("urn:twitter:profilepicture", profilePic, ClaimTypes.Uri, ctx.Options.ClaimsIssuer)); return(Task.FromResult(0)); }, OnRemoteFailure = ctx => { ctx.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(ctx.Failure.Message)); ctx.HandleResponse(); return(Task.FromResult(0)); } } }); /* Azure AD app model v2 has restrictions that prevent the use of plain HTTP for redirect URLs. * Therefore, to authenticate through microsoft accounts, tryout the sample using the following URL: * https://localhost:44318/ */ // See config.json // https://apps.dev.microsoft.com/ app.UseOAuthAuthentication(new OAuthOptions { AuthenticationScheme = "Microsoft-AccessToken", DisplayName = "MicrosoftAccount-AccessToken", ClientId = Configuration["msa:clientid"], ClientSecret = Configuration["msa:clientsecret"], CallbackPath = new PathString("/signin-microsoft-token"), AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint, TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint, Scope = { "https://graph.microsoft.com/user.read" }, SaveTokens = true }); // See config.json // https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-app-registration/ app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions { DisplayName = "MicrosoftAccount", ClientId = Configuration["msa:clientid"], ClientSecret = Configuration["msa:clientsecret"], SaveTokens = true }); // See config.json // https://github.com/settings/applications/ app.UseOAuthAuthentication(new OAuthOptions { AuthenticationScheme = "GitHub-AccessToken", DisplayName = "Github-AccessToken", ClientId = Configuration["github-token:clientid"], ClientSecret = Configuration["github-token:clientsecret"], CallbackPath = new PathString("/signin-github-token"), AuthorizationEndpoint = "https://github.com/login/oauth/authorize", TokenEndpoint = "https://github.com/login/oauth/access_token", SaveTokens = true }); // See config.json app.UseOAuthAuthentication(new OAuthOptions { AuthenticationScheme = "GitHub", DisplayName = "Github", ClientId = Configuration["github:clientid"], ClientSecret = Configuration["github:clientsecret"], CallbackPath = new PathString("/signin-github"), AuthorizationEndpoint = "https://github.com/login/oauth/authorize", TokenEndpoint = "https://github.com/login/oauth/access_token", UserInformationEndpoint = "https://api.github.com/user", ClaimsIssuer = "OAuth2-Github", SaveTokens = true, // Retrieving user information is unique to each provider. Events = new OAuthEvents { OnCreatingTicket = async context => { // Get the GitHub user var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); var user = JObject.Parse(await response.Content.ReadAsStringAsync()); var identifier = user.Value <string>("id"); if (!string.IsNullOrEmpty(identifier)) { context.Identity.AddClaim(new Claim( ClaimTypes.NameIdentifier, identifier, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } var userName = user.Value <string>("login"); if (!string.IsNullOrEmpty(userName)) { context.Identity.AddClaim(new Claim( ClaimsIdentity.DefaultNameClaimType, userName, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } var name = user.Value <string>("name"); if (!string.IsNullOrEmpty(name)) { context.Identity.AddClaim(new Claim( "urn:github:name", name, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } var email = user.Value <string>("email"); if (!string.IsNullOrEmpty(email)) { context.Identity.AddClaim(new Claim( ClaimTypes.Email, email, ClaimValueTypes.Email, context.Options.ClaimsIssuer)); } var link = user.Value <string>("url"); if (!string.IsNullOrEmpty(link)) { context.Identity.AddClaim(new Claim( "urn:github:url", link, ClaimValueTypes.String, context.Options.ClaimsIssuer)); } } } }); // Choose an authentication type app.Map("/login", signoutApp => { signoutApp.Run(async context => { var authType = context.Request.Query["authscheme"]; if (!string.IsNullOrEmpty(authType)) { // By default the client will be redirect back to the URL that issued the challenge (/login?authtype=foo), // send them to the home page instead (/). await context.Authentication.ChallengeAsync(authType, new AuthenticationProperties() { RedirectUri = "/" }); return; } context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync("Choose an authentication scheme: <br>"); foreach (var type in context.Authentication.GetAuthenticationSchemes()) { await context.Response.WriteAsync("<a href=\"?authscheme=" + type.AuthenticationScheme + "\">" + (type.DisplayName ?? "(suppressed)") + "</a><br>"); } await context.Response.WriteAsync("</body></html>"); }); }); // Sign-out to remove the user cookie. app.Map("/logout", signoutApp => { signoutApp.Run(async context => { context.Response.ContentType = "text/html"; await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync("You have been logged out. Goodbye " + context.User.Identity.Name + "<br>"); await context.Response.WriteAsync("<a href=\"/\">Home</a>"); await context.Response.WriteAsync("</body></html>"); }); }); // Display the remote error app.Map("/error", errorApp => { errorApp.Run(async context => { context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync("An remote failure has occurred: " + context.Request.Query["FailureMessage"] + "<br>"); await context.Response.WriteAsync("<a href=\"/\">Home</a>"); await context.Response.WriteAsync("</body></html>"); }); }); // Deny anonymous request beyond this point. app.Use(async(context, next) => { if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) { // The cookie middleware will intercept this 401 and redirect to /login await context.Authentication.ChallengeAsync(); return; } await next(); }); // Display user information app.Run(async context => { context.Response.ContentType = "text/html"; await context.Response.WriteAsync("<html><body>"); await context.Response.WriteAsync("Hello " + (context.User.Identity.Name ?? "anonymous") + "<br>"); foreach (var claim in context.User.Claims) { await context.Response.WriteAsync(claim.Type + ": " + claim.Value + "<br>"); } await context.Response.WriteAsync("Tokens:<br>"); await context.Response.WriteAsync("Access Token: " + await context.Authentication.GetTokenAsync("access_token") + "<br>"); await context.Response.WriteAsync("Refresh Token: " + await context.Authentication.GetTokenAsync("refresh_token") + "<br>"); await context.Response.WriteAsync("Token Type: " + await context.Authentication.GetTokenAsync("token_type") + "<br>"); await context.Response.WriteAsync("expires_at: " + await context.Authentication.GetTokenAsync("expires_at") + "<br>"); await context.Response.WriteAsync("<a href=\"/logout\">Logout</a>"); await context.Response.WriteAsync("</body></html>"); }); }
/// <summary> /// Adds user-defined metadata to the request as one or more name-value pairs. /// </summary> /// <param name="request">The web request.</param> /// <param name="metadata">The user-defined metadata.</param> public static void AddMetadata(HttpRequestMessage request, IDictionary <string, string> metadata) { HttpRequestMessageFactory.AddMetadata(request, metadata); }
/// <summary> /// Called on the initial send /// </summary> /// <param name="request"></param> /// <returns></returns> internal abstract Task AuthenticateAsync(HttpRequestMessage request);
protected IHttpActionResult File(HttpRequestMessage request, string path, string contentType = null) { return(new FileResult(request, path, contentType)); }
/// <summary> /// Called when the send is challenged. /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <returns></returns> internal abstract Task AuthenticateAsync(HttpRequestMessage request, HttpResponseMessage response);
/// <summary> /// The Put Metric Settings operation creates or updates the metric /// settings for the resource. /// </summary> /// <param name='parameters'> /// Required. Metric settings to be created or updated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task <OperationResponse> CreateOrUpdateAsync(MetricSettingsPutParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.MetricSetting == null) { throw new ArgumentNullException("parameters.MetricSetting"); } if (parameters.MetricSetting.ResourceId == null) { throw new ArgumentNullException("parameters.MetricSetting.ResourceId"); } if (parameters.MetricSetting.Value == null) { throw new ArgumentNullException("parameters.MetricSetting.Value"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/monitoring/metricsettings"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; requestDoc = new JObject(); requestDoc["ResourceId"] = parameters.MetricSetting.ResourceId; if (parameters.MetricSetting.Namespace != null) { requestDoc["Namespace"] = parameters.MetricSetting.Namespace; } JObject valueValue = new JObject(); requestDoc["Value"] = valueValue; if (parameters.MetricSetting.Value is AvailabilityMetricSettingValue) { valueValue["odata.type"] = parameters.MetricSetting.Value.GetType().FullName; AvailabilityMetricSettingValue derived = ((AvailabilityMetricSettingValue)parameters.MetricSetting.Value); if (derived.AvailableLocations != null) { JArray availableLocationsArray = new JArray(); foreach (NameConfig availableLocationsItem in derived.AvailableLocations) { JObject nameConfigValue = new JObject(); availableLocationsArray.Add(nameConfigValue); if (availableLocationsItem.Name != null) { nameConfigValue["Name"] = availableLocationsItem.Name; } if (availableLocationsItem.DisplayName != null) { nameConfigValue["DisplayName"] = availableLocationsItem.DisplayName; } } valueValue["AvailableLocations"] = availableLocationsArray; } if (derived.Endpoints != null) { JArray endpointsArray = new JArray(); foreach (EndpointConfig endpointsItem in derived.Endpoints) { JObject endpointConfigValue = new JObject(); endpointsArray.Add(endpointConfigValue); if (endpointsItem.ConfigId != null) { endpointConfigValue["ConfigId"] = endpointsItem.ConfigId; } if (endpointsItem.Name != null) { endpointConfigValue["Name"] = endpointsItem.Name; } if (endpointsItem.Location != null) { endpointConfigValue["Location"] = endpointsItem.Location; } if (endpointsItem.Url != null) { endpointConfigValue["Url"] = endpointsItem.Url.AbsoluteUri; } } valueValue["Endpoints"] = endpointsArray; } } requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpRequest.Content.Headers.ContentType.CharSet = "utf-8"; // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Translates an array of strings from a source language to a target language. /// </summary> /// <param name="translateArraySourceTexts">The strings to translate.</param> /// <param name="from">The language code of the translation text. For example, "en" for English.</param> /// <param name="to">The language code to translate the text into.</param> /// <returns>An array of the translated documents.</returns> public async Task <List <TranslatedDocument> > TranslateArrayAsync(string[] translateArraySourceTexts, string from, string to) { var translatedDocuments = new List <TranslatedDocument>(); var uri = "https://api.microsofttranslator.com/v2/Http.svc/TranslateArray2"; for (var srcTxtIndx = 0; srcTxtIndx < translateArraySourceTexts.Length; srcTxtIndx++) { // Check for literal tag in input user message var currentTranslatedDocument = new TranslatedDocument(translateArraySourceTexts[srcTxtIndx]); translatedDocuments.Add(currentTranslatedDocument); PreprocessMessage(currentTranslatedDocument.SourceMessage, out var processedText, out var literanlNoTranslateList); currentTranslatedDocument.SourceMessage = processedText; translateArraySourceTexts[srcTxtIndx] = processedText; currentTranslatedDocument.LiteranlNoTranslatePhrases = literanlNoTranslateList; } // body of http request var body = $"<TranslateArrayRequest>" + "<AppId />" + $"<From>{from}</From>" + "<Options>" + " <Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" >generalnn</Category>" + "<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">text/plain</ContentType>" + "<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" + "</Options>" + "<Texts>" + string.Join(string.Empty, translateArraySourceTexts.Select(s => $"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">{SecurityElement.Escape(s)}</string>\n")) + "</Texts>" + $"<To>{to}</To>" + "</TranslateArrayRequest>"; var accessToken = await _authToken.GetAccessTokenAsync().ConfigureAwait(false); using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(uri); request.Content = new StringContent(body, Encoding.UTF8, "text/xml"); request.Headers.Add("Authorization", accessToken); using (var response = await _httpClient.SendAsync(request).ConfigureAwait(false)) { var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); switch (response.StatusCode) { case HttpStatusCode.OK: Console.WriteLine("Request status is OK. Result of translate array method is:"); var doc = XDocument.Parse(responseBody); var ns = XNamespace.Get("http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2"); var results = new List <string>(); var sentIndex = 0; foreach (var xe in doc.Descendants(ns + "TranslateArray2Response")) { var currentTranslatedDocument = translatedDocuments[sentIndex]; currentTranslatedDocument.RawAlignment = xe.Element(ns + "Alignment").Value; currentTranslatedDocument.TargetMessage = xe.Element(ns + "TranslatedText").Value; if (!string.IsNullOrEmpty(currentTranslatedDocument.RawAlignment)) { var alignments = currentTranslatedDocument.RawAlignment.Trim().Split(' '); currentTranslatedDocument.SourceTokens = PostProcessingUtilities.SplitSentence(currentTranslatedDocument.SourceMessage, alignments); currentTranslatedDocument.TranslatedTokens = PostProcessingUtilities.SplitSentence(xe.Element(ns + "TranslatedText").Value, alignments, false); currentTranslatedDocument.IndexedAlignment = PostProcessingUtilities.WordAlignmentParse(alignments, currentTranslatedDocument.SourceTokens, currentTranslatedDocument.TranslatedTokens); } sentIndex += 1; } return(translatedDocuments); default: throw new Exception(response.ReasonPhrase); } } } }
public ModelFactory(HttpRequestMessage request, ApplicationUserManager appUserManager) { _UrlHelper = new UrlHelper(request); _AppUserManager = appUserManager; }
private static InternalServerErrorResult CreateProductUnderTest(HttpRequestMessage request) { return new InternalServerErrorResult(request); }
public HttpResponseMessage GetComment(string blogId, string postId, string id, HttpRequestMessage request) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); try { ICommentsService commentsService = ObjectFactory.GetInstance <ICommentsService>(); var comment = commentsService.Get(String.Format("comments/{0}", id)); var etag = request.Headers.IfNoneMatch.FirstOrDefault(); if (etag != null && etag.Tag == comment.etag) { response.StatusCode = HttpStatusCode.NotModified; } else { if (comment != null) { if (this.ClientAcceptsMediaType("text/html", request)) { response.Content = new ObjectContent <string>(comment.ToHtml(), "text/html"); } else { SyndicationFeed commentFeed = new SyndicationFeed { Title = new TextSyndicationContent("Single Comment"), LastUpdatedTime = new DateTimeOffset(DateTime.Now) }; commentFeed.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); SyndicationItem item = new SyndicationItem(); List <SyndicationItem> itemList = new List <SyndicationItem> { item }; commentFeed.Items = itemList; item.Id = comment.Id; item.LastUpdatedTime = comment.updated; item.PublishDate = comment.published; item.Content = new TextSyndicationContent(comment.content); item.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); item.Links.Add(SyndicationLink.CreateAlternateLink(request.RequestUri, "text/html")); item.Links.Add(new SyndicationLink(request.RequestUri, "service.edit", "Edit Comment", "application/atom+xml;type=feed", 0)); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/blogs/{1}/posts/{2}/{3}", this.serviceURI, blogId, postId, comment.Id)), "service.comments", "Post comments", "application/atom+xml;type=feed", 0)); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/blogs/{1}/posts/{2}", this.serviceURI, blogId, postId)), "service.post", "Parent post", "application/atom+xml;type=feed", 0)); item.Authors.Add(new SyndicationPerson(string.Empty, comment.author, string.Empty)); SyndicationFeedFormatter formatter = null; if (this.ClientAcceptsMediaType("application/atom+xml", request)) { formatter = commentFeed.GetAtom10Formatter(); } else { if (this.ClientAcceptsMediaType("application/rss+xml", request)) { formatter = commentFeed.GetRss20Formatter(); } } response.Content = new ObjectContent(typeof(SyndicationFeedFormatter), formatter); } } else { response.StatusCode = HttpStatusCode.NotFound; } } } catch (Exception) { response.StatusCode = HttpStatusCode.InternalServerError; } return(response); }
private static void RetrieveText(string uriToLoad, string cacheFolder, Action <string> updateResult, Action <HttpRequestMessage> addHeaders = null) { var longHash = uriToLoad.GetLongHashCode(); var appDataFileName = ApplicationController.CacheablePath(cacheFolder, longHash.ToString() + ".txt"); string fileText = null; // first try the cache in the users applications folder if (File.Exists(appDataFileName)) { try { lock (locker) { fileText = File.ReadAllText(appDataFileName); } updateResult?.Invoke(fileText); } catch { } } else // We could not find it in the application cache. Check if it is in static data. { var staticDataPath = Path.Combine(cacheFolder, longHash.ToString() + ".txt"); if (StaticData.Instance.FileExists(staticDataPath)) { try { lock (locker) { fileText = StaticData.Instance.ReadAllText(staticDataPath); } updateResult?.Invoke(fileText); } catch { } } } // whether we find it or not check the web for the latest version Task.Run(async() => { var requestMessage = new HttpRequestMessage(HttpMethod.Get, uriToLoad); addHeaders?.Invoke(requestMessage); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(requestMessage)) { var text = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(text) && text != fileText) { File.WriteAllText(appDataFileName, text); updateResult?.Invoke(text); } } } }); }
public HttpResponseMessage GetBlogs(HttpRequestMessage request, int pageIndex = 1, int pageSize = 10) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); try { IBlogsService blogsService = ObjectFactory.GetInstance <IBlogsService>(); List <Blog> blogs = blogsService.GetAll(pageIndex, pageSize); if (blogs != null) { if (this.ClientAcceptsMediaType("text/html", request)) { var blogsHtml = blogs.GenerateBlogsHtml(); response.Content = new ObjectContent <string>(blogsHtml, "text/html"); } else { SyndicationFeed blogsFeed = new SyndicationFeed { Title = new TextSyndicationContent("Blogs List"), LastUpdatedTime = new DateTimeOffset(DateTime.Now) }; blogsFeed.Links.Add(SyndicationLink.CreateSelfLink(request.RequestUri)); List <SyndicationItem> itemList = new List <SyndicationItem>(); blogsFeed.Items = itemList; foreach (var blog in blogs) { SyndicationItem item = new SyndicationItem { Id = blog.Id, LastUpdatedTime = blog.updated, PublishDate = blog.published, Title = new TextSyndicationContent(blog.name), Summary = new TextSyndicationContent(blog.description) }; item.Links.Add(SyndicationLink.CreateSelfLink(new Uri(String.Format("{0}/{1}", this.serviceURI, blog.Id)))); item.Links.Add(SyndicationLink.CreateAlternateLink(request.RequestUri, "text/html")); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/{1}", this.serviceURI, blog.Id)), "service.edit", "Edit Blog", "application/atom+xml;type=feed", 0)); item.Links.Add(new SyndicationLink(new Uri(String.Format("{0}/{1}/posts", this.serviceURI, blog.Id)), "service.posts", "Blog posts", "application/atom+xml;type=feed", 0)); var pagingLinks = this.BuildPagingLinks(blogsService.Count(), pageIndex, pageSize, request.RequestUri); foreach (var link in pagingLinks) { item.Links.Add(link); } item.Authors.Add(new SyndicationPerson(string.Empty, blog.author, string.Empty)); itemList.Add(item); } SyndicationFeedFormatter formatter = null; if (this.ClientAcceptsMediaType("application/atom+xml", request)) { formatter = blogsFeed.GetAtom10Formatter(); } else { if (this.ClientAcceptsMediaType("application/rss+xml", request)) { formatter = blogsFeed.GetRss20Formatter(); } } response.Content = new ObjectContent(typeof(SyndicationFeedFormatter), formatter); } } else { response.StatusCode = HttpStatusCode.NoContent; } } catch (Exception) { response.StatusCode = HttpStatusCode.InternalServerError; } return(response); }
/// <summary> /// Gets an extended server's blob auditing policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <ExtendedServerBlobAuditingPolicy> > GetWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string blobAuditingPolicyName = "default"; string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("blobAuditingPolicyName", blobAuditingPolicyName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/extendedAuditingSettings/{blobAuditingPolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{blobAuditingPolicyName}", System.Uri.EscapeDataString(blobAuditingPolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <ExtendedServerBlobAuditingPolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <ExtendedServerBlobAuditingPolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public static async Task RequestEndAsync(ILogger logger, string typedClientName, string requestId, HttpRequestMessage request, TimeSpan duration, HttpResponseMessage response) { using (LogContext.Push( new PropertyEnricher("RequestId", requestId), new PropertyEnricher("RequestType", request.GetType().Name), new PropertyEnricher("RequestHeaders", GetRequestHeaders(request), true), new PropertyEnricher("RequestBody", await GetRequestBodyAsync(request)), new PropertyEnricher("ResponseHeaders", GetResponseHeaders(response), true), new PropertyEnricher("ResponseBody", await GetResponseBodyAsync(response)))) { LogRequestEnd(logger, typedClientName, "In", request.Method, request.RequestUri, duration.TotalMilliseconds, response.StatusCode, null); } }
private static HttpRequestMessage SetAbsoluteUri(this HttpRequestMessage msg, Microsoft.AspNetCore.Http.HttpRequest req) => msg.Set(m => m.RequestUri = req.GetAbsoluteUri());
internal HttpRequestMessageProperties(HttpRequestMessage request) { Contract.Assert(request != null); _request = request; }
public static void RequestStart(ILogger logger, string typedClientName, string requestId, HttpRequestMessage request) { using (LogContext.Push( new PropertyEnricher("RequestId", requestId), new PropertyEnricher("RequestType", request.GetType().Name))) { LogRequestStart(logger, typedClientName, "Out", request.Method, request.RequestUri, null); } }
public async Task<bool> SendRemoteCommandForAppAsync(string pressedApp) { bool succeeded = false; string address = String.Empty; if (!string.IsNullOrWhiteSpace(pressedApp) && !string.IsNullOrWhiteSpace(_ipAddress)) { address = "http://" + _ipAddress + "/Applications/Lifecycle/open?appId=" + pressedApp; var uri = new Uri(address, UriKind.Absolute); using (HttpClient client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage(); request.RequestUri = new Uri(address); IHttpContent httpContent = new HttpStringContent(String.Empty); try { await client.PostAsync(uri, httpContent); } catch (Exception) { return succeeded = false; } return succeeded = true; } } return succeeded = false; }