public static void AddAlbumXml(HttpClient client)
        {
            client.DefaultRequestHeaders.Accept.Add(new
                MediaTypeWithQualityHeaderValue("application/xml"));

            Console.WriteLine("Enter album title");
            string title = Console.ReadLine();
            Console.WriteLine("Enter album year");
            int year = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter producer");
            string producer = Console.ReadLine();
            Album album = new Album { AlbumTitle = title, AlbumYear = year, Producer = producer };
            HttpResponseMessage response =
                client.PostAsXmlAsync("api/albums", album).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Album added");
            }
            else
            {
                Console.WriteLine("{0} ({1})",
                    (int)response.StatusCode, response.ReasonPhrase);
            }
        }
 /// <summary>
 /// Save order on web api.
 /// </summary>
 /// <param name="newOrder">New Order to be saved.</param>
 /// <returns>Tuple of bool and string, bool == true when API succeded, bool == false when API did not succeed, string == fail message.</returns>
 public Tuple<bool,string> PostOrderAsync(NewOrderInfo newOrder)
 {
     using (var client = new HttpClient())
     {
         try
         {
             client.BaseAddress = _baseAddress;
             var response = client.PostAsXmlAsync("api/order/create", newOrder, new CancellationToken()).Result;
             if (response.IsSuccessStatusCode)
             {
                 var answer = new Tuple<bool, string>(true, response.StatusCode.ToString());
                 return answer;
             }
             else //do failure thing
             {
                 var answer = new Tuple<bool, string>(false, "Could not save the created order: Error from Web api: " + response.StatusCode.ToString() + ": " + response.ReasonPhrase);
                 return answer;
             }
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
Example #3
1
        internal static async void ProcessPostRequests(HttpClient client)
        {
            ResponseAlbumModel album = new ResponseAlbumModel
            {
                Title = "Xml added",
                ProducerName = "Xml Produer",
                Year = 2000
            };

            var httpResponse = await client.PostAsXmlAsync("api/albums", album);
            Console.WriteLine(httpResponse.ReasonPhrase.ToString() + " from albums");
        }
Example #4
0
 public void PostAsXmlAsync_String_WhenUriIsNull_ThrowsException()
 {
     Assert.Throws <InvalidOperationException>(
         () => _client.PostAsXmlAsync((string)null, new object()),
         "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."
         );
 }
        public static void AddArtistXml(HttpClient client)
        {
            client.DefaultRequestHeaders.Accept.Add(new
                MediaTypeWithQualityHeaderValue("application/xml"));

            Console.WriteLine("Enter artist name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter artist country");
            string country = Console.ReadLine();
            Console.WriteLine("Enter artist birth date");
            DateTime birthDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US"));
            Artist artist = new Artist { Name = name, Country = country, DateOfBirth = birthDate };
            HttpResponseMessage response =
                client.PostAsXmlAsync("api/artists", artist).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Artist added");
            }
            else
            {
                Console.WriteLine("{0} ({1})",
                    (int)response.StatusCode, response.ReasonPhrase);
            }
        }
        public static void AddSongXml(HttpClient client)
        {
            client.DefaultRequestHeaders.Accept.Add(new
                MediaTypeWithQualityHeaderValue("application/xml"));

            Console.WriteLine("Enter song title");
            string title = Console.ReadLine();
            Console.WriteLine("Enter song year");
            int year = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter song genre code");
            Genre genre = (Genre)int.Parse(Console.ReadLine());
            Console.WriteLine("Enter song description");
            string description = Console.ReadLine();
            Console.WriteLine("Enter song artist id");
            int id = int.Parse(Console.ReadLine());
            Song song = new Song { SongTitle = title, SongYear = year, SongGenre = genre, Description = description, ArtistId = id };
            HttpResponseMessage response =
                client.PostAsXmlAsync("api/songs", song).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Song added");
            }
            else
            {
                Console.WriteLine("{0} ({1})",
                    (int)response.StatusCode, response.ReasonPhrase);
            }
        }
        public async Task <T> PostAsync <P, T>(string relativePath, P submittingData, string mediaType = "application/json")
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(BaseUrl);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));

                HttpResponseMessage response = null;
                if (submittingData.GetType() == typeof(FormUrlEncodedContent))
                {
                    response = await client.PostAsync(relativePath, ((FormUrlEncodedContent)Convert.ChangeType(submittingData, typeof(FormUrlEncodedContent))));
                }
                else if ((mediaType?.ToLower()).Contains("xml"))
                {
                    response = await client.PostAsXmlAsync <P>(relativePath, submittingData);
                }
                else
                {
                    response = await client.PostAsJsonAsync <P>(relativePath, submittingData);
                }

                response.EnsureSuccessStatusCode();
                T result = await response.Content.ReadAsAsync <T>();

                return(result);
            }
        }
Example #8
0
        public void PostAsXmlAsync_String_WhenClientIsNull_ThrowsException()
        {
            HttpClient client = null;

            Assert.ThrowsArgumentNull(
                () => client.PostAsXmlAsync("http://www.example.com", new object()),
                "client"
                );
        }
        public async void PostCanRespondInXml()
        {
            var message = new MessageDto
            {
                Text = "This is XML"
            };
            var client = new HttpClient(_server);
            var response = await client.PostAsXmlAsync(Url + "hello", message);

            var result = await response.Content.ReadAsAsync<MessageDto>(new [] {new XmlMediaTypeFormatter() });
            
            Assert.Equal(message.Text, result.Text);
        }
		public static async Task NotifySites()
		{
			BlogConfigurationDto configuration = configurationDataService.GetConfiguration();
			IEnumerable<Uri> pingSites = pingDataService.GetPingSites();

			foreach (Uri pingSite in pingSites)
			{
				using (HttpClient client = new HttpClient())
				{
					await client.PostAsXmlAsync(pingSite.ToString(), GetRequest(pingSite, configuration));
				}
			}
		}
        public static void Post <TRequest, TResponse>(this HttpClient httpClient, string requestUri, TRequest content, DataFormat dataFormat,
                                                      out HttpResponseMessage httpResponseMessage,
                                                      out string responseString,
                                                      out TResponse response) where TResponse : class where TRequest : class
        {
            httpClient.DefaultRequestHeaders.Accept.Clear();

            switch (dataFormat)
            {
            case DataFormat.Xml:
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
                httpResponseMessage = httpClient.PostAsXmlAsync(requestUri, content).Result;
                responseString      = httpResponseMessage.Content.ReadAsStringAsync().Result;
                try
                {
                    response = responseString.ToXml <TResponse>();
                }
                catch
                {
                    response = null;
                }
            }
            break;

            default:
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpResponseMessage = httpClient.PostAsJsonAsync(requestUri, content).Result;
                responseString      = httpResponseMessage.Content.ReadAsStringAsync().Result;
                try
                {
                    response = JsonConvert.DeserializeObject <TResponse>(responseString);
                }
                catch
                {
                    response = null;
                }
            }
            break;
            }
        }
Example #12
0
        internal static Song AddNewSongAsXML(HttpClient Client, string title, int year, string genre, Artist artist)
        {
            var album = new Song() { Title = title, Year = year, Genre = genre, Artist = artist };

            var response = Client.PostAsXmlAsync("api/Songs", album).Result;

            Song resultSong = response.Content.ReadAsAsync<Song>().Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Song added!");
                return resultSong;
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            return new Song();
        }
Example #13
0
        internal static Album AddNewAlbumAsXml(HttpClient Client, string title, int year, string producer, ICollection<Song> songs, ICollection<Artist> artists)
        {
            var album = new Album() { Title = title, Year = year, Producer = producer, Songs = songs, Artists = artists };

            var response = Client.PostAsXmlAsync("api/Albums", album).Result;

            Album resultAlbum = response.Content.ReadAsAsync<Album>().Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Album added!");
                return resultAlbum;
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            return new Album();
        }
Example #14
0
        internal static Artist AddNewArtistAsXml(HttpClient Client, string name, string country, DateTime dateOfBirth)
        {
            var artist = new Artist { Name = name, Country = country, DateOfBirth = dateOfBirth };

            var response = Client.PostAsXmlAsync("api/Artists", artist).Result;

            Artist resultArtist = response.Content.ReadAsAsync<Artist>().Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Artist added!");
                return resultArtist;
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            return new Artist();
        }
        public static void AddSong(HttpClient client, Song song)
        {
            HttpResponseMessage response;
            if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")))
            {
                response = client.PostAsJsonAsync("api/songs", song).Result;
            }
            else
            {
                response = client.PostAsXmlAsync("api/songs", song).Result;
            }

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Artist {0} added successfully", song.Title);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
		public static async Task Notify(ItemDto item, Uri uri)
		{
			SiteUrl itemUrl = item is PostDto
				                  ? urlBuilder.Post.Permalink(item)
				                  : urlBuilder.Page.Permalink(item);

			using (HttpClient client = new HttpClient())
			{
				HttpResponseMessage response = await client.GetAsync(uri);

				KeyValuePair<string, IEnumerable<string>> header = response.Headers.SingleOrDefault(h => h.Key.Equals("x-pingback", StringComparison.OrdinalIgnoreCase) || h.Key.Equals("pingback", StringComparison.OrdinalIgnoreCase));

				string urlToPing = header.Value.FirstOrDefault();

				if (string.IsNullOrEmpty(urlToPing))
				{
					return;
				}

				var xmlRequest = GetXmlRequest(itemUrl, uri);

				await client.PostAsXmlAsync(urlToPing, xmlRequest);
			}
		}
Example #17
0
        private Uri SaveInfoToWebApi <U>(string path, U model)
        {
            var httpClient = new System.Net.Http.HttpClient
            {
                BaseAddress = new Uri(baseUri + path),
                Timeout     = TimeSpan.FromSeconds(8),
            };

            try
            {
                var response = httpClient.PostAsXmlAsync("", model).Result;
                response.EnsureSuccessStatusCode();
                if (response.IsSuccessStatusCode)
                {
                    // Get the URI of the created resource.
                    return(response.Headers.Location);
                }
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
Example #18
0
 /// <summary>
 /// Sends a POST request as an asynchronous operation to the specified Uri with the given <paramref name="value"/> serialized
 /// as XML.
 /// </summary>
 /// <remarks>
 /// This method uses the default instance of <see cref="XmlMediaTypeFormatter"/>.
 /// </remarks>
 /// <typeparam name="T">The type of <paramref name="value"/>.</typeparam>
 /// <param name="client">The client used to make the request.</param>
 /// <param name="requestUri">The Uri the request is sent to.</param>
 /// <param name="value">The value that will be placed in the request's entity body.</param>
 /// <returns>A task object representing the asynchronous operation.</returns>
 public static Task <HttpResponseMessage> PostAsXmlAsync <T>(this HttpClient client, Uri requestUri, T value)
 {
     return(client.PostAsXmlAsync(requestUri, value, CancellationToken.None));
 }
 public static async void Add(HttpClient httpClient, SongApiModel song)
 {
     var response = await httpClient.PostAsXmlAsync("song", song);
     Console.WriteLine("Done!");
 }
 public void When_POST_typed_XML_content_can_be_read()
 {
     var reqModel = new SomeModel
     {
         AnInteger = 2,
         AString = "hello"
     };
     var client = new HttpClient();
     client.PostAsXmlAsync(_baseAddress + "Test", reqModel);
     TestController.OnPost(req =>
     {
         var recModel = req.Content.ReadAsAsync<SomeModel>().Result;
         Assert.Equal(reqModel.AnInteger, recModel.AnInteger);
         Assert.Equal(reqModel.AString, recModel.AString);
         return new HttpResponseMessage();
     });
 }
Example #21
0
        public void PostVPN()
        {
            string baseAddress = "http://localhost:6000/";
              var request_payload = new SendRequest() { VPNKey = "vpn1", Topic = "A/B", Message = "msg1", CorrelationID = 123 };
              using (Microsoft.Owin.Hosting.WebApp.Start<VpnStartup>(url: baseAddress))
              {
            using (var client = new System.Net.Http.HttpClient())
            {
              var response = client.PostAsXmlAsync(baseAddress + "api/vpn", request_payload).Result;

              Assert.AreEqual<string>("vpn1", VpnController.received_request.VPNKey);
              Assert.AreEqual<string>("A/B", VpnController.received_request.Topic);
              Assert.AreEqual<string>("msg1", VpnController.received_request.Message);
              Assert.AreEqual<uint>(123, VpnController.received_request.CorrelationID );

              Assert.IsTrue(response.IsSuccessStatusCode);
              Assert.AreEqual<System.Net.HttpStatusCode>(System.Net.HttpStatusCode.OK, response.StatusCode);
              Assert.AreEqual<string>("OK", response.ReasonPhrase);
              string response_xml = response.Content.ReadAsStringAsync().Result;
              Assert.IsTrue(response_xml.Length > 0);
              var response_doc = XDocument.Parse(response_xml);

              XNamespace ns = "http://schemas.datacontract.org/2004/07/ContractLib";

              Assert.IsNotNull(response_doc.Root);
              Assert.IsTrue(response_doc.Root.HasElements);
              Assert.AreEqual<int>(3, response_doc.Root.Elements().Count());
              var correlationID = response_doc.Root.Element(ns + "CorrelationID");
              Assert.IsNotNull(correlationID);
              var status = response_doc.Root.Element(ns + "Status");
              Assert.IsNotNull(status);
              var description = response_doc.Root.Element(ns + "Description");
              Assert.IsNotNull(description);

              Assert.AreEqual<string>("123", correlationID.Value);
              Assert.AreEqual<string>("102", status.Value);
              Assert.AreEqual<string>(string.Format("{0}|{1}|{2}", request_payload.VPNKey, request_payload.Topic, request_payload.Message), description.Value);
            }
              }
        }
Example #22
0
        static void Main(string[] args)
        {
            // Prepare for a simple HttpPost request
            var client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:61924/");

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            // Get the body of the request
            var vMRRequest = GetSampleRequest();

            // Construct the DSS-level request, base-64 encoding the vMR request within it.
            var evaluate = 
                new evaluate 
                { 
                    interactionId =
                        new InteractionIdentifier 
                        { 
                            interactionId = Guid.NewGuid().ToString("N"), 
                            scopingEntityId = "SAMPLE-CLIENT", 
                            submissionTime = DateTime.Now.ToUniversalTime() 
                        },
                    evaluationRequest =
                        new EvaluationRequest
                        {
                            clientLanguage = "XXX",
                            clientTimeZoneOffset = "XXX",
                            dataRequirementItemData = new List<DataRequirementItemData> 
                            { 
                                new DataRequirementItemData
                                {
                                    driId = new ItemIdentifier { itemId = "RequiredDataId" },
                                    data = 
                                        new SemanticPayload 
                                        { 
                                            informationModelSSId = SemanticSignifiers.CDSInputId, 
                                            base64EncodedPayload = Packager.EncodeRequestPayload(vMRRequest) 
                                        }
                                }
                            },
                            kmEvaluationRequest = new List<KMEvaluationRequest> 
                            { 
                                new KMEvaluationRequest { kmId = new EntityIdentifier { scopingEntityId = "org.hl7.cds", businessId = "NQF-0068", version = "1.0" } }
                            }
                        }
                };

            // Post the request and retrieve the response
            var response = client.PostAsXmlAsync("api/evaluation", evaluate).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Evaluation succeeded.");
                var evaluateResponse = response.Content.ReadAsAsync<evaluateResponse>().Result;

                var evaluationResponse = evaluateResponse.evaluationResponse.finalKMEvaluationResponse.First();

                if (evaluationResponse.kmId.scopingEntityId != "SAMPLE-CLIENT")
                {
                    Console.WriteLine("Evaluation did not return the input scoping entity Id.");
                }

                var evaluationResult = evaluationResponse.kmEvaluationResultData.First();

                if (!SemanticSignifiers.AreEqual(evaluationResult.data.informationModelSSId, SemanticSignifiers.CDSActionGroupResponseId))
                {
                    Console.WriteLine("Evaluation did not return an action group response.");
                }

                var actionGroupResponse = Packager.DecodeActionGroupResponsePayload(evaluationResult.data.base64EncodedPayload);

                var createAction = actionGroupResponse.actionGroup.subElements.Items.First() as CreateAction;

                if (createAction == null)
                {
                    Console.WriteLine("Result does not include a CreateAction.");
                }
                else
                {
                    var proposalLiteral = createAction.actionSentence as elm.Instance;
                    if (proposalLiteral == null)
                    {
                        Console.WriteLine("Resulting CreateAction does not have an ELM Instance as the Action Sentence.");
                    }
                    else
                    {
						if (proposalLiteral.classType.Name != "SubstanceAdministrationProposal")
                        {
                            Console.WriteLine("Resulting proposal is not a substance administration proposal");
                        }
                        else
                        {
                            Console.WriteLine("Substance Administration Proposed: {0}.", (proposalLiteral.element.Single(e => e.name == "substanceAdministrationGeneralPurpose").value as elm.Code).display);
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

                var content = response.Content.ReadAsStringAsync().Result;
                if (content.Length > 0)
                {
                    // NOTE: Deserialization here is assuming EvaluationException, need to peek into the Xml stream to determine the actual type.
                    var dssException = DSSExceptionExtensions.DeserializeFromString<EvaluationException>(content);
                    Console.WriteLine(dssException.GetType().Name);
                    Console.WriteLine(String.Join("\r\n", dssException.errorMessage));
                    if (dssException.value != null)
                    {
                        var cdsMessage = Packager.DecodeExecutionMessagePayload(dssException.value.base64EncodedPayload);
                        Console.WriteLine(cdsMessage.GetType().Name);
                        Console.WriteLine(cdsMessage.message.value);
                    }
                }
            }

            Console.ReadLine();
        }
Example #23
0
        public void PostValueAsXML()
        {
            string baseAddress = "http://localhost:9003/";
              const string posted_datakey = "posted";
              using (Microsoft.Owin.Hosting.WebApp.Start<ValuesStartup>(url: baseAddress))
              {
            using (var client = new System.Net.Http.HttpClient())
            {
              var response = client.PostAsXmlAsync(baseAddress + "api/values", posted_datakey).Result;

              Assert.IsTrue(response.IsSuccessStatusCode);
              Assert.AreEqual<System.Net.HttpStatusCode>(System.Net.HttpStatusCode.NoContent, response.StatusCode);
              Assert.AreEqual<string>("No Content", response.ReasonPhrase);

              Assert.IsNotNull(ValuesController.PostRequest);
              Assert.IsTrue(ValuesController.PostRequest.ContainsKey(posted_datakey));
              Assert.AreEqual<string>("application/xml; charset=utf-8", ValuesController.PostRequest[posted_datakey].Content.Headers.ContentType.ToString());
              Assert.IsNotNull(ValuesController.PostRequestValue);
              Assert.IsTrue(ValuesController.PostRequestValue.Contains(posted_datakey));
            }
              }
        }
Example #24
-1
        public static void AddSong(HttpClient client, Song song)
        {
            HttpResponseMessage response = null;

            if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/xml")))
            {
                response = client.PostAsXmlAsync<Song>("api/Song", song).Result;
            }
            else if (client.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")))
            {
                response = client.PostAsJsonAsync<Song>("api/Song", song).Result;
            }

            if (response == null)
            {
                throw new InvalidOperationException("Client must use json or xml.");
            }

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Song added.");
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }