示例#1
0
        private static async void Foo()
        {
            Uri uri = new Uri("http://localhost/?cache=1");

            System.Net.Http.WebRequestHandler handler =
                new System.Net.Http.WebRequestHandler();

            // Cache options:
            //     System.Net.Cache.RequestCacheLevel.BypassCache
            //     System.Net.Cache.RequestCacheLevel.CacheIfAvailable
            handler.CachePolicy = new System.Net.Cache.RequestCachePolicy(
                System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

            System.Net.Http.HttpClient client2 =
                new System.Net.Http.HttpClient(handler);

            System.Net.Http.HttpResponseMessage response2 = await client2.GetAsync(uri);
            response2.EnsureSuccessStatusCode();
            string str = await response2.Content.ReadAsStringAsync();
            Console.WriteLine(str);

            System.Threading.Thread.Sleep(1111);

            response2 = await client2.GetAsync(uri);
            response2.EnsureSuccessStatusCode();
            str = await response2.Content.ReadAsStringAsync();
            Console.WriteLine(str);

            autoResetEvent.Set();
        }
        protected async Task<System.Net.Http.HttpResponseMessage> GetAsync(string url)
#endif
        {
            if (url == null) throw new ArgumentNullException(nameof(url));

            try
            {
                var uri = new Uri(url);

#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
                using (var client = new System.Net.Http.HttpClient())
#elif WINDOWS_UAP
                using (var client = new System.Net.Http.HttpClient())
#endif
                {
#if WINDOWS_PORTABLE || WINDOWS_DESKTOP
                    // Setting timeout for httpclient on portable architecture. 
                    // UAP supports timeout configuration via System.Threading.Task
                    if (ProxyConfiguration.Timeout.HasValue)
                    {
                        client.Timeout = ProxyConfiguration.Timeout.Value;
                    }
#endif

                    var response = await client.GetAsync(uri, System.Net.Http.HttpCompletionOption.ResponseContentRead);
                    if (!response.IsSuccessStatusCode) throw new TheTvDbBadResponseException(response.StatusCode);

                    return response;
                }
            }
            catch (Exception e)
            {
                throw new TheTvDbServerNotAvailableException(inner: e);
            }
        }
示例#3
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            date.Text = DateTime.Today.ToString("d.M.yyyy");
            System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage response = await hc.GetAsync("http://api.teknolog.fi/taffa/sv/today/");
            response.EnsureSuccessStatusCode();
            menu.Text = await response.Content.ReadAsStringAsync();


            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text05);

            XmlNodeList tileTextAttributes = tileXml.GetElementsByTagName("text");
            tileTextAttributes[0].InnerText = menu.Text;


            XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text03);
            XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
            squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(menu.Text));
            IXmlNode node = tileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            TileNotification tileNotification = new TileNotification(tileXml);

            tileNotification.ExpirationTime = DateTime.Now.Date.AddDays(1);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);



        }
示例#4
0
 // function for map sdk
 private async Task<BingMapHelper.Response> GetResponse(Uri uri)
 {
     System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
     var response = await client.GetAsync(uri);
     using (var stream = await response.Content.ReadAsStreamAsync())
     {
         DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BingMapHelper.Response));
         return ser.ReadObject(stream) as BingMapHelper.Response;
     }
 }
		public async Task<RelatedTopic[]> GetQueriesAsync () {
			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://api.duckduckgo.com/");

			var response = await client.GetAsync("?q=tijuana&format=json&pretty=1");
			var queriesJson = response.Content.ReadAsStringAsync().Result;
			var rootObject = JsonConvert.DeserializeObject<RootObject>(queriesJson);

			return rootObject.RelatedTopics;
		}
 private async Task<RootObject> CallService(Uri uri)
 {
     string _JsonString = string.Empty;
     // fetch from rest service             
     var _HttpClient = new System.Net.Http.HttpClient();
     var _HttpResponse = await _HttpClient.GetAsync(uri.ToString());
     _JsonString = await _HttpResponse.Content.ReadAsStringAsync();
     // deserialize json to objects        
     var _JsonBytes = Encoding.Unicode.GetBytes(_JsonString);
     using (MemoryStream _MemoryStream = new MemoryStream(_JsonBytes))
     { var _JsonSerializer = new DataContractJsonSerializer(typeof(RootObject)); var _Result = (RootObject)_JsonSerializer.ReadObject(_MemoryStream); return _Result; }
 }
示例#7
0
        public static object Request(object request, Type responseType=null, bool post=false)
        {
            /** determine the api method to call */
            string method = Mozu.getMethod(request);
            if (responseType == null) responseType = request.GetType();

            /** make sure we have a valid authentication ticket */
            if (_auth == null && request.GetType() != typeof(AuthenticationContract)) Mozu.authenticate();

            string url = string.Format("{0}{1}", _apiUrl, method);
            Type t = request.GetType();
            bool get = false;
            if (! post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com";
                get = true;
            }
            else if (post && (t == typeof(CustomerAccount) || t == typeof(Product) || t == typeof(Order))) {
                url = "https://t7949.sandbox.mozu.com/api/platform";
            }
            //HTTP http = new HTTP();
            Console.WriteLine("Calling Mozu API: " + url);
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient { BaseAddress = new Uri(url) };
            //if (request.GetType() != typeof(AuthenticationContract)) http.AddHeader("x-vol-app-claims", _auth.Ticket.AccessToken);
            if (t != typeof(AuthenticationContract)) {
                client.DefaultRequestHeaders.Add("x-vol-app-claims", _auth.Ticket.AccessToken);
                client.DefaultRequestHeaders.Add("x-vol-tenant", "7949");//the sandbox number
                if (t == typeof(Product)) {
                    client.DefaultRequestHeaders.Add("x-vol-master-catalog", "2");
                }
                //client.DefaultRequestHeaders.Add("x-vol-catalog", "1");
                //client.DefaultRequestHeaders.Add("x-vol-version", "1.9.14232.3");
            }

            string json = JSON.Serialize(request);

            //string response = http.POSTRaw(url, json, "application/json");

            string response = null;
            if (get) {
                method = "/api" + method;
                if (t == typeof(Product)) method += "?startindex=0&pagesize=200";
                var r = client.GetAsync(method).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }
            else {
                var r = client.PostAsync("/api" + method, new System.Net.Http.StringContent(json, System.Text.Encoding.UTF8, "application/json")).Result;
                response = r.Content.ReadAsStringAsync().Result;
            }

            object o = JSON.Deserialize(response, responseType);
            return o;
        }
示例#8
0
 public static async Task<Byte[]> GetDataFromUri(Uri uri)
 {
     using (System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient())
     {
         Client.BaseAddress = uri;
         var resultContext = await Client.GetAsync(uri);
         if (resultContext != null)
         {
             return await resultContext.Content.ReadAsByteArrayAsync();
         }
     }
     return null;
 }
示例#9
0
 private async Task<string> GetResponseContentAsync(string url)
 {
     var httpClient = new System.Net.Http.HttpClient();
     var response = await httpClient.GetAsync(url);
     if (response.StatusCode == System.Net.HttpStatusCode.OK)
     {
         return await response.Content.ReadAsStringAsync();
     }
     else
     {
         return "error";
     }
 }
示例#10
0
 public async void GetCurrentVersion(Action<int> callback)
 {
     try
     {
         var client = new System.Net.Http.HttpClient();
         var response = await client.GetAsync(new Uri(_baseUrl + "/Version"));
         callback(int.Parse(response.Content.ReadAsString()));
     }
     catch (Exception)
     {
         callback(-1);
     }
 }
        // GET api/ManageUser
        public async Task<string> Get()
        {
            Web.Models.ConfigModel config = new Web.Models.ConfigModel();
            string retVal = config.DefaultUserId;

            // Get the credentials for the logged-in user.
            var fbCredentials = await this.User.GetAppServiceIdentityAsync<FacebookCredentials>(this.Request);

            if (null != fbCredentials && fbCredentials.Claims.Count > 0)
            {
                // Create a query string with the Facebook access token.
                var fbRequestUrl = "https://graph.facebook.com/v2.5/me?fields=email%2Cfirst_name%2Clast_name&access_token="
                    + fbCredentials.AccessToken;

                // Create an HttpClient request.
                var client = new System.Net.Http.HttpClient();

                // Request the current user info from Facebook.
                var resp = await client.GetAsync(fbRequestUrl);
                resp.EnsureSuccessStatusCode();

                // Do something here with the Facebook user information.
                var fbInfo = await resp.Content.ReadAsStringAsync();

                JObject fbObject = JObject.Parse(fbInfo);
                var emailToken = fbObject.GetValue("email");

                if (null != emailToken)
                {
                    string email = emailToken.ToString();
                    retVal = CheckAddEmailToDB(email);
                }
                else
                {
                    return retVal;
                }

                return retVal;
            }

            var aadCredentials = await this.User.GetAppServiceIdentityAsync<AzureActiveDirectoryCredentials>(this.Request);
            if (null != aadCredentials && aadCredentials.Claims.Count > 0)
            {
                string email = aadCredentials.UserId;

                retVal = CheckAddEmailToDB(email);
            }

            return retVal;
        }
示例#12
0
        public static async Task<string> getHttpWebRequest(string api, List<KeyValuePair<String, String>> paramList = null, int PostORGet = 0, bool fulluri = false)
        {
            string content = "";
            return await Task.Run(() =>
            {
                if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    try
                    {
                        System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                        string uri;
                        if (!fulluri)
                            uri = "http://hongyan.cqupt.edu.cn/" + api;
                        else
                            uri = api;
                        httpClient.DefaultRequestHeaders.Add("API_APP", "winphone");
                        httpClient.DefaultRequestHeaders.Add("API_TOKEN", "0zLUZA0j+OL77OsjXC0ulOz50KaI6yANZtkOk2vQIDg=");
                        System.Net.Http.HttpRequestMessage requst;
                        System.Net.Http.HttpResponseMessage response;
                        if (PostORGet == 0)
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, new Uri(uri));
                            response = httpClient.PostAsync(new Uri(uri), new System.Net.Http.FormUrlEncodedContent(paramList)).Result;
                        }
                        else
                        {
                            requst = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, new Uri(uri));
                            response = httpClient.GetAsync(new Uri(uri)).Result;
                        }
                        if (response.StatusCode == HttpStatusCode.OK)
                            content = response.Content.ReadAsStringAsync().Result;
                        //else if (response.StatusCode == HttpStatusCode.NotFound)
                        //    Utils.Message("Oh...服务器又跪了,给我们点时间修好它");

                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "网络请求异常");
                    }
                }
                else
                {
                }
                //if (content.IndexOf("{") != 0)
                //    return "";
                //else
                return content;

            });
        }
        public async Task<string> GetDocument(string key, int imageId)
        {
            var client = new System.Net.Http.HttpClient
            {
                BaseAddress = new Uri(Constants.SERVICE_URL)
            };
            client.DefaultRequestHeaders.Add("X-Client-Identifier", DeviceDetail.DeviceIdentifierInfo);
            client.DefaultRequestHeaders.Add("application_key", DeviceDetail.UserKey);
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + CommonHelper.GetTokenInfo());
            Debug.WriteLine(Constants.FIRST_DOCUMENT_URL + "Get?folder=" + key + "&page=" + imageId);
			var response = client.GetAsync(Constants.FIRST_DOCUMENT_URL + "/Get?folder=" + key + "&page=" + imageId).Result;
            string content = await response.Content.ReadAsStringAsync();
			
            return content;
        }
		public async Task<Earthquake[]> GetEarthquakesAsync () {

			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://api.geonames.org/");

			var response = await client.GetAsync("earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt&maxRows=20");

			var earthquakesJson = response.Content.ReadAsStringAsync().Result;

			var rootobject = JsonConvert.DeserializeObject<RootobjectE>(earthquakesJson);

			return rootobject.earthquakes;

		}
        public async Task<string> GetFirstDocument(string docName, string path)
        {
            var client = new System.Net.Http.HttpClient
            {
                BaseAddress = new Uri(Constants.SERVICE_URL)
            };
            string val = path == "" ? "" : CommonHelper.Base64Encode(path);
            client.DefaultRequestHeaders.Add("X-Client-Identifier", DeviceDetail.DeviceIdentifierInfo);
            client.DefaultRequestHeaders.Add("application_key", DeviceDetail.UserKey);
			client.DefaultRequestHeaders.Add("Authorization", "Bearer " + CommonHelper.GetTokenInfo());
            Debug.WriteLine(Constants.FIRST_DOCUMENT_URL + "GetDocument?documentName=" + docName + "&folderPath=" + val);
            var response = client.GetAsync(Constants.FIRST_DOCUMENT_URL + "GetDocument?documentName=" + docName + "&folderPath=" + val).Result;
            string content = await response.Content.ReadAsStringAsync();
            return content;
        }
		// http://services.faa.gov/docs/faq/

		public async Task<string> GetEarthquakesAsync (string code) {

			var client = new System.Net.Http.HttpClient ();
			client.DefaultRequestHeaders.Add("Accept", "application/json");
			var address = $"http://services.faa.gov/airport/status/{code}"; //?format=application/json";

			var response = await client.GetAsync(address);

			var airportJson = response.Content.ReadAsStringAsync().Result;

			//var rootobject = JsonConvert.DeserializeObject<Rootobject>(airportJson);

			return airportJson;

		}
示例#17
0
 public async void GetXml(Action<string> callback)
 {
     string xml = null;
     try
     {
         var client = new System.Net.Http.HttpClient() { MaxResponseContentBufferSize = Int32.MaxValue };
         var response = await client.GetAsync(new Uri(_baseUrl + "/Xml"));
         xml = response.Content.ReadAsString();
     }
     catch (Exception ex) 
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     callback(xml);
 }
示例#18
0
		public async Task<Taco[]> GetTacosAsync () {

			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://tacodemo.herokuapp.com/");

			var response = await client.GetAsync("tacos.json");

			var tacosJson = response.Content.ReadAsStringAsync().Result;

			var rootobject = JsonConvert.DeserializeObject<Taco[]>(tacosJson);

			return rootobject;

		}
		public async Task<WeatherObservation[]> GetWeatherObservationsAsync () {

			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri("http://api.geonames.org/");

			//findNearByWeatherJSON?lat=43&lng=-2&username=demo
			var response = await client.GetAsync("weatherJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=bertt&maxRows=20");

			var earthquakesJson = response.Content.ReadAsStringAsync().Result;

			var rootobject = JsonConvert.DeserializeObject<RootObjectWO>(earthquakesJson);

			return rootobject.weatherObservations;

		}
示例#20
0
        public static async void GetImages(string query)
#endif
        {
            // Default query

#if WINRT
            var wc = new System.Net.Http.HttpClient();

            var response = await wc.GetAsync(new Uri(searchUrl + query));
            ParseImages(query, XDocument.Parse(response.Content.ReadAsString()));
            
#elif SILVERLIGHT

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WebClient_DownloadStringCompleted);
            wc.DownloadStringAsync(new Uri(searchUrl + query), query);

#endif
        }
示例#21
0
        public async Task <string> getAPI2()
        {
            App.Database.reset();
            var client = new System.Net.Http.HttpClient();

            client.BaseAddress = new Uri("https://thursdayhomework.azurewebsites.net/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            var response = await client.GetAsync("API/GetItemList/2");

            var listJson = response.Content.ReadAsStringAsync().Result;


            dynamic results = JsonConvert.DeserializeObject(listJson);

            var data = string.Empty;


            for (var i = 0; i < results.data.Count; i++)
            {
                data = results.data[i].Name;
                Items api = new Items();
                if (results.msg != "OK" && results.error_code != 0)
                {
                    break;
                }
                api.Error_Code = results.error_code;
                api.Msg        = results.msg;
                api.Name       = results.data[i].Name;
                api.Attribute  = results.data[i].Attribute;
                api.Value      = results.data[i].Value;

                await App.Database.InsertItem(api);
            }

            return(data);
        }
        public async void GetItems()
        {
            var serviceURI = "[YOUR-WINDOWS-AZURE-SERVICE-URI]/api/values";

            using (var client = new System.Net.Http.HttpClient())
            using (var response = await client.GetAsync(serviceURI))
            {
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();
                    var values = JsonArray.Parse(data);

                    var valueList = from v in values
                                    select new
                                    {
                                        Name = v.GetString()
                                    };

                    this.listValues.ItemsSource = valueList;
                }
            }
        }
示例#23
0
        /// <summary>
        /// Fetches a single tile and adds it to the ConcurrentBag.
        /// </summary>
        /// <param name="ti"></param>
        /// <param name="client"></param>
        /// <param name="bag"></param>
        /// <param name="uriFormat"></param>
        /// <returns></returns>
        static async Task FetchTile(TileInfo ti, System.Net.Http.HttpClient client, ConcurrentBag <LoadedTile> bag, string uriFormat)
        {
            uriFormat = uriFormat.Replace("{z}", ti.Index.Level);
            uriFormat = uriFormat.Replace("{y}", ti.Index.Row.ToString(CultureInfo.InvariantCulture));
            uriFormat = uriFormat.Replace("{x}", ti.Index.Col.ToString(CultureInfo.InvariantCulture));

            System.Net.Http.HttpResponseMessage response = await client.GetAsync(uriFormat);

            byte[] data = await response.Content.ReadAsByteArrayAsync();

            if (data == null)
            {
                return;
            }

            LoadedTile lt = new LoadedTile();

            lt.ti       = ti;
            lt.data     = data;
            lt.mimeType = response.Content.Headers.ContentType.MediaType;
            bag.Add(lt);
        }
        public async System.Threading.Tasks.Task <ObservableCollection <Order> > RefreshDataAsync()
        {
            WebAPIUrl = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; // Set your REST API url here
            var uri = new Uri(WebAPIUrl);

            try
            {
                var response = await client.GetAsync(uri);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    Items = JsonConvert.DeserializeObject <ObservableCollection <Order> >(content);
                    return(Items);
                }
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
示例#25
0
        private async Task <JsonItemNote> GetData()
        {
            var itemsr = string.Empty;
            ///  var client = RestService.HttpClient;
            var client   = new System.Net.Http.HttpClient();
            var response = await client.GetAsync("http://172.16.101.236/GetItemNote.php");

            JsonItemNote ObjItemList = new JsonItemNote();

            if (response.IsSuccessStatusCode)
            {
                string NoteInfoList = response.Content.ReadAsStringAsync().Result;
                ObjItemList = JsonConvert.DeserializeObject <JsonItemNote>(NoteInfoList);
                foreach (JsonItemnoteClass t in ObjItemList.NoteInfo)
                {
                    // FlagNu = t.Name;
                    itemsr = t.Name;
                    // itemname = t.Name;
                }
            }
            return(ObjItemList);
        }
示例#26
0
        static NewsRepository()
        {
            const string url = "https://hacker-news.firebaseio.com/v0/item/121003.json?print=pretty";

            using (var client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add
                    (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.GetAsync(url).Result;
                var data     = response.Content.ReadAsStringAsync().Result;
                //result = JsonConvert.DeserializeObject<List<Rideplicity_reference>>(data);
            }
            //return result;
            //}
            //lock()
            //{
            _alreadyLoaded = true;

            //}
        }
        public async System.Threading.Tasks.Task <IActionResult> TrialBalance()
        {
            ViewBag.PageContentHeader = "Trial Balance";

            using (var client = new System.Net.Http.HttpClient())
            {
                var baseUri = _baseConfig["ApiUrl"];
                client.BaseAddress = new System.Uri(baseUri);
                client.DefaultRequestHeaders.Accept.Clear();
                var response = await client.GetAsync(baseUri + "financials/trialbalance");

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();

                    var trialBalanceModel = Newtonsoft.Json.JsonConvert.DeserializeObject <System.Collections.Generic.List <Models.TrialBalance> >(responseJson);
                    return(View(trialBalanceModel));
                }
            }

            return(View());
        }
示例#28
0
        public async Task <string> GetTFSDetails(string url)
        {
            System.Net.Http.HttpClientHandler handler = new System.Net.Http.HttpClientHandler()
            {
                UseDefaultCredentials = true
            };
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                System.Net.Http.HttpResponseMessage response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string data = await response.Content.ReadAsStringAsync();

                    return(data);
                }
            }
            return(null);
        }
示例#29
0
        public async Task <List <Gateway> > GetGateways()
        {
            m_Gateways = new List <Gateway>();

            System.Net.Http.HttpClient m_HttpClient = new System.Net.Http.HttpClient();
            m_HttpClient.DefaultRequestHeaders.Add("X-HeaderKey", "HeaderValue");
            m_HttpClient.DefaultRequestHeaders.Referrer = new Uri(m_Settings.ServiceURL);

            var m_URL = String.Format(m_Settings.ServiceURL);

            System.Net.Http.HttpResponseMessage m_HttpResponseMessage = await m_HttpClient.GetAsync(m_URL);

            if (m_HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string m_Response = await m_HttpResponseMessage.Content.ReadAsStringAsync();

                System.Web.Script.Serialization.JavaScriptSerializer m_JsSerializer =
                    new System.Web.Script.Serialization.JavaScriptSerializer();
                var             m_Result      = m_JsSerializer.DeserializeObject(m_Response);
                System.Object[] m_ObjectArray = (System.Object[])m_Result;

                foreach (System.Object m_GWObject in m_ObjectArray)
                {
                    System.Collections.Generic.Dictionary <string, object> m_GWDictionary =
                        (System.Collections.Generic.Dictionary <string, object>)m_GWObject;

                    ZigBee.ConBee.Gateway m_Gateway = new ConBee.Gateway(m_Settings)
                    {
                        ID                = m_GWDictionary["id"].ToString(),
                        MacAddress        = m_GWDictionary["macaddress"].ToString(),
                        InternalIPAddress = m_GWDictionary["internalipaddress"].ToString(),
                        InternalPort      = m_GWDictionary["internalport"].ToString(),
                        Name              = m_GWDictionary["name"].ToString()
                    };
                    m_Gateways.Add(m_Gateway);
                }
            }
            return(m_Gateways);
        }
        public async Task <RootObject> GetJSON()
        {
            try
            {
                var client   = new System.Net.Http.HttpClient();
                var response = await client.GetAsync("https://api.themoviedb.org/3/discover/movie?primary_release_date.gte=2014-09-15&primary_release_date.lte=2014-10-22&api_key=195f09ffbfbedc80a969bd3eeda78b38");

                string json = await response.Content.ReadAsStringAsync();

                RootObject rootObject = new RootObject();
                if (json != "")
                {
                    rootObject = JsonConvert.DeserializeObject <RootObject>(json);
                }

                return(rootObject);
            }
            catch (InvalidCastException e)
            {
                throw e;
            }
        }
示例#31
0
        private async void BtnRequest_Clicked(object sender, EventArgs e)
        {
            string target_url = "http://saeyan2019.cafe24.com/rw.php";

            //CrossConnectivity 네트워크 연결상태 여부 체크 nuget 패키지
            if (CrossConnectivity.Current.IsConnected)
            {
                var client = new System.Net.Http.HttpClient();

                if (!string.IsNullOrEmpty(entryRequestString.Text))
                {
                    target_url += "?word=" + entryRequestString.Text;
                    //서버에 접속 및 데이터 요청
                    var response = await client.GetAsync(target_url);

                    //Response 데이터 가져오기
                    string response_word = await response.Content.ReadAsStringAsync();

                    if (response_word != "")
                    {
                        labelResponse.Text = response_word;
                    }
                    else
                    {
                        //xamarin에서 사용하는 alert 창
                        await DisplayAlert("Warning", "빈 데이터입니다.", "예");
                    }
                }
                else
                {
                    await DisplayAlert("Warning", "보낼 메시지 입력바람.", "예");
                }
            }
            else
            {
                await DisplayAlert("Warning", "서버에 연결할 수 없음.", "예");
            }
        }
示例#32
0
        /// <summary>
        /// Primary method for performing typed data retrieval from Cloverleaf in pages.
        /// </summary>
        /// <remarks>
        /// This uses the BSON flag by default, which instructs the Cloverleaf API to use BSON to transfer the data as opposed to JSON, as BSON
        /// typically results in a smaller payload.  Each invocation of this method returns a single page, usually a typed FeedResponse wrapper,
        /// although it can also be used for the FeedMeta and FeedEvent endpoints as desired.
        ///
        /// We illustrate this method here to demonstrate how one may use the automatically-generated class definitions available at
        /// https://api.cloverleaf.mge360.com/entityschema?fmt=cs, but it is not explicitly required that you use these wrappers if they do not fit your use
        /// cases; the FeedResponse could also be retooled to use a BsonArray in place of the typed "Entities" property, or one could omit the "bson" flag
        /// entirely and process the entire resultset as json objects (see some of the other samples in this repository for examples of straight-json
        /// implementations).
        /// </remarks>
        /// <typeparam name="T">Type of feedresponse to retrieve</typeparam>
        /// <param name="relURI">Relative feed uri</param>
        /// <param name="queryParams">Additional parameters, such as EventCode and Since values</param>
        /// <returns></returns>
        public static T BSONFetch <T>(string relURI, params string[] queryParams)
        {
            Uri myUrl = GetFetchURI(relURI, queryParams);

            // we retry on timeouts and certain I/O exceptions, because they typically indicate transient states of either our local system or the upstream service.
            const int MAX = 10;

            for (var Attempt = 1; Attempt <= MAX; Attempt++)
            {
                try
                {
                    var resp = CLClient.GetAsync(myUrl).Result;
                    if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        throw new Exception($"{resp.StatusCode} '{resp.ReasonPhrase}': {resp.Content.ReadAsStringAsync().Result}.  Please verify that the Cloverleaf credentials you provided are correct.");
                    }
                    if (resp.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        throw new Exception($"{resp.StatusCode} '{resp.ReasonPhrase}': {resp.Content.ReadAsStringAsync().Result}");
                    }
                    using (var MS = new MemoryStream())
                    {
                        resp.Content.ReadAsStreamAsync().Result.CopyTo(MS);
                        MS.Position = 0;
                        return(BsonSerializer.Deserialize <T>(MS));
                    }
                }
                catch (Exception ex)
                {
                    if (!ex.IsTimeoutOrIO() || (Attempt == MAX))
                    {
                        throw;
                    }
                }
            }

            throw new Exception("BSONFetch: retry timeouts loop exited.");
        }
        public async Task <string> GetToken(string identity)
        {
            this.lastIdentityUsed = identity;
            var    client = new System.Net.Http.HttpClient();
            string url    = $"{tokenProviderUrl}?identity={identity}";

            if (Device.RuntimePlatform.Equals(Device.Android))
            {
                url += $"&pushChannel=fcm";
            }
            else if (Device.RuntimePlatform.Equals(Device.iOS))
            {
                url += $"&pushChannel=apn";
            }
            ;

            try
            {
                var response = await client.GetAsync(url);

                if (response.StatusCode.Equals(System.Net.HttpStatusCode.OK))
                {
                    var token = System.Text.Encoding.UTF8.GetString(await response.Content.ReadAsByteArrayAsync());
                    Logger.Info("TokenProvider", $"Got chat token: {token}");
                    return(token);
                }
                else
                {
                    Logger.Error("TokenProvider", $"Can't get token, token generator responded with {response}");
                    throw new TokenProviderException(response.ToString());
                }
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                Logger.Error("TokenProvider", $"Can't get token, token generator encountered exception {ex.Message}");
                throw new TokenProviderException(ex.Message, ex);
            }
        }
		public async Task<List<PredicPlaces>> GetLocationAsync (string search) {

			var client = new System.Net.Http.HttpClient ();

			client.BaseAddress = new Uri ("https://maps.googleapis.com/maps/api/place/autocomplete/");
			string afterBaseUrl = "json?input=" + search + "&" + "types=establishment" + "&" + "location=" + "37.76999,-122.44696" + "&" + "radius=500" +
			                      "&" + "key=" + MapsApiKey;

			var response = await client.GetAsync (afterBaseUrl);
			//var response = await client.GetAsync("json?input=Amoeba&types=establishment&location=37.76999,-122.44696&radius=500&key="+MapsApiKey);

			var placesJson = response.Content.ReadAsStringAsync().Result;

			/*
			dynamic rootObject = JsonConvert.DeserializeObject(placesJson);
			var predictions = rootObject.predictions;
			foreach (var place in predictions) {
				string des = place.description;
			} */

			JToken token = JObject.Parse(placesJson);

			string status = (string)token.SelectToken("status");
			var predictions = token.SelectToken("predictions");
			List<PredicPlaces> ppList = new List<PredicPlaces> ();
			ppList.Clear ();
			if (status == "OK") {

				foreach (var place in predictions) {
					PredicPlaces pp = new PredicPlaces ();
					pp.description = (string)place ["description"];
					pp.id = (string)place ["id"];
					ppList.Add (pp);
				}
			} 

			return ppList;
		}
示例#35
0
        /// <summary>
        ///   Получаем коеф для заданых валют
        /// </summary>
        /// <param name="base">Валюта из которой конвертируем</param>
        /// <param name="symbols">Валюта в которую конвертируем</param>
        /// <returns></returns>
        public async Task <decimal> FetchRate(string @base, string symbols)
        {
            if (symbols == "RUR")
            {
                symbols = "RUB";
            }

            if (@base == "RUR")
            {
                @base = "RUB";
            }

            var uri      = $@"/latest?base={@base}&symbols={symbols}";
            var response = await _httpClient.GetAsync(uri);

            var responseString = await response.Content.ReadAsStringAsync();

            var root = JObject.Parse(responseString);

            var rate = (decimal)root["rates"][$"{symbols}"];

            return(rate);
        }
示例#36
0
 private void buttonSearch_Click(object sender, EventArgs e)
 {
     //http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=iphone+6s
     try
     {
         textBoxOutput.Text = "";
         var url = "http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=" + System.Web.HttpUtility.UrlEncode(textBoxInput.Text);
         using (var client = new System.Net.Http.HttpClient())
         {
             var res = client.GetAsync(url).Result.Content.ReadAsStreamAsync().Result;
             var doc = AngleSharp.DocumentBuilder.Html(res); //AngleSharp.DOM.Html.HTMLDocument.LoadFromSource(html);
             var a = doc.QuerySelectorAll("//div[@class=\"s-item-container\"]//a");
             if (a != null)
             {
                 textBoxOutput.Text = a[0].Attributes["href"].Value.ToString();
             }
         }
     }
     catch (Exception ex)
     {
         textBoxOutput.Text = ex.Message;
     }
 }
示例#37
0
        public async static Task <RecData> GetData()
        {
            string httpResponseBody = "";

            try
            {
                string uri = String.Format(api);
                httpResponse = await httpClient.GetAsync(new Uri(uri));

                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                RecData data = JsonConvert.DeserializeObject <RecData>(httpResponseBody);
                return(data);
            }
            catch (Exception e)
            {
                RecData ErrorData = new RecData
                {
                    data = null
                };
                return(ErrorData);
            }
        }
示例#38
0
        protected async void OnGetList(string filme_id)
        {
            try
            {
                var client   = new System.Net.Http.HttpClient();
                var response = await client.GetAsync("https://api.themoviedb.org/3/movie/" + filme_id + "?api_key=195f09ffbfbedc80a969bd3eeda78b38");

                string json = await response.Content.ReadAsStringAsync();

                if (json != "")
                {
                    var tr = JsonConvert.DeserializeObject <Filme>(json);
                    Original_title.BindingContext = tr.Original_title;
                    Poster_path.BindingContext    = "https://image.tmdb.org/t/p/w300_and_h450_bestv2/" + tr.Poster_path;
                    Backdrop_path.BindingContext  = "https://image.tmdb.org/t/p/w533_and_h300_bestv2/" + tr.Backdrop_path;
                    Overview.BindingContext       = tr.Overview;
                }
            }
            catch (InvalidCastException e)
            {
                throw e;
            }
        }
示例#39
0
 private void buttonSearch_Click(object sender, EventArgs e)
 {
     //http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=iphone+6s
     try
     {
         textBoxOutput.Text = "";
         var url = "http://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=" + System.Web.HttpUtility.UrlEncode(textBoxInput.Text);
         using (var client = new System.Net.Http.HttpClient())
         {
             var res = client.GetAsync(url).Result.Content.ReadAsStreamAsync().Result;
             var doc = AngleSharp.DocumentBuilder.Html(res); //AngleSharp.DOM.Html.HTMLDocument.LoadFromSource(html);
             var a   = doc.QuerySelectorAll("//div[@class=\"s-item-container\"]//a");
             if (a != null)
             {
                 textBoxOutput.Text = a[0].Attributes["href"].Value.ToString();
             }
         }
     }
     catch (Exception ex)
     {
         textBoxOutput.Text = ex.Message;
     }
 }
        public static async Task <LUIS> QueryLUIS(string Query)
        {
            LUIS LUISResult = new LUIS();
            var  LUISQuery  = Uri.EscapeDataString(Query);

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                // Get key values from the web.config
                string LUIS_Url = WebConfigurationManager.AppSettings["LUISUrl"];
                string LUIS_Subscription_Key = WebConfigurationManager.AppSettings["LUISSubscriptionKey"];
                string RequestURI            = String.Format("{0}?subscription-key={1}&q={2}",
                                                             LUIS_Url, LUIS_Subscription_Key, LUISQuery);
                System.Net.Http.HttpResponseMessage msg = await client.GetAsync(RequestURI);

                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse = await msg.Content.ReadAsStringAsync();

                    LUISResult = JsonConvert.DeserializeObject <LUIS>(JsonDataResponse);
                }
            }
            return(LUISResult);
        }
示例#41
0
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            var client = new System.Net.Http.HttpClient();
            var result = await client.GetAsync("https://www.pja.edu.pl");

            if (result.IsSuccessStatusCode)
            {
                string html = await result.Content.ReadAsStringAsync();

                var regex = new Regex("[a-z]+[a-z0-9]*@[a-z0-9]+\\.[a-z]", RegexOptions.IgnoreCase);

                var matches = regex.Matches(html);

                foreach (var m in matches)
                {
                    Console.WriteLine(m.ToString());
                }
            }



            Console.WriteLine("...");
        }
        public async void GetItems()
        {
            var serviceURI = "[YOUR-WINDOWS-AZURE-SERVICE-URI]/api/values";

            using (var client = new System.Net.Http.HttpClient())
                using (var response = await client.GetAsync(serviceURI))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var data = await response.Content.ReadAsStringAsync();

                        var values = JsonArray.Parse(data);

                        var valueList = from v in values
                                        select new
                        {
                            Name = v.GetString()
                        };

                        this.listValues.ItemsSource = valueList;
                    }
                }
        }
        public async void GetJSON()
        {
            //Check network status
            if (NetworkCheck.IsInternet())
            {
                var httpClient = new System.Net.Http.HttpClient();

                var response = await httpClient.GetAsync(Config.MESSAGE_THREAD_API + threadId);

                string assignJson = await response.Content.ReadAsStringAsync();

                if (assignJson != "")
                {
                    messageView = JsonConvert.DeserializeObject <DealMessageThreadList>(assignJson);
                }
                //Binding listview with server response
                listOfThreadUsers.ItemsSource = messageView.threadUsers;
            }
            else
            {
                await DisplayAlert("JSONParsing", "No network is available.", "Ok");
            }
        }
示例#44
0
        public async Task WhenConfigurePerTenantServicesHasNonValidArguments_ThrowException()
        {
            // Arrange
            WebHostBuilder builder = CreateWebHostBuilder <TestStartup2, TestTenant, TestTenantMemoryCacheResolver>();

            // Act
            using (TestServer server = new TestServer(builder))
                using (System.Net.Http.HttpClient client = server.CreateClient())
                {
                    Task res() => Task.Run(async() =>
                    {
                        System.Net.Http.HttpResponseMessage response = await client.GetAsync("/tenant-1-1").ConfigureAwait(false);
                        response.EnsureSuccessStatusCode();
                        string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    });

                    Exception ex = await Assert.ThrowsAsync <InvalidOperationException>(res).ConfigureAwait(false);

                    Assert.Equal(
                        "The ConfigurePerTenantServices method must take only two parameter one of type IServiceCollection and one of type TTenant.",
                        ex.Message);
                }
        }
示例#45
0
        /// <summary>
        /// Used to get people data from API with provided ID
        /// </summary>
        /// <param name="IDNumber"></param>
        /// <returns>People object</returns>
        public async System.Threading.Tasks.Task <People> GetPeopleDataWithID(string IDNumber)
        {
            WebAPIUrl = "https://swapi.dev/api/people/" + IDNumber + "/"; // Set your REST API url here

            var uri = new Uri(WebAPIUrl);

            try
            {
                var response = await client.GetAsync(uri);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    People people = JsonConvert.DeserializeObject <People>(content);
                    return(people);
                }
            }
            catch (Exception)
            {
            }
            return(null);
        }
        private async void RegisterUser(object sender, RoutedEventArgs e)
        {
            string param = "vname=" + this.vname.Text + "&nname=" + this.nname.Text + "&email=" + this.email.Text + "&pw=" + this.param.App.HashPW(this.pw.Password) + "&pwagain=" + this.param.App.HashPW(this.pwagain.Password);

            Uri    geturi   = new Uri("http://37.252.185.24:8080/ertl/register?" + param);
            string response = "";

            try
            {
                System.Net.Http.HttpClient          client      = new System.Net.Http.HttpClient();
                System.Net.Http.HttpResponseMessage responseGet = await client.GetAsync(geturi);

                response = await responseGet.Content.ReadAsStringAsync();
            }
            catch (System.Net.Http.HttpRequestException)
            {
                this.errormessages.NavigateToString("Fehler beim Verbinden mit den Server.");
                return;
            }

            Newtonsoft.Json.Linq.JArray result = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(response);
            if (((string)result[0]).Equals("error"))
            {
                this.errormessages.NavigateToString((string)result[1]);
                return;
            }
            else if (((string)result[0]).Equals("success"))
            {
                this.errormessages.NavigateToString(response);

                this.param.Text = (string)result[1];
                Frame.Navigate(typeof(MainPage), this.param);
                return;
            }

            this.errormessages.NavigateToString("Fehler beim Verarbeiten der Antwort vom Server.");
        }
示例#47
0
        public object Invoke(string methodName, object[] arguments)
        {
            if (methodName == "ContextClick")
            {
                // The IApp interface doesn't have a context click concept, and mapping TouchAndHold to
                // context clicking would box us in if we have the option of running these tests on touch
                // devices later. So we're going to use the back door.
                ContextClick(arguments[0].ToString());
                return(null);
            }

            if (methodName == "hasInternetAccess")
            {
                try
                {
                    using (var httpClient = new System.Net.Http.HttpClient())
                        using (var httpResponse = httpClient.GetAsync(@"https://www.github.com"))
                        {
                            httpResponse.Wait();
                            if (httpResponse.Result.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                }
                catch
                {
                    return(false);
                }
            }

            return(null);
        }
示例#48
0
        private async void Button1_Click(object sender, EventArgs e)
        {
            string url = "http://192.168.0.55:8080/hello";

            if (CrossConnectivity.Current.IsConnected)
            {
                try
                {
                    var client = new System.Net.Http.HttpClient();
                    if (!string.IsNullOrEmpty(txtName.Text))
                    {
                        url += "?name=" + txtName.Text;
                    }
                    var response = await client.GetAsync(url);

                    string helloString = await
                                         response.Content.ReadAsStringAsync();

                    if (helloString != "")
                    {
                        label1.Text = helloString;
                    }
                    else
                    {
                        await DisplayAlert("경고", "데이터가 없습니다.", "OK");
                    }
                }
                catch (Exception ex)
                {
                    await DisplayAlert("경고", ex.Message, "OK");
                }
            }
            else
            {
                await DisplayAlert("경고", "네크워크 에러! 인터넷 연결 확인 바랍니다.", "OK");
            }
        }
        public static async Task <bool> UpdateQuestions()
        {
            IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();

            DateTime LatestQuestionDate = GetLatestQuestion();

            using (var client = new System.Net.Http.HttpClient())
            {
                var data = await client.GetAsync("http://193.164.131.73//SportyQuizServices/api/game/GetUpdateSinglePlayerQuestions?QuestionDate=" + LatestQuestionDate.ToString(new CultureInfo("en-US")));

                //var data = await client.GetAsync("http://192.168.1.5//SportyQuizServices/api/game/GetUpdateSinglePlayerQuestions?QuestionDate=" + LatestQuestionDate.ToString(new CultureInfo("en-US")));

                if (data.StatusCode == HttpStatusCode.OK)
                {
                    if (data.Content != null)
                    {
                        using (StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("Questions.txt", FileMode.Create, FileAccess.Write, ISF)))
                        {
                            var writabledata = data.Content.ReadAsStringAsync().Result;
                            SW.WriteLine(writabledata);
                            SW.Close();
                        }

                        App.QuestionsList = GetQuestions();

                        return(true);
                    }

                    return(false);
                }

                else
                {
                    return(false);
                }
            }
        }
示例#50
0
        /// <summary>
        /// Checks if the given package version is present in V2. This method bypasses the hijack.
        /// </summary>
        private async Task <bool> CheckIfPackageVersionExistsInV2Async(string packageId, string version, bool?shouldBeListed)
        {
            var sourceUrl         = UrlHelper.V2FeedRootUrl;
            var normalizedVersion = NuGetVersion.Parse(version).ToNormalizedString();

            var url = UrlHelper.V2FeedRootUrl + $"/Packages(Id='{packageId}',Version='{normalizedVersion}')?hijack=false";

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                return(await VerifyWithRetryAsync(
                           $"Verifying that package {packageId} {version} exists on source {sourceUrl} (non-hijacked).",
                           async() =>
                {
                    using (var response = await httpClient.GetAsync(url))
                    {
                        if (response.StatusCode == HttpStatusCode.NotFound)
                        {
                            return false;
                        }
                        else if (response.StatusCode == HttpStatusCode.OK)
                        {
                            if (shouldBeListed.HasValue)
                            {
                                var responseString = await response.Content.ReadAsStringAsync();
                                var isActuallyListed = !responseString.Contains("<d:Published m:type=\"Edm.DateTime\">1900-01-01T00:00:00</d:Published>");
                                return shouldBeListed == isActuallyListed;
                            }

                            return true;
                        }

                        response.EnsureSuccessStatusCode();
                        return false;
                    }
                }));
            }
        }
示例#51
0
        public static PhpArray get_headers(string url, int format = 0, PhpResource context = null)
        {
            var arr = new PhpArray();

            var streamcontext = Streams.StreamContext.GetValid(context, allowNull: true);

            try
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    var response = client.GetAsync(url, System.Net.Http.HttpCompletionOption.ResponseHeadersRead).Result;

                    arr.Add($"HTTP/{response.Version} {(int)response.StatusCode} {response.ReasonPhrase}");

                    foreach (var h in response.Headers)
                    {
                        var value = string.Join(", ", h.Value);

                        if (format == 0)
                        {
                            arr.Add(h.Key + ": " + value);
                        }
                        else
                        {
                            arr[h.Key] = value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PhpException.Throw(PhpError.Warning, ex.Message);
                return(null);
            }

            return(arr);
        }
        public async Task <string> Subscribe(string email, IEnumerable <KeyValuePair <string, string> > parameters)
        {
            string returnValue = string.Empty;

            if (!string.IsNullOrWhiteSpace(email))
            {
                var encodedEmail = HttpUtility.UrlEncode(email);

                var url = GetUrl(encodedEmail);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        url = string.Format("{0}&{1}={2}", url, parameter.Key, HttpUtility.UrlEncode(parameter.Value));
                    }
                }

                using (var client = new System.Net.Http.HttpClient())
                {
                    using (var response = await client.GetAsync(new Uri(url)))
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        if (_logger.IsInformationEnabled())
                        {
                            _logger.Log(Level.Information, "Email: " + email + " Result:" + content);
                        }

                        returnValue = content;
                    }
                }
            }

            return(returnValue);
        }
        public static async Task <List <OssIndexResponse> > CheckVulnerabilityOnPackage(PackageMagic package, string packageManager)
        {
            List <OssIndexResponse> objResponse = null;
            var result = await Client.GetAsync($"v2.0/package/{packageManager}/{package.Name}/{package.Version}");

            if (result.IsSuccessStatusCode)
            {
                string content = await result.Content.ReadAsStringAsync();

                objResponse = JsonConvert.DeserializeObject <List <OssIndexResponse> >(content);
                Console.WriteLine($"Checked vulnerabilitys from OSS Index -  {packageManager}/{package.Name}/{package.Version}");
                foreach (var item in objResponse)
                {
                    package.OssIndexResponse = item;
                    if (item.vulnerabilities != null)
                    {
                        Console.WriteLine($"*************************************************************");

                        Console.WriteLine($"Vulnerability found in package - {package.Name}:{package.Version}");
                        foreach (var vul in item.vulnerabilities)
                        {
                            Console.WriteLine($"Vulnerability found in package - {vul.title}");
                            Console.WriteLine($"Vulnerability found in package - {vul.description}");
                            Console.WriteLine($"Vulnerability found in package - {vul.resource}");
                        }
                        Console.WriteLine($"*************************************************************");
                    }
                }
            }
            else
            {
                Console.WriteLine($"OSS Index error statuscode {result.StatusCode}");
            }

            return(objResponse);
        }
示例#54
0
        public void LogPageShare(ContentHead content, string serverHost, bool logShare = true, bool logComments = false)
        {
            string url = serverHost + content.Location + content.CanonicalName;

            string appDataPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");

            System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient();

            wc.GetAsync("https://graph.facebook.com/?id=" + url)
                .ContinueWith(task => {

                    if (task.IsFaulted && DebugCMS) {
                        string filePath = appDataPath + "\\logShareError" + DateTime.Now.ToString().Replace("/", ".").Replace(":", ".") + ".txt";
                        using (StreamWriter sw = System.IO.File.CreateText(filePath)) {
                            sw.WriteLine("https://graph.facebook.com/?id=" + url);
                            sw.WriteLine("Exception: " + task.Exception.Message);
                            if(task.Exception.InnerException!=null)
                                sw.WriteLine("InnerException: " + task.Exception.InnerException.Message);
                            if (task.Exception.InnerException.InnerException != null)
                                sw.WriteLine("InnerException 2: " + task.Exception.InnerException.InnerException.Message);
                        }
                    }

                    if (task.IsFaulted || task.IsCanceled)
                        return;
                    var msg = task.Result;
                    dynamic data = null;

                    if (msg.StatusCode != System.Net.HttpStatusCode.OK)
                        return;

                    string json = msg.Content.ReadAsStringAsync().Result;
                    data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);

                    if (logShare) {
                        if (data.shares == null)
                            UpdateShareCount(content.ContentUId, 0);
                        else
                            UpdateShareCount(content.ContentUId, (long)data.shares);
                    }

                    if (logComments) {
                        if (data.comments == null)
                            UpdateCommentCount(content.ContentUId, 0);
                        else
                            UpdateCommentCount(content.ContentUId, (int)data.comments);
                    }

                });
        }
示例#55
0
        protected dynamic GetUserData(string token)
        {
            System.Net.Http.HttpClient wc = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage msg = wc.GetAsync(String.Format(GET_USER_URL, token)).Result;

            dynamic data = null;

            if (msg.StatusCode == System.Net.HttpStatusCode.OK) {
                string json = msg.Content.ReadAsStringAsync().Result;
                data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
            }

            return data;
        }
示例#56
0
        // helper method
        private static async Task<RootObject> CallService(Uri uri)
        {
            string jsonString = string.Empty;
            try
            {
                // fetch from rest service
                var httpClient = new System.Net.Http.HttpClient();
                var httpResponse = await httpClient.GetAsync(uri.ToString());
                jsonString = await httpResponse.Content.ReadAsStringAsync();

                // check for error
                if (!jsonString.Contains("\"statusCode\":200"))
                    throw new InvalidStatusCodeException { JSON = jsonString };
                if (jsonString.Contains("InvalidCredentials")
                    || jsonString.Contains("CredentialsExpired")
                    || jsonString.Contains("NotAuthorized")
                    || jsonString.Contains("NoCredentials"))
                    throw new InvalidCredentialsException { JSON = jsonString };

                // deserialize json to objects
                var jsonBytes = Encoding.Unicode.GetBytes(jsonString);
                using (MemoryStream _MemoryStream = new MemoryStream(jsonBytes))
                {
                    var jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
                    var result = (RootObject)jsonSerializer.ReadObject(_MemoryStream);
                    return result;
                }
            }
            catch (InvalidSomethingException) { throw; }
            catch (Exception e) { throw new InvalidSomethingException(e) { JSON = jsonString }; }
        }
示例#57
0
        private async Task<DataTable> DownloadByUri(string uri, DownloadType downloadtype)
        {
            using(var client = new System.Net.Http.HttpClient())
            {
                // Request headers
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);

                var response = await client.GetAsync(uri).ConfigureAwait(false);
                var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // select response jobject from 
                JObject message = JsonConvert.DeserializeObject<JObject>(json.ToString());

                // deserialize json string to datatable, default format is class object
                if (downloadtype == DownloadType.ScheduledWork)
                {
                    return ResponseToScheduledWorkTable(message["response"].ToString());
                }
                else
                {
                    return JsonConvert.DeserializeObject<DataTable>(message["response"].ToString());
                }
            }
        }
        private async Task<string> Get(string uri)
        {
            var client = new System.Net.Http.HttpClient ();

            client.BaseAddress = new Uri(BaseUrL);

            var response = await client.GetAsync(string.Format("{0}?key={1}", uri, Key));

            response.EnsureSuccessStatusCode();

            var result = response.Content.ReadAsStringAsync().Result;
            return result;
        }
        private  void GetCountsFromWeb(ref webResults VoteColorPair)
        {
            //Create an HTTP client object
            // Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient();
            System.Net.Http.HttpClient snhClient = new System.Net.Http.HttpClient();
            //Add a user-agent header to the GET request. 
            var headers = snhClient.DefaultRequestHeaders;

            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }

            Uri requestUri = new Uri(RestUrlBox.Text);

            //Send the GET request asynchronously and retrieve the response as a string.
            System.Net.Http.HttpResponseMessage snhResponse = new System.Net.Http.HttpResponseMessage();
   
           // Windows.Web.Http.HttpResponseMessage httpResponse = new Windows.Web.Http.HttpResponseMessage();
            string httpResponseBody = "";

            try
            {
                int Reds = -1;
                int Blues = -1;

                //Send the GET request
                snhResponse = snhClient.GetAsync(requestUri).Result;
                //httpResponse =  await httpClient.GetAsync(requestUri,Windows.Web.Http.HttpCompletionOption.ResponseContentRead).Re;
                snhResponse.EnsureSuccessStatusCode();
                //httpResponse.EnsureSuccessStatusCode();
                //httpResponseBody = httpResponse.Content.ToString();
                httpResponseBody = snhResponse.Content.ReadAsStringAsync().Result;
                debugText.Text += httpResponseBody;
                int blueCloseCurlyLoc = httpResponseBody.IndexOf("}");
                string bluestring = httpResponseBody.Substring(0, blueCloseCurlyLoc);
                int lastColonLoc = bluestring.LastIndexOf(":");
                bluestring = bluestring.Substring(lastColonLoc+1, blueCloseCurlyLoc - lastColonLoc-1);
                Blues = int.Parse(bluestring);

                int redCloseCurlyLoc = httpResponseBody.LastIndexOf("}");
                string redstring = httpResponseBody.Substring(blueCloseCurlyLoc+1, redCloseCurlyLoc - blueCloseCurlyLoc);
                lastColonLoc = redstring.LastIndexOf(":");
                redCloseCurlyLoc = redstring.LastIndexOf("}");
                redstring = redstring.Substring(lastColonLoc + 1, redCloseCurlyLoc - lastColonLoc - 1);
                Reds = int.Parse(redstring);

                /*                JObject voteJson = JObject.Parse(httpResponseBody);
                if (voteJson[0]["Color"].ToString() == "Blue")
                {
                    Blues = int.Parse(voteJson[0]["Count"].ToString());
                }
                if (voteJson[1]["Color"].ToString() == "Red")
                {
                    Reds = int.Parse(voteJson[1]["Count"].ToString());
                }
*/

                VoteColorPair.RedVotes = Reds;
                VoteColorPair.BlueVotes = Blues;
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
                debugText.Text = httpResponseBody;
            }


        }
示例#60
0
        public override IGISLegend GetLegend(GISLayerInfo selectedLayer)
        {
            try
            {
                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
                httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
                System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> response = httpClient.GetAsync(string.Empty);
                System.Threading.Tasks.Task<string> responseBody = response.Result.Content.ReadAsStringAsync();

                MemoryStream stream1 = new MemoryStream();
                StreamWriter sw = new StreamWriter(stream1);
                sw.Write(responseBody);
                System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(EsriLegend));
                StreamReader sr = new StreamReader(stream1);
                EsriLegend p2 = (EsriLegend)ser.ReadObject(stream1);
                return p2;
            }
            catch (System.Net.WebException e)
            {
                throw e;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }