protected async Task<Boolean> CreateItems(string token)
		{
			var client = new HttpClient();
			client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
			var mediaType = new MediaTypeWithQualityHeaderValue ("application/json");
			mediaType.Parameters.Add (new NameValueHeaderValue ("odata", "verbose"));
			client.DefaultRequestHeaders.Accept.Add (mediaType);

			var itemToCreateTitle = "Item created on: " + DateTime.Now.ToString("dd/MM HH:mm");
			var body = "{\"__metadata\":{\"type\":\"SP.Data.TasksByAndroidListItem\"},\"Title\":\"" + itemToCreateTitle + "\",\"Status\": \"Not Started\"}";
			var contents = new StringContent (body);
			contents.Headers.ContentType = MediaTypeHeaderValue.Parse( "application/json;odata=verbose");
			try {

				var postResult = await client.PostAsync ("https://mayurtendulkar.sharepoint.com/_api/web/lists/GetByTitle('TasksByAndroid')/items", contents);
				var result = postResult.EnsureSuccessStatusCode();
				if(result.IsSuccessStatusCode)
					Toast.MakeText (this, "List item created successfully!", ToastLength.Long).Show();
				return true;
			} catch (Exception ex) {
				var msg = "Unable to create list item. " + ex.Message;
				Toast.MakeText (this, msg, ToastLength.Long).Show();
				return false;
			}
		}
        public void TryParse_SetOfValidValueStringsForMediaTypeWithQuality_ParsedCorrectly()
        {
            MediaTypeWithQualityHeaderValue expected = new MediaTypeWithQualityHeaderValue("text/plain");
            CheckValidParsedValue("\r\n text/plain  ", 0, expected, 15, true);
            CheckValidParsedValue("text/plain", 0, expected, 10, true);
            CheckValidParsedValue("\r\n text/plain  , next/mediatype", 0, expected, 17, true);
            CheckValidParsedValue("text/plain, next/mediatype", 0, expected, 12, true);
            CheckValidParsedValue("  ", 0, null, 2, true);
            CheckValidParsedValue("", 0, null, 0, true);
            CheckValidParsedValue(null, 0, null, 0, true);
            CheckValidParsedValue("  ,,", 0, null, 4, true);

            // Note that even if the whole string is invalid, the first media-type value is valid. When the parser
            // gets called again using the result-index (13), then it fails: I.e. we have 1 valid media-type and an
            // invalid one.
            CheckValidParsedValue("text/plain , invalid", 0, expected, 13, true);

            // We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
            // The purpose of this test is to verify that these other parsers are combined correctly to build a 
            // media-type parser.
            expected.CharSet = "utf-8";
            CheckValidParsedValue("\r\n text   /  plain ;  charset =   utf-8 ", 0, expected, 40, true);
            CheckValidParsedValue("  text/plain;charset=utf-8", 2, expected, 26, true);
            CheckValidParsedValue("\r\n text   /  plain ;  charset =   utf-8  , next/mediatype", 0, expected, 43, true);
            CheckValidParsedValue("  text/plain;charset=utf-8, next/mediatype", 2, expected, 28, true);
        }
        public void Clone_Call_CloneFieldsMatchSourceFields()
        {
            // This test just verifies that MediaTypeWithQualityHeaderValue calls the correct base implementation.
            MediaTypeWithQualityHeaderValue source = new MediaTypeWithQualityHeaderValue("application/xml");
            MediaTypeWithQualityHeaderValue clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.MediaType, clone.MediaType);
            Assert.Equal(0, clone.Parameters.Count);

            source.CharSet = "utf-8";
            source.Quality = 0.1;
            clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.MediaType, clone.MediaType);
            Assert.Equal("utf-8", clone.CharSet);
            Assert.Equal(0.1, clone.Quality);
            Assert.Equal(2, clone.Parameters.Count);

            source.Parameters.Add(new NameValueHeaderValue("custom", "customValue"));
            clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
            Assert.Equal(source.MediaType, clone.MediaType);
            Assert.Equal("utf-8", clone.CharSet);
            Assert.Equal(0.1, clone.Quality);
            Assert.Equal(3, clone.Parameters.Count);
            Assert.Equal("custom", clone.Parameters.ElementAt(2).Name);
            Assert.Equal("customValue", clone.Parameters.ElementAt(2).Value);
        }
        public void Compare_Returns_0_For_MediaTypeHeaderValues_With_Same_Q_Value()
        {
            MediaTypeHeaderValueComparer comparer = MediaTypeHeaderValueComparer.Comparer;

            MediaTypeWithQualityHeaderValue mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml", 0.5);
            MediaTypeWithQualityHeaderValue mediaType2 = new MediaTypeWithQualityHeaderValue("text/xml", 0.50);
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml", .7);
            mediaType2 = new MediaTypeWithQualityHeaderValue("application/xml", .7);
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml");
            mediaType2 = new MediaTypeWithQualityHeaderValue("text/xml");
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml");
            mediaType2 = new MediaTypeWithQualityHeaderValue("text/plain");
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("text/*", 0.3);
            mediaType2 = new MediaTypeWithQualityHeaderValue("text/*", .3);
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("*/*");
            mediaType2 = new MediaTypeWithQualityHeaderValue("*/*");
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");

            mediaType1 = new MediaTypeWithQualityHeaderValue("text/*", .1);
            mediaType2 = new MediaTypeWithQualityHeaderValue("application/xml", .1);
            Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
        }
Beispiel #5
0
        public static List<UserModel> GetUsers(string accessToken)
        {
            List<UserModel> users = new List<UserModel>();
            MediaTypeWithQualityHeaderValue Json = new MediaTypeWithQualityHeaderValue("application/json");

            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, @"https://graph.microsoft.com/v1.0/users"))
                {
                    request.Headers.Accept.Add(Json);
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    using (var response = client.SendAsync(request).Result)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);

                            foreach (JToken user in json.SelectToken("value").Children())
                            {
                                users.Add(new UserModel(user));
                            }
                        }
                    }
                }
            }
            return users;
        }
Beispiel #6
0
        private async Task<JToken> SendAsync(HttpMethod method, string endpoint, bool acceptJson = true, HttpContent content = null)
        {
            var requestUrl = new Uri(_serverUrl, endpoint);
            var request = new HttpRequestMessage(method, requestUrl);

            if (acceptJson)
            {
                var acceptJsonHeader = new MediaTypeWithQualityHeaderValue("application/json");
                request.Headers.Accept.Add(acceptJsonHeader);
            }

            if (content != null)
            {
                request.Content = content;
            }

            var response = await _httpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();

            if (acceptJson)
            {
                var json = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<JToken>(json);
            }

            return null;
        }
Beispiel #7
0
        public async void RenameAsset(IAsset asset, string newName)
        {
            // Create the request
            var client = new HttpClient();
            var resource = string.Format("https://wamsbluclus001rest-hs.cloudapp.net/API/Assets('{0}')", asset.Id);
            var request = new HttpRequestMessage(new HttpMethod("MERGE"), resource);

            // Set the request content
            var content = string.Format("{{ 'Name' : '{0}' }}", newName);
            var stringContent = new StringContent(content, Encoding.UTF8, "application/json");
            var oDataParameter = new NameValueHeaderValue("odata", "verbose");
            stringContent.Headers.ContentType.Parameters.Add(oDataParameter);
            request.Content = stringContent;
            
            // Set the request headers
            var jsonAccessToken = await this.GetAccessToken();
            string accessToken = JsonConvert.DeserializeObject<dynamic>(jsonAccessToken).access_token.Value;
            request.Headers.Add("Authorization", "Bearer " + accessToken);
            request.Headers.Add("DataServiceVersion", "3.0");
            request.Headers.Add("MaxDataServiceVersion", "3.0");
            request.Headers.Add("x-ms-version", "1.0");
            request.Headers.Host = "wamsbluclus001rest-hs.cloudapp.net";
            var mediaType = new MediaTypeWithQualityHeaderValue("application/json");
            mediaType.Parameters.Add(oDataParameter);
            client.DefaultRequestHeaders.Accept.Add(mediaType);

            // Make the request
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }
        public async Task When_POST_request_headers_are_preserved()
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Post, _baseAddress + "Test");
            var acceptHeaders = new MediaTypeWithQualityHeaderValue[]
            {
                new MediaTypeWithQualityHeaderValue("text/plain"),
                new MediaTypeWithQualityHeaderValue("application/xml", 0.13)
            };
            foreach (var h in acceptHeaders) { request.Headers.Accept.Add(h); }
            request.Headers.Add("X-CustomHeader", "value1");
            request.Headers.Add("X-CustomHeader", "value2");
            request.Content = new StringContent("some content");
            request.Content.Headers.ContentLanguage.Add("en-gb");
            request.Content.Headers.ContentLanguage.Add("en-us");
            var rt = client.SendAsync(request);
            TestController.OnPost(req =>
            {
                foreach (var h in acceptHeaders)
                {
                    Assert.True(req.Headers.Accept.Contains(h));
                }
                var customHeader = req.Headers.First(kvp => kvp.Key == "X-CustomHeader");
                Assert.NotNull(customHeader);
                Assert.True(customHeader.Value.Any(s => s.Contains("value1")));
                Assert.True(customHeader.Value.Any(s => s.Contains("value2")));
                Assert.True(req.Content.Headers.ContentLanguage.Contains("en-gb"));
                Assert.True(req.Content.Headers.ContentLanguage.Contains("en-us"));

                return new HttpResponseMessage();
            });
            var response = await rt;
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
        public void SelectsSuperItemBasedOnParameter_5LMT()
        {
            // arrange
            var configuration = new HttpConfiguration();
            configuration.Services.Replace(typeof(IHttpActionSelector), new MediaTypeBasedActionSelector());
            configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            configuration.AddFiveLevelsOfMediaType();
            var server = new InMemoryServer(configuration);
            var client = new HttpClient(server);
            var request = new HttpRequestMessage(HttpMethod.Get, "http://lhasa/api/Item/1");
            var headerValue = new MediaTypeWithQualityHeaderValue("application/json");
            headerValue.Parameters.Add(new NameValueHeaderValue("domain-model", "SuperItem"));
            request.Headers.Accept.Add(headerValue);

            // act
            var response = client.SendAsync(request).Result;
            var content = response.Content.ReadAsStringAsync().Result;
            var mediaType = response.Content.Headers.ContentType.ExtractFiveLevelsOfMediaType();

            // assert
            Assert.Equal("SuperItem", mediaType.DomainModel);
        }
 public void Ctor_AddNameAndQuality_QualityParameterAdded()
 {
     MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/xml", 0.08);
     Assert.Equal(0.08, mediaType.Quality);
     Assert.Equal("application/xml", mediaType.MediaType);
     Assert.Equal(1, mediaType.Parameters.Count);
 }
        private int ExtractApiVersion(MediaTypeWithQualityHeaderValue header)
        {
            var apiVersionIndex = header.MediaType.IndexOf("api.v", StringComparison.InvariantCultureIgnoreCase) + 5;
            var formatSpecificationIndex = header.MediaType.IndexOf("+", StringComparison.InvariantCultureIgnoreCase);
            var versionTextLength = formatSpecificationIndex - apiVersionIndex;

            return int.Parse(header.MediaType.Substring(apiVersionIndex, versionTextLength));
        }
        // Private helpers
        private static HttpRequestMessage ConstructRequest(
            HttpMethod httpMethod, string uri,
            MediaTypeWithQualityHeaderValue mediaType) {

            return ConstructRequest(
                httpMethod, 
                uri, 
                new[] { mediaType });
        }
		public static bool TryParse (string input, out MediaTypeWithQualityHeaderValue parsedValue)
		{
			var lexer = new Lexer (input);
			Token token;
			if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
				return true;

			parsedValue = null;
			return false;
		}
Beispiel #14
0
 static Program()
 {
     _formatters = new List<MediaTypeFormatter> { new JsonMediaTypeFormatter
     {
         SerializerSettings = new JsonSerializerSettings
         {
             TypeNameHandling = TypeNameHandling.Objects
         }
     }};
     _mediaTypeJson = new MediaTypeWithQualityHeaderValue("application/json");
 }
        public void CreateAcceptHeader()
        {
            var expected = new MediaTypeWithQualityHeaderValue("application/json");
            var sut = new SutBuilder<RequestHeaderFactory>().Build();

            using (var client = new HttpClient())
            {
                sut.SetHeaders(client.DefaultRequestHeaders);

                Assert.AreEqual(client.DefaultRequestHeaders.Accept.First(), expected);
            }
        }
		public void Equals ()
		{
			var value = new MediaTypeWithQualityHeaderValue ("audio/x");
			Assert.AreEqual (value, new MediaTypeWithQualityHeaderValue ("audio/x"), "#1");
			Assert.AreEqual (value, new MediaTypeWithQualityHeaderValue ("aUdio/X"), "#2");
			Assert.AreNotEqual (value, new MediaTypeWithQualityHeaderValue ("audio/y"), "#3");

			value = new MediaTypeWithQualityHeaderValue ("audio/x", 0.3);
			Assert.AreEqual (value, new MediaTypeWithQualityHeaderValue ("audio/x", 0.3), "#4");
			Assert.AreNotEqual (value, new MediaTypeWithQualityHeaderValue ("audio/x"), "#5");
			Assert.AreNotEqual (value, new MediaTypeWithQualityHeaderValue ("audio/Y", 0.6), "#6");
		}
        public static bool TryParse(string input, out MediaTypeWithQualityHeaderValue parsedValue)
        {
            int index = 0;
            object output;
            parsedValue = null;

            if (MediaTypeHeaderParser.SingleValueWithQualityParser.TryParseValue(input, null, ref index, out output))
            {
                parsedValue = (MediaTypeWithQualityHeaderValue)output;
                return true;
            }
            return false;
        }
        private ODataMessageReader GetODataMessageReader(string content)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/odata/CEO");

            request.Content = new StringContent(content);
            request.Headers.Add("OData-Version", "4.0");

            MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/json");
            mediaType.Parameters.Add(new NameValueHeaderValue("odata.metadata", "full"));
            request.Headers.Accept.Add(mediaType);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            return new ODataMessageReader(new HttpRequestODataMessage(request), new ODataMessageReaderSettings(), _edmModel);
        }
        public void Quality_SetCharSetAndValidateObject_ParametersEntryForCharSetAdded()
        {
            MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("text/plain");
            mediaType.Quality = 0.563156454;
            Assert.Equal(0.563, mediaType.Quality);
            Assert.Equal(1, mediaType.Parameters.Count);
            Assert.Equal("q", mediaType.Parameters.First().Name);
            Assert.Equal("0.563", mediaType.Parameters.First().Value);

            mediaType.Quality = null;
            Assert.Null(mediaType.Quality);
            Assert.Equal(0, mediaType.Parameters.Count);
            mediaType.Quality = null; // It's OK to set it again to null; no exception.
        }
        private static IODataRequestMessage GetODataMessage(string content)
        {
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("Patch"), "http://localhost/OData/Suppliers(1)/Address");

            request.Content = new StringContent(content);
            request.Headers.Add("OData-Version", "4.0");

            MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/json");
            mediaType.Parameters.Add(new NameValueHeaderValue("odata.metadata", "full"));
            request.Headers.Accept.Add(mediaType);
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            return new HttpRequestODataMessage(request);
        }
        private static bool FormatterSuportsMediaType(MediaTypeWithQualityHeaderValue mediaType, MediaTypeFormatter formatter)
        {
            var supportsMediaType = formatter.SupportedMediaTypes.Contains(mediaType);
            var supportsTypeGroup = formatter.SupportedMediaTypes.Any(mt =>
                                                                          {
                                                                              var splitMediaType = mt.MediaType.Split('/');
                                                                              var type = splitMediaType.First();
                                                                              return mediaType.MediaType.StartsWith(type);
                                                                          });

            var isTypeGroup = mediaType.MediaType.Split('/').Last() == "*";
            var isAllMediaType = mediaType.MediaType == allMediaTypesRange;

            return isAllMediaType || supportsMediaType || (isTypeGroup && supportsTypeGroup);
        }
 public ModernWebRequester([NotNull] ILog log)
 {
     if (log == null)
         throw new ArgumentNullException("log");
     _log = log;
     WorkingClients = new List<HttpClient>();
     FreeClients = new List<HttpClient>();
     objectLock = new object();
     headersLock = new object();
     authHeaders = new Dictionary<string, AuthenticationHeaderValue>();
     enigma1MediaTypeHeader = new MediaTypeWithQualityHeaderValue("text/html");
     enigma2MediaTypeHeader = new MediaTypeWithQualityHeaderValue("text/xml");
     uriCache = new Dictionary<string, Uri>();
     uriLock = new object();
 }
        protected override string GetVersion(MediaTypeWithQualityHeaderValue mimeType) {
            if (!String.Equals(mimeType.MediaType, AcceptMediaType, StringComparison.InvariantCultureIgnoreCase)) {
                return null;
            }

            // get version
            NameValueHeaderValue versionParameter =
                mimeType.Parameters.FirstOrDefault(parameter => parameter.Name == "version");

            if (versionParameter == null || String.IsNullOrWhiteSpace(versionParameter.Value)) {
                return null;
            }

            return versionParameter.Value;
        }
        public void Response_Contains_ContentType(string contentType)
        {
            // Arrange
            MediaTypeWithQualityHeaderValue requestContentType = new MediaTypeWithQualityHeaderValue(contentType);
            MediaTypeHeaderValue responseContentType = null;

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, baseUri);
            request.Headers.Accept.Add(requestContentType);
            HttpResponseMessage response = httpClient.SendAsync(request).Result;
            response.EnsureSuccessStatusCode();
            responseContentType = response.Content.Headers.ContentType;

            // Assert
            Assert.Equal(requestContentType.MediaType, responseContentType.MediaType);
        }
        public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
        {
            headers.TryAddWithoutValidation("Accept",
                ",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,");

            MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
            value1.CharSet = "iso-8859-1";
            value1.Quality = 1.0;

            MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml");
            value2.CharSet = "utf-8";
            value2.Quality = 0.5;

            Assert.Equal(value1, headers.Accept.ElementAt(0));
            Assert.Equal(value2, headers.Accept.ElementAt(1));
        }
        public void Quality_AddQualityParameterThenUseProperty_ParametersEntryIsOverwritten()
        {
            MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("text/plain");

            NameValueHeaderValue quality = new NameValueHeaderValue("q", "0.132");
            mediaType.Parameters.Add(quality);
            Assert.Equal(1, mediaType.Parameters.Count);
            Assert.Equal("q", mediaType.Parameters.First().Name);
            Assert.Equal(0.132, mediaType.Quality);

            mediaType.Quality = 0.9;
            Assert.Equal(0.9, mediaType.Quality);
            Assert.Equal(1, mediaType.Parameters.Count);
            Assert.Equal("q", mediaType.Parameters.First().Name);

            mediaType.Parameters.Remove(quality);
            Assert.Null(mediaType.Quality);
        }
Beispiel #27
0
        private async Task<ActionResult> GetRedirectForRelease(string version)
        {
            var org = Configuration.Settings["GitHub:OrgName"];
            var repo = Configuration.Settings["GitHub:RepoName"];

            var releases = await _gitHubClient.Release.GetAll(org, repo);
            var release = string.IsNullOrEmpty(version)
                ? releases.OrderByDescending(r => r.PublishedAt).FirstOrDefault()
                : releases.FirstOrDefault(r => r.TagName == "v" + version);

            if (release == null) return HttpNotFound("No releases found.");

            var assets = await _gitHubClient.Release.GetAssets(org, repo, release.Id);
            var installer = assets.FirstOrDefault(a => a.Name.EndsWith(".msi"));

            if (installer == null) return HttpNotFound("Latest release has no MSI asset.");

            var handler = new HttpClientHandler {AllowAutoRedirect = false};
            using (var httpClient = new HttpClient(handler))
            {
                var acceptHeader = new MediaTypeWithQualityHeaderValue("application/octet-stream");
                httpClient.DefaultRequestHeaders.Accept.Add(acceptHeader);
                httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Hadouken", "1.0"));

                var response = await httpClient.GetAsync(installer.Url);

                // Redirect to where the file is
                if (response.StatusCode == HttpStatusCode.Found)
                {
                    return Redirect(response.Headers.Location.AbsoluteUri);
                }
                
                // Return the content
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return File(await response.Content.ReadAsStreamAsync(), installer.ContentType, installer.Name);
                }
            }

            return HttpNotFound();
        }
		static bool TryParseElement (Lexer lexer, out MediaTypeWithQualityHeaderValue parsedValue, out Token t)
		{
			parsedValue = null;

			string media;
			List<NameValueHeaderValue> parameters = null;
			var token = TryParseMediaType (lexer, out media);
			if (token == null) {
				t = Token.Empty;
				return false;
			}

			t = token.Value;
			if (t == Token.Type.SeparatorSemicolon && (!NameValueHeaderValue.TryParseParameters (lexer, out parameters, out t) || t != Token.Type.End))
				return false;

			parsedValue = new MediaTypeWithQualityHeaderValue ();
			parsedValue.media_type = media;
			parsedValue.parameters = parameters;
			return true;
		}
		protected async Task<Boolean> CreateList(string token)
		{
			var client = new HttpClient();
			client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
			var mediaType = new MediaTypeWithQualityHeaderValue ("application/A");
			mediaType.Parameters.Add (new NameValueHeaderValue ("odata", "verbose"));
			client.DefaultRequestHeaders.Accept.Add (mediaType);
			var body = "{\"__metadata\":{\"type\":\"SP.List\"},\"AllowContentTypes\":true,\"BaseTemplate\":107,\"ContentTypesEnabled\":true,\"Description\":\"Tasks by Xamarin.Android\",\"Title\":\"TasksByAndroid\"}";
			var contents = new StringContent (body);
			contents.Headers.ContentType = MediaTypeHeaderValue.Parse( "application/json;odata=verbose");
			try {
				var postResult = await client.PostAsync ("https://mayurtendulkar.sharepoint.com/_api/web/lists/", contents);
				var result = postResult.EnsureSuccessStatusCode();
				Toast.MakeText (this, "List created successfully! Seeding tasks.", ToastLength.Long).Show();
				return true;
			} catch (Exception ex) {
				Toast.MakeText (this, "List already exists! Fetching tasks.", ToastLength.Long).Show();
				return false;

			}
		}
        protected override int? GetVersion(MediaTypeWithQualityHeaderValue mimeType) {
            if (!String.Equals(mimeType.MediaType, AcceptMediaType, StringComparison.InvariantCultureIgnoreCase)) {
                return null;
            }

            // get version
            NameValueHeaderValue versionParameter =
                mimeType.Parameters.FirstOrDefault(parameter => parameter.Name == "version");

            if (versionParameter == null) {
                return null;
            }

            // parse version
            int version;
            if (!Int32.TryParse(versionParameter.Value, NumberStyles.None, CultureInfo.InvariantCulture, out version)) {
                return null;
            }

            return version;
        }
Beispiel #31
0
 public static bool TryParse(string input, out MediaTypeWithQualityHeaderValue parsedValue)
 {
 }
 private MediaTypeWithQualityHeaderValue(MediaTypeWithQualityHeaderValue source)
     : base(source)
 {
     // No additional members to initialize here. This constructor is used by Clone().
 }