Пример #1
26
        public async Task<bool> apiPOST(string access_token, string response, string href)
        {
            
            mlibrary = new methodLibrary();
            HttpClient httpClient = new HttpClient();
            try
            {
                httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));

                var httpResponseMessage = await httpClient.PostAsync(new Uri(href), new HttpStringContent(response));
                string resp = await httpResponseMessage.Content.ReadAsStringAsync();
                await mlibrary.writeFile("POSTresponse", resp);
                Debug.WriteLine(resp);
                ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;
            }
            catch(Exception ex)
            {
                Debug.WriteLine("Caught exception : " + ex);
                               
                return false;
            }
            
            return true;
        }
Пример #2
11
        public async Task<bool> TelemetryIngest(Telemetry telemetry)
        {

            string serviceBusNamespace = "iotmc-ns";
            string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";
            string eventHubSASKey = "<< Your SAS Key here >>";

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri));
                httpClient.DefaultRequestHeaders.Accept.Clear();

                string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri);
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken);
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(telemetry), Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
              
                string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName);
                var response = await httpClient.PostAsync(ingestPath, httpContent);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }

                return false;
            }
        }
Пример #3
5
        public async Task<bool> Initialize()
        {
            _client = new HttpClient();

            // Define the data needed to request an authorization token.
            var service = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
            var scope = "http://music.xboxlive.com";
            var grantType = "client_credentials";

            // Create the request data.
            var requestData = new Dictionary<string, string>();
            requestData["client_id"] = CLIENT_ID;
            requestData["client_secret"] = CLIENT_SECRET;
            requestData["scope"] = scope;
            requestData["grant_type"] = grantType;

            // Post the request and retrieve the response.
            string token = null;
            var response = await _client.PostAsync(new Uri(service), new HttpFormUrlEncodedContent(requestData));
            var responseString = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                token = Regex.Match(responseString, ".*\"access_token\":\"(.*?)\".*", RegexOptions.IgnoreCase).Groups[1].Value;
            }
            else
            {
                await new MessageDialog("Authentication failed. Please provide a valid client.").ShowAsync();
                App.Current.Exit();
            }
            
            Token = token;
            return (token != null) ? true : false;
        }
Пример #4
3
        public async Task<JsonValue> PostAsync(string relativeUri)
        {
            HttpStringContent content = new HttpStringContent(message.Stringify(), UnicodeEncoding.Utf8, "application/json");

            HttpClient httpClient = new HttpClient();
            HttpResponseMessage httpResponse = null;
            try
            {
                httpResponse = await httpClient.PostAsync(new Uri(serverBaseUri, relativeUri), content);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                    case E_WINHTTP_TIMEOUT:
                    // The connection to the server timed out.
                    case E_WINHTTP_NAME_NOT_RESOLVED:
                    case E_WINHTTP_CANNOT_CONNECT:
                    case E_WINHTTP_CONNECTION_ERROR:
                    // Unable to connect to the server. Check that you have Internet access.
                    default:
                        // "Unexpected error connecting to server: ex.Message
                        return null;
                }
            }

            // We assume that if the server responds at all, it responds with valid JSON.
            return JsonValue.Parse(await httpResponse.Content.ReadAsStringAsync());
        }
Пример #5
2
        private async Task<string> HttpPost(string relativeUri, string json)
        {
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            try
            {
                HttpClient client = new HttpClient();

                Uri uri = new Uri($"http://{Ip}:{Port}/api/{relativeUri}");
                HttpStringContent httpContent = new HttpStringContent(json);
                HttpResponseMessage response = await client.PostAsync(uri, httpContent).AsTask(cts.Token);

                if (!response.IsSuccessStatusCode)
                {
                    return string.Empty;
                }

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

                System.Diagnostics.Debug.WriteLine(jsonResponse);

                return jsonResponse;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
Пример #6
1
		private async Task<String> Post(string path, string json)
		{
			var cts = new CancellationTokenSource();
			cts.CancelAfter(5000);

			try
			{
				HttpClient client = new HttpClient();
				HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json");

				Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);
				var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token);

				if (!response.IsSuccessStatusCode)
				{
					return string.Empty;
				}

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

				return jsonResponse;
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				return string.Empty;
			}
		}
Пример #7
1
        private async Task Authorize(string code)
        {
            Uri uri = new Uri("https://api.weibo.com/oauth2/access_token");

            List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();

            pairs.Add(new KeyValuePair<string, string>("client_id", appInfo.Key));
            pairs.Add(new KeyValuePair<string, string>("client_secret", appInfo.Secret));
            pairs.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
            pairs.Add(new KeyValuePair<string, string>("code", code));
            pairs.Add(new KeyValuePair<string, string>("redirect_uri", appInfo.RedirectUri));

            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);

            using (HttpClient client = new HttpClient())
            {
                DateTime time = DateTime.Now;

                HttpResponseMessage response;
                try
                {
                    response = await client.PostAsync(uri, content);
                }
                catch (Exception ex)
                {
                    throw new Exception("network error", ex);
                }
                string json = await response.Content.ReadAsStringAsync();

                JObject accessToken = JsonConvert.DeserializeObject<JObject>(json);
                UserInfo.Token = accessToken["access_token"].ToString();
                UserInfo.ExpiresAt = Untils.ToTimestamp(time) + (long)accessToken["expires_in"];
                UserInfo.Uid = accessToken["uid"].ToString();
            }
        }
Пример #8
0
 private static async Task<string> PostAsync(string url, string content)
 {
    var client = new HttpClient();
    var response = await client.PostAsync(new Uri(url), new HttpStringContent(content));
    var result = await response.Content.ReadAsStringAsync();
    return result;
 }
Пример #9
0
		private static async Task<string> PostFormNoParse(string url, Dictionary<string, string> args) {
			var client = new HttpClient();

			var response = await client.PostAsync(new Uri(url), new HttpFormUrlEncodedContent(args));
			var responseString = await response.Content.ReadAsStringAsync();
			return responseString;
        }
Пример #10
0
		//public List<CartUnit> Units { get; set; }
		//public List<CartOption> Options { get; set; }

		public static async Task<Cart> SetCarUnit(CancellationToken token, string cartKey, int searchDateId, int unitId, int currencyId, double pricePerItem, int taxId, long crc) {
			var cart = new Cart();

			using (var httpClient = new HttpClient()) {
				var apiKey = Common.StorageService.LoadSetting("ApiKey");
				var apiUrl = Common.StorageService.LoadSetting("ApiUrl");
				var profileToken = Common.StorageService.LoadSetting("ProfileToken");

				httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
				httpClient.DefaultRequestHeaders.Add("token", apiKey);
				httpClient.DefaultRequestHeaders.Add("api-version", "2");
				httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);

				var criteria = new CartUnitCriteria() {
					CartKey = cartKey,
					SearchDateId = searchDateId,
					UnitId = unitId,
					CurrencyId = currencyId,
					PricePerItem = pricePerItem,
					TaxId = taxId,
					Crc = crc
				};

				var url = apiUrl + "/api/cart/unit/";
				var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

				using (var httpResponse = await httpClient.PostAsync(new Uri(url), queryString).AsTask(token)) {
					string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token);
					json = json.Replace("<br>", Environment.NewLine);
					cart = JsonConvert.DeserializeObject<Cart>(json);
				}
			}

			return cart;
		}
 public async Task<string> ExecuteAsync()
 {
     if (OAuthSettings.AccessToken != null)
     {
         return OAuthSettings.AccessToken;
     }
     else if (OAuthSettings.RefreshToken == null)
     {
         return null;
     }
     using (var client = new HttpClient())
     {
         var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{
                         {"grant_type","refresh_token"},
                         {"refresh_token", OAuthSettings.RefreshToken},
                         {"client_id", OAuthSettings.ClientId},
                         {"client_secret", OAuthSettings.ClientSecret}
                     });
         var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content);
         response.EnsureSuccessStatusCode();
         var contentString = await response.Content.ReadAsStringAsync();
         var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString);
         OAuthSettings.AccessToken = accessTokenInfo.AccessToken;
         OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken;
         return OAuthSettings.AccessToken;
     }
 }
Пример #12
0
        public async Task<bool> SendRemoteCommandAsync(string pressedKey) 
        {
            bool succeeded = false;
            string address = String.Empty;

            if (!string.IsNullOrWhiteSpace(pressedKey) && !string.IsNullOrWhiteSpace(_ipAddress))
            {
                address = "http://" + _ipAddress + "/RemoteControl/KeyHandling/sendKey?key=" + pressedKey;

                var uri = new Uri(address, UriKind.Absolute);

                using (HttpClient client = new HttpClient())
                {
                    HttpRequestMessage request = new HttpRequestMessage();

                    request.RequestUri = new Uri(address);

                    IHttpContent httpContent = new HttpStringContent(String.Empty);
                    try
                    {
                        await client.PostAsync(uri, httpContent);
                    }
                    catch (Exception)
                    {
                        return succeeded = false;
                    }

                    return succeeded = true;
                }
            }
            return succeeded = false;
        }
Пример #13
0
        /// <summary>
        /// 约定成功登陆返回0,不成功返回错误代码,未知返回-1
        /// </summary>
        /// <returns></returns>
        public async Task<int> DoLogin()
        {
            var httpClient = new HttpClient();
            var requestUrl = "https://net.zju.edu.cn/cgi-bin/srun_portal";
            var formcontent = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("action","login"),
                new KeyValuePair<string, string>("username",_mAccount.Username),
                new KeyValuePair<string, string>("password",_mAccount.Password),
                new KeyValuePair<string, string>("ac_id","3"),
                new KeyValuePair<string, string>("type","1"),
                new KeyValuePair<string, string>("wbaredirect",@"http://www.qsc.zju.edu.cn/"),
                new KeyValuePair<string, string>("mac","undefined"),
                new KeyValuePair<string, string>("user_ip",""),
                new KeyValuePair<string, string>("is_ldap","1"),
                new KeyValuePair<string, string>("local_auth","1"),
            });
            var response = await httpClient.PostAsync(new Uri(requestUrl), formcontent);
            if (response.Content != null)
            {
                string textMessage = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(textMessage);
            }

            httpClient.Dispose();

            return -1;
        }
Пример #14
0
        public async Task<string> PostStringAsync(string link, string param)
        {

            try
            {

                System.Diagnostics.Debug.WriteLine(param);

                Uri uri = new Uri(link);

                HttpClient httpClient = new HttpClient();


                HttpStringContent httpStringContent = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/x-www-form-urlencoded"); //,Windows.Storage.Streams.UnicodeEncoding.Utf8
                
                HttpResponseMessage response = await httpClient.PostAsync(uri,

                                                       httpStringContent).AsTask(cts.Token);
                responseHeaders = response.Headers;
                System.Diagnostics.Debug.WriteLine(responseHeaders);

                string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);
                return responseBody;
            }
            catch(Exception e)
            {
                return "Error:" + e.Message;
            }

        }
Пример #15
0
        /// <summary>
        /// Invoked to acquire the PlayReady license.
        /// </summary>
        /// <param name="licenseServerUri">License Server URI to retrieve the PlayReady license.</param>
        /// <param name="httpRequestContent">HttpContent including the Challenge transmitted to the PlayReady server.</param>
        public async virtual Task<IHttpContent> AcquireLicense(Uri licenseServerUri, IHttpContent httpRequestContent)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("msprdrm_server_redirect_compat", "false");
                httpClient.DefaultRequestHeaders.Add("msprdrm_server_exception_compat", "false");

                HttpResponseMessage response = await httpClient.PostAsync(licenseServerUri, httpRequestContent);
                response.EnsureSuccessStatusCode();
                
                if (response.StatusCode == HttpStatusCode.Ok)
                {
                    _lastErrorMessage = string.Empty;
                    return response.Content;
                }
                else
                {
                    _lastErrorMessage = "AcquireLicense - Http Response Status Code: " + response.StatusCode.ToString();
                }
            }
            catch (Exception exception)
            {
                _lastErrorMessage = exception.Message;
                return null;
            }
            return null;
        }
Пример #16
0
		public static async Task<Chat> PostChatMessage(int chatId, string message) {
			var chat = new Chat();

			//var authenticatedProfile = await Common.StorageService.RetrieveObjectAsync<Profile>("Profile");

			using (var httpClient = new HttpClient()) {
				var apiKey = Common.StorageService.LoadSetting("ApiKey");
				var apiUrl = Common.StorageService.LoadSetting("ApiUrl");
				var profileToken = Common.StorageService.LoadSetting("ProfileToken");

				httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
				httpClient.DefaultRequestHeaders.Add("token", apiKey);
				httpClient.DefaultRequestHeaders.Add("api-version", "2");
				httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);

				var criteria = new NewChatMessageCriteria {
					ChatId = chatId,
					Message = message
				};

				var uri = new Uri(apiUrl + "/api/chat/message");
				var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");

				HttpResponseMessage response = await httpClient.PostAsync(uri, queryString);
				string json = await response.Content.ReadAsStringAsync();
				json = json.Replace("<br>", Environment.NewLine);
				chat = JsonConvert.DeserializeObject<Chat>(json);
			}

			return chat;
		}
 public async Task SavePaymentMethodAsync(PaymentMethod paymentMethod)
 {
     using (var client = new HttpClient())
     {
         var response = await client.PostAsync(new Uri(_clientBaseUrl), new HttpStringContent(JsonConvert.SerializeObject(paymentMethod), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"));
         await response.EnsureSuccessWithValidationSupportAsync();
     }
 }
Пример #18
0
 public async Task<HttpResponseMessage> ExecuteSOAPRequest(string uri, string data, string soapAction)
 {
     HttpClient client = new HttpClient();
     var httpStringContent = new HttpStringContent(data, UnicodeEncoding.Utf8, "text/xml");
     client.DefaultRequestHeaders.Add("SOAPAction", soapAction);
     var message = await
         client.PostAsync(new Uri(uri), httpStringContent);
     return message;
 }
 public async Task RemoveProductFromShoppingCartAsync(string shoppingCartId, string productIdToDecrement)
 {
     using (var shoppingCartClient = new HttpClient())
     {
         string requestUrl = _shoppingCartBaseUrl + shoppingCartId + "?productIdToDecrement=" + productIdToDecrement;
         var response = await shoppingCartClient.PostAsync(new Uri(requestUrl), null);
         response.EnsureSuccessStatusCode();
     }
 }
        public async Task SaveAddressAsync(Address address)
        {
            using (var client = new HttpClient())
            {
                var serializedAddress = JsonConvert.SerializeObject(address);

                var response = await client.PostAsync(new Uri(_clientBaseUrl), new HttpStringContent(serializedAddress, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"));
                await response.EnsureSuccessWithValidationSupportAsync();
            }
        }
Пример #21
0
		/// <summary>
		/// Attemps to login to the server
		/// </summary>
		/// <param name="username">The Username</param>
		/// <param name="password">The Password</param>
		/// <returns>
		/// true if the app was able to login
		/// </returns>
		public async Task<LoginStatus> LoginAsync(string username, string password)
		{
			UriBuilder builder;
			try
			{
				builder = new UriBuilder(new Uri(settings.ServerUrl));
				builder.Path = "/Account/Login";
			}
			catch(UriFormatException)
			{
				return LoginStatus.InvalidServerUrl;
			}

			HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter();
			
			using (var client = new HttpClient(httpFilter))
			{
				var content = new Windows.Web.Http.HttpFormUrlEncodedContent(new KeyValuePair<String, String>[]
				{
					new KeyValuePair<string, string>("Email", username),
					new KeyValuePair<string, string>("Password", password),
					new KeyValuePair<string, string>("RememberMe", "true")
				});
				HttpResponseMessage result = null;
				try
				{
					result = await client.PostAsync(builder.Uri, content);
				}
				catch (COMException ce)
				{
					if(ce.HResult == -2147012867)
					{
						return LoginStatus.UnableToConnectToServer;
					}

					return LoginStatus.Error;
				}
				if (result.StatusCode == HttpStatusCode.Ok)
				{
					var cookies = httpFilter.CookieManager.GetCookies(new Uri($"{builder.Scheme}://{builder.Host}:{builder.Port}"));
					var authz = cookies.FirstOrDefault(i => String.Compare(i.Name, "Authz") == 0);
					if(authz != null)
					{
						this.authz = authz;
						return LoginStatus.Success;
					}
					else
					{
						return LoginStatus.ErrorAuthenticating;
					}
				}
			}

			return LoginStatus.Unknown;
		}
Пример #22
0
 //primjer post zahtjeva prema servisu
 public async void dodajKorisnika(Uposlenik uposlenik)
 {
     HttpClient httpClient = new HttpClient();
     //mora se stavity content/type da je json inace ce aplikacija da odbija zahtjev
     httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
     //json se salje u body post zahtjeva
     string jsonContents = JsonConvert.SerializeObject(uposlenik);
     HttpResponseMessage response = await httpClient.PostAsync(new Uri(serviceHost+ uposleniciName), new HttpStringContent(jsonContents, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json"));
     //dalje sa odgovorom se moze uraditi sta god zatreba
     JsonValue value = JsonValue.Parse(response.Content.ToString());
 }
Пример #23
0
    public static Task <HttpResponseMessage> PostAsJsonAsync <T>(this HttpClient httpClient, string url, T data)
    {
        var dataAsString = JsonConvert.SerializeObject(data);

#pragma warning disable CA2000 // Dispose objects before losing scope
        var content = new StringContent(dataAsString);
#pragma warning restore CA2000 // Dispose objects before losing scope
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return(httpClient?.PostAsync(new Uri(url), content));
    }
Пример #24
0
        static async Task AsyncTask(Dictionary<string, string> pairs)
        {
            Uri signup_uri = new Uri(SLOT_URL);
            HttpClient client = new HttpClient();
            HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);
            HttpResponseMessage res = await client.PostAsync(signup_uri, content);
            if (res.IsSuccessStatusCode)
            {
                response = res.Content.ToString();

            }
        }
Пример #25
0
        public static async Task<string> PostCallAsync(string url, string parameters)
        {
            var content = new StringContent(parameters);
            string output = string.Empty;
            using (var client = new HttpClient())
            {   
                HttpResponseMessage response = await client.PostAsync(url, content);
                output = await response.Content.ReadAsStringAsync();
            }

            return output;
        }
Пример #26
0
 public static async Task<string> GetTextByPost(string posturi, string poststr, IEnumerable<KeyValuePair<string, string>> body)
 {
     var httpClient = new HttpClient();
     //CreateHttpClient(ref httpClient);
     var postData = new HttpFormUrlEncodedContent(body);
     string responseString;
     using (var response = await httpClient.PostAsync(new Uri(posturi), postData))
     {
         responseString = await response.Content.ReadAsStringAsync();
     }
     return responseString;
 }
        public async Task<bool> MergeShoppingCartsAsync(string anonymousShoppingCartId, string authenticatedShoppingCartId)
        {
            using (var shoppingCartClient = new HttpClient())
            {
                string requestUrl = _shoppingCartBaseUrl + authenticatedShoppingCartId + "?anonymousShoppingCartId=" + anonymousShoppingCartId;
                var response = await shoppingCartClient.PostAsync(new Uri(requestUrl), null);
                response.EnsureSuccessStatusCode();
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<bool>(responseContent);

                return result;
            }
        }
        public async Task <bool> AddItemAsync(Item item)
        {
            if (item == null || !IsConnected)
            {
                return(false);
            }

            var serializedItem = JsonConvert.SerializeObject(item);

            var response = await client?.PostAsync($"api/item", new StringContent(serializedItem, Encoding.UTF8, "application/json"));

            return(response.IsSuccessStatusCode);
        }
Пример #29
0
        public static async Task<string> RetrieveUsername()
        {
            System.Diagnostics.Debug.WriteLine("Retrieving username");
            Boolean hasGotUsername = false;
            string jsonResponse = "";
            string usernameRetrieved = "";
            while (!hasGotUsername)
            {
                try
                {
                    HttpClient client = new HttpClient();
                    HttpStringContent content = new HttpStringContent("{\"devicetype\":\"HueApp#ComfyCrew\"}", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
                    string ip, username;
                    int port;
                    SettingsService.RetrieveSettings(out ip, out port, out username);
                    var response = await client.PostAsync(new Uri(string.Format("http://{0}:{1}/api/", ip, port)), content);

                    if (!response.IsSuccessStatusCode)
                    {
                        return string.Empty;
                    }

                    jsonResponse = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine(jsonResponse);

                    JsonArray jsonArray = JsonArray.Parse(jsonResponse);
                    ICollection<string> keys = jsonArray.First().GetObject().Keys;
                    if (keys.Contains("error"))
                    {
                        Hugh.Views_Viewmodels.MainPage.ShowErrorDialogue();
                        await Task.Delay(TimeSpan.FromSeconds(1));
                    }
                    else
                    {
                        hasGotUsername = true;
                        JsonObject succesObject = jsonArray.First().GetObject();

                        System.Diagnostics.Debug.WriteLine(succesObject.Values.First().GetObject().Values.First().GetString());
                        usernameRetrieved = succesObject.Values.First().GetObject().Values.First().GetString();
                    }

                }
                catch (Exception)
                {
                    return string.Empty;
                }
            }
            return usernameRetrieved;
        }
        /// <summary>
        /// Common method to request in POST, GET, PUT and DELETE form to get data in key value format.
        /// </summary>
        /// <param name="requestType"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns name="StatusAndResponseClass"></returns>
        public static async Task <StatusAndResponseClass> Request(RequestType requestType, string url, Dictionary <string, string> data, Dictionary <string, string> header)
        {
            StatusAndResponseClass getResponse = new StatusAndResponseClass();
            HttpClient             client      = new HttpClient();

            if (header != null && header.Count() > 0)
            {
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            IProgress <Windows.Web.Http.HttpProgress> progress = new Progress <Windows.Web.Http.HttpProgress>(ProgressHandler);
            HttpResponseMessage response = new HttpResponseMessage();
            HttpContent         content;

            System.Diagnostics.Debug.WriteLine("PostStringJsonData (URL): " + url);
            System.Diagnostics.Debug.WriteLine("PostStringJsonData (POSTDATA): " + data);
            try
            {
                switch (requestType)
                {
                case RequestType.POST:
                    content  = new FormUrlEncodedContent(data);
                    response = await client.PostAsync(new Uri(url), content, cancellationToken.Token);

                    break;

                case RequestType.GET:
                    var message = new HttpRequestMessage(HttpMethod.Get, url);
                    response = await client.SendAsync(message, cancellationToken.Token);

                    //response = await client.GetAsync(new Uri(url));
                    break;

                case RequestType.PUT:
                    content  = new FormUrlEncodedContent(data);
                    response = await client.PutAsync(new Uri(url), content, cancellationToken.Token);

                    break;

                case RequestType.DELETE:
                    content  = new FormUrlEncodedContent(data);
                    response = await client.DeleteAsync(new Uri(url + content), cancellationToken.Token);

                    break;

                default:
                    break;
                }
                client.Dispose();
                HttpStatusCode statuscode   = response.StatusCode;
                string         responseBody = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    getResponse.responseString = responseBody;
                }
                else
                {
                    getResponse.responseString = responseBody;
                }
                getResponse.statusCode = Convert.ToInt32(statuscode);
                if (getResponse.statusCode == 404)
                {
                    getResponse.responseString = string.Empty;
                }
                return(getResponse);
            }
            catch (Exception ex)
            {
                return(getResponse);
            }
        }
Пример #31
0
        public void Security_AuthorizeEndpointTests(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, AuthServerHappyPathConfiguration);

                IDisposable clientEndpoint = null;
                try
                {
                    clientEndpoint = WebApp.Start(Client_Redirect_Uri, app => app.Run(context => { return(context.Response.WriteAsync(context.Request.QueryString.Value)); }));

                    string tokenEndpointUri = applicationUrl + "TokenEndpoint";
                    var    basicClient      = new HttpClient();
                    var    headerValue      = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", "123", "invalid")));
                    basicClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);

                    HttpClient          httpClient          = new HttpClient();
                    string              requestUri          = null;
                    Uri                 landingUri          = null;
                    Uri                 applicationUri      = new Uri(applicationUrl);
                    HttpResponseMessage httpResponseMessage = null;

                    //Happy path - response_type:code
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Happy path - response_type:token
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    landingUri = new Uri(landingUri.AbsoluteUri.Replace('#', '?'));
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["access_token"]);
                    Assert.NotNull(landingUri.ParseQueryString()["expires_in"]);
                    Assert.Equal <string>("bearer", landingUri.ParseQueryString()["token_type"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Invalid redirect URI - pass error to application
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_passonerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>("error: invalid_request\r\n", httpResponseMessage.Content.ReadAsStringAsync().Result);
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");

                    //Invalid redirect URI - Display error by middleware
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_displayerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //What happens if we don't set Validated explicitly. Send an invalid clientId => We don't set Validated for this case.
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", "invalidClient", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //OnValidateAuthorizeRequest - Rejecting a request. Send an invalid state as we validate it there. Client should receive all the error code & description that we send
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "invalidstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    landingUri          = httpResponseMessage.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("state.invalid", landingUri.ParseQueryString()["error"]);
                    Assert.Equal <string>("state.invaliddescription", landingUri.ParseQueryString()["error_description"]);
                    Assert.Equal <string>("state.invaliduri", landingUri.ParseQueryString()["error_uri"]);
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error=state.invalid&error_description=state.invaliddescription&error_uri=state.invaliduri"), "Did not receive an error when provider did not set Validated");

                    //Missing response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, null, "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("invalid_request", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Unsupported response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "invalid_response_type", "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("unsupported_response_type", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Missing client_id
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", null, Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //Missing state - Should succeed
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", null);
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <bool>(false, landingUri.ParseQueryString().ContainsKey("state"));

                    //Token endpoint tests
                    //Invalid client (client_id, client_secret) - As form parameters
                    var formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "invalid") });
                    var responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    var jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //Invalid client (client_id, client_secret) - As Basic auth headers
                    responseMessage = basicClient.GetAsync(tokenEndpointUri).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - invalid code being sent
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", "InvalidCode"), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - Full scenario
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", landingUri.ParseQueryString()["code"]), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=password -- Resource owner credentials -- Invalid credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "invalid"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=password -- Resource owner credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "password1"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=refresh_token -- Use the refresh token issued on the previous call
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "refresh_token"), new kvp("refresh_token", jToken.SelectToken("refresh_token").Value <string>()), new kvp("scope", "scope1 scope2") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=client_credentials - Bug# https://github.com/Katana/katana/issues/562
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "client_credentials"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                }
                finally
                {
                    //Finally close the client endpoint
                    if (clientEndpoint != null)
                    {
                        clientEndpoint.Dispose();
                    }
                }
            }
        }
Пример #32
0
    ///<summary>Bliver kaldt når vi skal lave en netværks update</summary>
    private async void OnNetworkUpdate()
    {
        if (isGameMaster == true)
        {
            ServerDataPacket oldPacket = updateIntervalPacket;

            updateIntervalPacket = GenerateServerPacket(oldPacket);

            //Konverter data packeten til json format
            string packetDataJson = JsonUtility.ToJson(updateIntervalPacket);

            //Encode json stringen til base64 string
            string packetDataEncoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(packetDataJson));

            //Send vores data til serveren
            FormUrlEncodedContent packetValue = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("clientType", "master"),
                new KeyValuePair <string, string>("packetData", packetDataEncoded)
            });

            await networkClient.PostAsync(gameserverUrl, packetValue);
        }
        else
        {
            //Send en request til serveren om data
            FormUrlEncodedContent packetValue = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("clientType", "client")
            });

            HttpResponseMessage response = await networkClient.PostAsync(gameserverUrl, packetValue);

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

            //Tjek om der er data og vidersend til handleren
            if (responseData.Trim() != string.Empty)
            {
                //base 64 stringen til json string
                string packetDataDecoded = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(responseData));

                //Konverter json stringen til en data packet
                ServerDataPacket packetData = JsonUtility.FromJson <ServerDataPacket>(packetDataDecoded);

                //Vi tjekker her om sessionen har ændret sig eller om der er en fullupdate, hvis ja så fjerner vi alt i scenen og instantiere alt på nyt
                if (packetData.fullUpdate == true || packetData.gameSession != updateIntervalSession)
                {
                    updateIntervalSession = packetData.gameSession;

                    ResetNetworkedData();
                    CleanupUnnetworkedData();

                    OnNetworkDataReceived(packetData);

                    updateIntervalPacket = packetData;
                }
                else if (packetData.ID > updateIntervalPacket.ID)
                {
                    OnNetworkDataReceived(packetData);

                    updateIntervalPacket = packetData;
                }
            }
        }
    }
Пример #33
0
        /// <summary>
        /// 发送一个 Post 请求
        /// </summary>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="httpClient"></param>
        /// <param name="url">请求地址</param>
        /// <param name="requestContent"></param>
        /// <returns></returns>
        public static async Task <string> PostAsync(this HttpClient httpClient, string url, object requestContent)
        {
            var response = await httpClient.PostAsync(url, new StringContent(JsonConvert.SerializeObject(requestContent), Encoding.UTF8, "application/json"));

            return(await GetContentAsync(response));
        }
        private async Task WorkerAsync()
        {
            _timer.Stop();

            string fromMail = "";

            try
            {
                _emails = EmailService.GetAll().Where(x => !x.IsSent).OrderBy(x => x.Id).ToList();

                if (_emails.Count == 0)
                {
                    _timer.Start(); return;
                }

                foreach (var email in _emails)
                {
                    using (var client = new HttpClient())
                    {
                        client.BaseAddress = new Uri(_apiUrl);

                        using (var stream = new MemoryStream())
                            using (var bson = new BsonWriter(stream))
                            {
                                var jsonSerializer = new JsonSerializer();

                                fromMail = email.From;

                                _emailAttachments = EmailAttachmentService.GetAllNoTracking().Where(x => x.EmailId == email.Id).ToList();

                                var attachments = _emailAttachments.Select(attachment => new EMailAttachmentViewModel
                                {
                                    File     = attachment.File,
                                    FileName = attachment.FileName,
                                    EmailId  = attachment.EmailId
                                }).ToList();

                                if (email.Retry >= _retryLimitation)
                                {
                                    continue;
                                }
                                var willBeSentAgainEmail = new EMailViewModel
                                {
                                    Id               = email.Id,
                                    From             = email.From,
                                    To               = email.To,
                                    Subject          = email.Subject,
                                    Body             = email.Body,
                                    Bcc              = email.Bcc,
                                    Cc               = email.Cc,
                                    Exception        = email.Exception,
                                    Retry            = ++email.Retry,
                                    SmtpServer       = email.SmtpServer,
                                    IsRead           = false,
                                    IsSent           = false,
                                    LastTryDate      = DateTime.Now,
                                    EmailAttachments = attachments
                                };

                                jsonSerializer.Serialize(bson, willBeSentAgainEmail);

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

                                var byteArrayContent = new ByteArrayContent(stream.ToArray());
                                byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/bson");

                                await client?.PostAsync("api/mail/sendemailasync", byteArrayContent, _cancellationToken);
                            }
                    }
                }
                _timer.Start();
            }
            catch (Exception ex)
            {
                _timer.Start();
                #region Write Log
                string address = BaseAddress + ".MailController(IEmail emailService)";
                var    dic     = LogBusiness.GetDictionary();
                dic.Add(LogFieldName.FullyQualifiedFunctionName, address);
                var dicParams = LogBusiness.GetDictionary();
                dicParams.Add(LogFieldName.Token, dicParams);
                dic = LogBusiness.GetDictionary();
                dic.Add(LogFieldName.FullyQualifiedFunctionName, address);
                dic.Add(LogFieldName.ErrorMessage, ex.Message);
                dic.Add(LogFieldName.StackTrace, ex.StackTrace);
                LogBusiness.CustomLog(fromMail, LogEvent.ErrorEvent, dic, dicParams);
                #endregion
            }
            _timer.Start();
        }
Пример #35
0
        public async Task <List <string> > InvokeRequestResponseService(IBrowserFile File)
        {
            List <string> TagList = new();
            var           handler = new HttpClientHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                ServerCertificateCustomValidationCallback =
                    (httpRequestMessage, cert, cetChain, policyErrors) => { return(true); }
            };

            using (var MS = new MemoryStream())
            {
                await File.OpenReadStream(10485760).CopyToAsync(MS);

                MS.Position = 0;
                string base64ImageData = Convert.ToBase64String(MS.ToArray());
                using (var client = new HttpClient(handler))
                {
                    var scoreRequest = new
                    {
                        Inputs = new Dictionary <string, List <Dictionary <string, string> > >()
                        {
                            {
                                "WebServiceInput0",
                                new List <Dictionary <string, string> >()
                                {
                                    new Dictionary <string, string>()
                                    {
                                        {
                                            "image", "data:image/png;base64," + base64ImageData
                                        },
                                        {
                                            "id", "0"
                                        },
                                        {
                                            "category", ""
                                        },
                                    }
                                }
                            },
                        },
                        GlobalParameters = new Dictionary <string, string>()
                        {
                        }
                    };


                    string apiKey = Environment.GetEnvironmentVariable("MLApiKey") ?? MLApiKey; // Replace this with the API key for the web service
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
                    client.BaseAddress = new Uri(Environment.GetEnvironmentVariable("MLUrl") ?? MLUrl);

                    // WARNING: The 'await' statement below can result in a deadlock
                    // if you are calling this code from the UI thread of an ASP.Net application.
                    // One way to address this would be to call ConfigureAwait(false)
                    // so that the execution does not attempt to resume on the original context.
                    // For instance, replace code such as:
                    //      result = await DoSomeTask()
                    // with the following:
                    //      result = await DoSomeTask().ConfigureAwait(false)

                    var requestString = JsonConvert.SerializeObject(scoreRequest);
                    var content       = new StringContent(requestString);

                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    HttpResponseMessage response = await client.PostAsync("", content);

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

                        ImageResponse resultObj = JsonConvert.DeserializeObject <ImageResponse>(result);
                        Console.WriteLine("Normalizing score list");
                        resultObj.Response.SetScoreValues();
                        Console.WriteLine("Fetching top 5 result");
                        var top5Probabilities = (from entry in resultObj.Response.ScoreValues orderby entry.Value descending select entry).Take(5);
                        TagList = top5Probabilities.ToDictionary(k => k.Key, v => v.Value).Keys.ToList();
                    }
                    else
                    {
                        Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                        // Print the headers - they include the requert ID and the timestamp,
                        // which are useful for debugging the failure
                        Console.WriteLine(response.Headers.ToString());

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

                        Console.WriteLine(responseContent);
                    }
                }
            }
            return(TagList);
        }
Пример #36
0
 public async Task PostAsync(string accessToken, string endpoint, object data, string args = null)
 {
     var payload = GetPayload(data);
     await _httpClient.PostAsync($"{endpoint}?access_token={accessToken}&{args}", payload);
 }
Пример #37
0
 public void AddSensor(Sensor sensor)
 {
     var url        = "/sensors/add";
     var jsonString = JsonConvert.SerializeObject(sensor);
     HttpResponseMessage response = client.PostAsync(url, new StringContent(jsonString, Encoding.UTF8, "application/json")).Result;
 }
Пример #38
0
        static void Main(string[] args)
        {
            const string      serverUrl = "http://localhost:61172/";
            HttpClientHandler handler   = new HttpClientHandler();

            handler.UseDefaultCredentials = true;

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(serverUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                try
                {
                    var response = client.GetAsync("api/demohotels").Result;

                    if (response.IsSuccessStatusCode)
                    {
                        string res    = response.Content.ReadAsStringAsync().Result;
                        var    hotels = JsonConvert.DeserializeObject <List <DemoHotel> >(res);
                        foreach (var hotel in hotels)
                        {
                            Console.WriteLine(hotel);
                        }
                    }

                    response = client.GetAsync("api/demohotels/5").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string res   = response.Content.ReadAsStringAsync().Result;
                        var    hotel = JsonConvert.DeserializeObject <DemoHotel>(res);
                        Console.WriteLine("");
                        Console.WriteLine("Get single hotel:");
                        Console.WriteLine(hotel);
                        Console.WriteLine("Rooms:");
                        foreach (DemoRoom dr in hotel.DemoRooms)
                        {
                            Console.WriteLine(dr);
                        }
                    }

                    response = client.DeleteAsync("api/demohotels/42").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var res   = response.Content.ReadAsStringAsync().Result;
                        var hotel = JsonConvert.DeserializeObject <DemoHotel>(res);
                        Console.WriteLine("");
                        Console.WriteLine("Delete single hotel:");
                        Console.WriteLine(hotel);
                    }

                    DemoHotel dh = new DemoHotel()
                    {
                        Hotel_No = 42, Address = "Address 42", Name = "42nd hotel"
                    };
                    String        jsonStr = JsonConvert.SerializeObject(dh);
                    StringContent content = new StringContent(jsonStr, Encoding.ASCII, "application/json");
                    response = client.PostAsync("api/demohotels", content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var res   = response.Content.ReadAsStringAsync().Result;
                        var hotel = JsonConvert.DeserializeObject <DemoHotel>(res);
                        Console.WriteLine("");
                        Console.WriteLine("Create single hotel:");
                        Console.WriteLine(hotel);
                    }
                    else
                    {
                        Console.WriteLine("Failed to create single hotel");
                    }

                    dh = new DemoHotel()
                    {
                        Hotel_No = 42, Address = "Address 42 (update)", Name = "42nd hotel (update)"
                    };
                    jsonStr  = JsonConvert.SerializeObject(dh);
                    content  = new StringContent(jsonStr, Encoding.ASCII, "application/json");
                    response = client.PutAsync("api/demohotels/42", content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Updated single hotel");
                    }
                    else
                    {
                        Console.WriteLine("Failed to update single hotel");
                    }
                }
                catch (Exception)
                {
                }
            }

            Console.ReadLine();
        }
    public async Task <bool> Notify(string title, string message, Dictionary <string, string> customData = default(Dictionary <string, string>))
    {
        try
        {
            if (!receiver.IOSDevices.Any() && !receiver.AndroidDevices.Any())
            {
                return(false);                //No devices to send
            }
            //To make sure in Android, title and message is retain when click from notification. Else it's lost when app is in background
            if (customData == null)
            {
                customData = new Dictionary <string, string>();
            }

            if (!customData.ContainsKey("Title"))
            {
                customData.Add("Title", title);
            }

            if (!customData.ContainsKey("Message"))
            {
                customData.Add("Message", message);
            }

            var push = new Push
            {
                Content = new Content
                {
                    Title      = title,
                    Body       = message,
                    CustomData = customData
                },
                Target = new Target
                {
                    Type = Constants.DeviceTarget
                }
            };

            HttpClient httpClient = new HttpClient();

            //Set the content header to json and inject the token
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add(Constants.ApiKeyName, Constants.FullAccessToken);

            //Needed to solve SSL/TLS issue when
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            if (receiver.IOSDevices.Any())
            {
                push.Target.Devices = receiver.IOSDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/Constants.AppNameiOS}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            if (receiver.AndroidDevices.Any())
            {
                push.Target.Devices = receiver.AndroidDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameAndroid}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            return(true);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());

            return(false);
        }
    }
Пример #40
0
        public static async void Run([TimerTrigger("0 0 14 * * *")] TimerInfo myTimer, ILogger log)
        {
            DateTime start = DateTime.Now.AddDays(-1);

            string time = start.ToString("MM/dd/yyyy");


            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var    azureServiceTokenProvider = new AzureServiceTokenProvider();
            string AuthToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");

            using (var client = new HttpClient())
            {
                // Setting Authorization.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);

                // Setting Base address.
                client.BaseAddress = new Uri("https://management.azure.com");

                // Setting content type.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Initialization.
                HttpResponseMessage response = new HttpResponseMessage();

                string myJson = @"{
                    'dataset': {
                        'aggregation': {
                        'totalCost': {
                            'function': 'Sum',
                            'name': 'PreTaxCost'
                        }
                    },
                    'granularity': 'Daily',
                    'grouping': [
                        {
                            'name': 'ResourceId',
                            'type': 'Dimension'
                        },
                        {
                            'name': 'ResourceType',
                            'type': 'dimension'
                        },
                        {
                            'name': 'SubscriptionName',
                            'type': 'dimension'
                        },
                        {
                            'name': 'ResourceGroup',
                            'type': 'dimension'
                        }
                    ]
                },
                'timePeriod': {
                    'from': '" + time + @"',
                    'to': '" + time + @"'
                },
                'timeframe': 'Custom',
                'type': 'Usage'
            }";
                Console.WriteLine(myJson);
                AzureLogAnalytics logAnalytics = new AzureLogAnalytics(
                    workspaceId: $"{workspaceid}",
                    sharedKey: $"{workspacekey}",
                    logType: $"{logName}");

                foreach (string scope in scopes)
                {
                    Console.WriteLine(scope);
                    // HTTP Post
                    response = await client.PostAsync("/" + scope + "/providers/Microsoft.CostManagement/query?api-version=2019-11-01", new StringContent(myJson, Encoding.UTF8, "application/json"));

                    QueryResults result = Newtonsoft.Json.JsonConvert.DeserializeObject <QueryResults>(response.Content.ReadAsStringAsync().Result);


                    jsonResult = "[";
                    for (int i = 0; i < result.properties.rows.Length; i++)
                    {
                        object[] row  = result.properties.rows[i];
                        double   cost = Convert.ToDouble(row[0]);

                        if (i == 0)
                        {
                            jsonResult += $"{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                        }
                        else
                        {
                            jsonResult += $",{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                        }
                    }

                    jsonResult += "]";
                    logAnalytics.Post(jsonResult);

                    if (result.properties.nextLink != null)
                    {
                        string nextLink  = result.properties.nextLink.ToString();
                        string skipToken = nextLink.Split('&')[1];
                        callAPIPage(scope, skipToken, workspaceid, workspacekey, logName, log, myJson);
                    }
                }
            }
        }
Пример #41
0
 public async Task <HttpResponseMessage> PostAsync(string uri, StringContent content)
 {
     return(await _httpClient.PostAsync(uri, content));
 }
Пример #42
0
        private void SendHttp(byte[] buffer)
        {
            string data = Convert.ToBase64String(buffer);

            lock (_httpClient) _httpClient?.PostAsync(GetUrl("update"), new StringContent(data, Encoding.ASCII)).Wait();
        }
        /// <summary>
        /// Common method to request in POST, GET, PUT and DELETE form to get data in json format.
        /// </summary>
        /// <param name="requestType"></param>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns name="StatusAndResponseClass"></returns>
        public static async Task <StatusAndResponseClass> Request(RequestType requestType, string url, string data, Dictionary <string, string> header)
        {
            StatusAndResponseClass getResponse = new StatusAndResponseClass();
            HttpClient             client      = new HttpClient();

            if (header != null && header.Count() > 0)
            {
                foreach (var item in header)
                {
                    client.DefaultRequestHeaders.Add(item.Key, item.Value);
                }
            }
            HttpResponseMessage response = new HttpResponseMessage();
            StringContent       queryString;

            System.Diagnostics.Debug.WriteLine("PostStringJsonData (URL): " + url);
            System.Diagnostics.Debug.WriteLine("PostStringJsonData (POSTDATA): " + data);
            try
            {
                switch (requestType)
                {
                case RequestType.POST:
                    queryString = new StringContent(data, UTF8Encoding.UTF8, "application/json");
                    response    = await client.PostAsync(new Uri(url), queryString);

                    break;

                case RequestType.GET:
                    response = await client.GetAsync(new Uri(url));

                    break;

                case RequestType.PUT:
                    queryString = new StringContent(data, UTF8Encoding.UTF8, "application/json");
                    response    = await client.PutAsync(new Uri(url), queryString);

                    break;

                case RequestType.DELETE:
                    response = await client.DeleteAsync(new Uri(url + data));

                    break;

                default:
                    break;
                }
                client.Dispose();
                HttpStatusCode statuscode   = response.StatusCode;
                string         responseBody = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    getResponse.responseString = responseBody;
                }
                else
                {
                    getResponse.responseString = responseBody;
                }
                getResponse.statusCode = Convert.ToInt32(statuscode);
                if (getResponse.statusCode == 404)
                {
                    getResponse.responseString = string.Empty;
                }
                return(getResponse);
            }
            catch (Exception ex)
            {
                return(getResponse);
            }
        }
Пример #44
0
        public async Task<List<ActionResult>> Execute(DeploymentTaskExecutionParams execParams)
        {

            var definition = GetDefinition(execParams.Definition);

            var results = await Validate(execParams);
            if (results.Any())
            {
                return results;
            }

            var managedCert = ManagedCertificate.GetManagedCertificate(execParams.Subject);

            if (string.IsNullOrEmpty(managedCert.CertificatePath))
            {
                results.Add(new ActionResult("No certificate to deploy.", false));
                return results;

            }
            string vaultUri = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_uri")?.Value;
            string vaultPath = execParams.Settings.Parameters.FirstOrDefault(c => c.Key == "vault_secret_path")?.Value;

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("X-Vault-Token", execParams.Credentials["api_token"]);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var vaultUrl = $"{vaultUri}{vaultPath}";

            byte[] pfxData = File.ReadAllBytes(managedCert.CertificatePath);

            var pfxPwd = "";

            var secret = new
            {
                data = new
                {
                    key = GetEncodedCertComponent("pemkey", pfxData, pfxPwd),
                    cert = GetEncodedCertComponent("pemcrt", pfxData, pfxPwd),
                    intermediates = GetEncodedCertComponent("pemchain", pfxData, pfxPwd),
                    pfx = GetEncodedCertComponent("pfxfull", pfxData, pfxPwd)
                }
            };

            /*
                {
                  "data": { },
                  "options": { },
                  "version": 0
                }";
            */

            var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(secret), System.Text.UnicodeEncoding.UTF8, "application/json");

            execParams.Log.Information($"Deploying to Vault: {vaultUrl}");

            var response = await httpClient.PostAsync(vaultUrl, content);

            if (response.IsSuccessStatusCode)
            {
                return results;
            }
            else
            {
                var error = await response.Content.ReadAsStringAsync();
                return new List<ActionResult> { new ActionResult("Vault storage failed: " + error, false) };
            }
        }
        public async Task <string> GetUserProfile(string userid)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    var formContent = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("user_id", Settings.User_id),
                        new KeyValuePair <string, string>("user_profile_id", userid),
                        new KeyValuePair <string, string>("s", Settings.Session)
                    });

                    var response = await client.PostAsync(Settings.Website + "/app_api.php?application=phone&type=get_user_data", formContent);

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

                    var    data      = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);
                    string apiStatus = data["api_status"].ToString();
                    if (apiStatus == "200")
                    {
                        JObject userdata = JObject.FromObject(data["user_data"]);
                        //Settings.UserFullName = userdata["name"].ToString();

                        var avatar       = userdata["avatar"].ToString();
                        var cover        = userdata["cover"].ToString();
                        var First_name   = userdata["first_name"].ToString();
                        var Last_name    = userdata["last_name"].ToString();
                        var Website      = userdata["website"].ToString();
                        var user_id      = userdata["user_id"].ToString();
                        var Lastseen     = userdata["lastseen_time_text"].ToString();
                        var url          = userdata["url"].ToString();
                        var is_following = userdata["is_following"].ToString();
                        var Pro_Type     = userdata["pro_type"].ToString();
                        var Is_Pro       = userdata["is_pro"].ToString();
                        var Is_blocked   = userdata["is_blocked"].ToString();


                        S_About = Functions.DecodeString(userdata["about"].ToString());

                        S_Website    = userdata["website"].ToString();
                        S_Name       = userdata["name"].ToString();
                        S_Username   = userdata["username"].ToString();
                        S_Gender     = userdata["gender"].ToString();
                        S_Email      = userdata["email"].ToString();
                        S_Birthday   = userdata["birthday"].ToString();
                        S_Address    = userdata["address"].ToString();
                        S_URL        = userdata["url"].ToString();
                        S_School     = userdata["school"].ToString();
                        S_Working    = userdata["working"].ToString();
                        S_Facebook   = userdata["facebook"].ToString();
                        S_Google     = userdata["google"].ToString();
                        S_Twitter    = userdata["twitter"].ToString();
                        S_Linkedin   = userdata["linkedin"].ToString();
                        S_Youtube    = userdata["youtube"].ToString();
                        S_VK         = userdata["vk"].ToString();
                        S_Instagram  = userdata["instagram"].ToString();
                        S_Can_follow = userdata["can_follow"].ToString();

                        if (Is_Pro == "1")
                        {
                            if (Pro_Type == "1")
                            {
                                StarIcon.IsVisible = true;
                            }
                            else if (Pro_Type == "2")
                            {
                                HotIcon.IsVisible = true;
                            }
                            else if (Pro_Type == "3")
                            {
                                UltimaIcon.IsVisible = true;
                            }
                            else if (Pro_Type == "4")
                            {
                                VIPIcon.IsVisible = true;
                            }
                        }
                        if (Is_blocked == "true")
                        {
                        }

                        CoverImage.Source = ImageSource.FromFile(DependencyService.Get <IPicture>().GetPictureFromDisk(cover, user_id));
                        if (DependencyService.Get <IPicture>().GetPictureFromDisk(cover, user_id) == "File Dont Exists")
                        {
                            CoverImage.Source = new UriImageSource {
                                Uri = new Uri(cover)
                            };
                            DependencyService.Get <IPicture>().SavePictureToDisk(cover, user_id);
                        }

                        AvatarImage.Source = ImageSource.FromFile(DependencyService.Get <IPicture>().GetPictureFromDisk(avatar, user_id));
                        if (DependencyService.Get <IPicture>().GetPictureFromDisk(avatar, user_id) == "File Dont Exists")
                        {
                            AvatarImage.Source = new UriImageSource {
                                Uri = new Uri(avatar)
                            };
                            DependencyService.Get <IPicture>().SavePictureToDisk(avatar, user_id);
                        }

                        if (Website == "")
                        {
                            Website = AppResources.Label_Unavailable;
                        }
                        if (S_School == "")
                        {
                            S_School = AppResources.Label_Askme;
                        }
                        if (S_Birthday == "" || S_Birthday.Contains("00"))
                        {
                            S_Birthday = AppResources.Label_Askme;
                        }
                        if (S_About == "" || S_About == " ")
                        {
                            S_About = Settings.PR_AboutDefault;
                        }
                        if (S_Address == "")
                        {
                            S_Address = AppResources.Label_Unavailable;
                        }
                        if (S_Gender == "")
                        {
                            S_Gender = AppResources.Label_Unavailable;
                        }
                        if (S_Working == "")
                        {
                            S_Working = AppResources.Label_Unavailable;
                        }
                        if (S_Website == "")
                        {
                            S_Website = AppResources.Label_Unavailable;
                        }


                        LastseenLabel.Text = Lastseen;

                        if (Lastseen == "online" || Lastseen == "Online" || Lastseen.Contains("sec") || Lastseen.Contains("Sec"))
                        {
                            LastseenLabel.Text = AppResources.Label_Online;
                        }



                        Username.Text = S_Name;

                        if (UserprofileListItems.Count > 0)
                        {
                            UserprofileListItems.Clear();
                        }

                        if (UserProfilePage.S_About != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_About,
                                Icon  = "\uf040",
                                Color = "#c5c9c8"
                            });
                        }
                        else
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = AppResources.Label_About_Me,
                                Icon  = "\uf040",
                                Color = "#c5c9c8"
                            });
                        }

                        UserprofileListItems.Add(new Userprofiletems()
                        {
                            Label = UserProfilePage.S_Gender,
                            Icon  = "\uf224",
                            Color = "#c5c9c8"
                        });

                        if (UserProfilePage.S_Birthday != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Birthday,
                                Icon  = "\uf133",
                                Color = "#c5c9c8"
                            });
                        }

                        UserprofileListItems.Add(new Userprofiletems()
                        {
                            Label = UserProfilePage.S_Address,
                            Icon  = "\uf041",
                            Color = "#c5c9c8"
                        });



                        UserprofileListItems.Add(new Userprofiletems()
                        {
                            Label = UserProfilePage.S_Website,
                            Icon  = "\uf0ac",
                            Color = "#c5c9c8"
                        });

                        UserprofileListItems.Add(new Userprofiletems()
                        {
                            Label = UserProfilePage.S_School,
                            Icon  = "\uf19d",
                            Color = "#c5c9c8"
                        });

                        UserprofileListItems.Add(new Userprofiletems()
                        {
                            Label = UserProfilePage.S_Working,
                            Icon  = "\uf0b1",
                            Color = "#c5c9c8"
                        });

                        if (UserProfilePage.S_Facebook != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Facebook,
                                Icon  = "\uf09a",
                                Color = "#00487b"
                            });
                        }
                        if (UserProfilePage.S_Google != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Google,
                                Icon  = "\uf0d5",
                                Color = "#be2020"
                            });
                        }

                        if (UserProfilePage.S_VK != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_VK,
                                Icon  = "\uf189",
                                Color = "#326c95"
                            });
                        }

                        if (UserProfilePage.S_Twitter != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Twitter,
                                Icon  = "\uf099",
                                Color = "#5a89aa"
                            });
                        }

                        if (UserProfilePage.S_Youtube != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Youtube,
                                Icon  = "\uf16a",
                                Color = "#be2020"
                            });
                        }

                        if (UserProfilePage.S_Linkedin != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Linkedin,
                                Icon  = "\uf0e1",
                                Color = "#5a89aa"
                            });
                        }

                        if (UserProfilePage.S_Instagram != "")
                        {
                            UserprofileListItems.Add(new Userprofiletems()
                            {
                                Label = UserProfilePage.S_Instagram,
                                Icon  = "\uf16d",
                                Color = "#5a89aa"
                            });
                        }

                        UserInfoList.ItemsSource = UserprofileListItems;
                        this.Title = S_Name;


                        //UserInfoList.HeightRequest = Functions.ListInfoResizer(S_About);



                        var contact = SQL_Commander.GetContactUser(user_id);
                        if (contact != null)
                        {
                            if (contact.UserID == user_id && ((contact.Cover != cover) || (contact.Avatar != avatar) || (contact.Birthday != S_Birthday) || (contact.Name != S_Name) ||
                                                              (contact.Username != S_Username) || (contact.First_name != First_name) || (contact.Last_name != Last_name) || (contact.lastseen != Lastseen) || (contact.About != S_About) || (contact.Website != Website) ||
                                                              (contact.School != S_School)))
                            {
                                if ((contact.Avatar != avatar))
                                {
                                    DependencyService.Get <IPicture>().DeletePictureFromDisk(contact.Avatar, user_id);
                                }
                                if ((contact.Cover != cover))
                                {
                                    DependencyService.Get <IPicture>().DeletePictureFromDisk(contact.Cover, user_id);
                                }

                                contact.UserID     = user_id;
                                contact.Name       = S_Name;
                                contact.Avatar     = avatar;
                                contact.Cover      = cover;
                                contact.Birthday   = S_Birthday;
                                contact.Address    = S_Address;
                                contact.Gender     = S_Gender;
                                contact.Email      = S_Email;
                                contact.Username   = S_Username;
                                contact.First_name = First_name;
                                contact.Last_name  = Last_name;
                                contact.About      = S_About;
                                contact.Website    = Website;
                                contact.School     = S_School;
                                contact.Youtube    = S_Youtube;
                                contact.Facebook   = S_Facebook;
                                contact.Twitter    = S_Twitter;
                                contact.Linkedin   = S_Linkedin;
                                contact.Google     = S_Google;
                                contact.instagram  = S_Instagram;
                                SQL_Commander.UpdateContactUsers(contact);
                            }
                        }
                        else
                        {
                            ContactsTableDB contactt = new ContactsTableDB();
                            contactt.UserID     = user_id;
                            contactt.Name       = S_Name;
                            contactt.Avatar     = avatar;
                            contactt.Cover      = cover;
                            contactt.Birthday   = S_Birthday;
                            contactt.Address    = S_Address;
                            contactt.Gender     = S_Gender;
                            contactt.Email      = S_Email;
                            contactt.Username   = S_Username;
                            contactt.First_name = First_name;
                            contactt.Last_name  = Last_name;
                            contactt.About      = S_About;
                            contactt.Website    = Website;
                            contactt.School     = S_School;
                            contactt.lastseen   = Lastseen;
                            contactt.Youtube    = S_Youtube;
                            contactt.Facebook   = S_Facebook;
                            contactt.Twitter    = S_Twitter;
                            contactt.Linkedin   = S_Linkedin;
                            contactt.Google     = S_Google;
                            contactt.instagram  = S_Instagram;

                            SQL_Commander.InsertContactUsers(contactt);
                        }
                    }
                    else if (apiStatus == "400")
                    {
                        json = AppResources.Label_Error;
                    }
                    return(json);
                }
            }
            catch (Exception)
            {
                return(AppResources.Label_Error);
            }
        }
Пример #46
0
        public async Task <string?> CreateRule(string name, IEnumerable <RuleCondition> conditions, IEnumerable <InternalBridgeCommand> actions)
        {
            CheckInitialized();

            if (conditions == null || !conditions.Any())
            {
                throw new ArgumentNullException(nameof(conditions));
            }
            if (actions == null || !actions.Any())
            {
                throw new ArgumentNullException(nameof(actions));
            }

            if (conditions.Count() > 8)
            {
                throw new ArgumentException("Max 8 conditions allowed", nameof(conditions));
            }
            if (actions.Count() > 8)
            {
                throw new ArgumentException("Max 8 actions allowed", nameof(actions));
            }

            JObject jsonObj = new JObject();

            if (conditions != null && conditions.Any())
            {
                jsonObj.Add("conditions", JToken.FromObject(conditions, new JsonSerializer {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            }
            if (actions != null && actions.Any())
            {
                jsonObj.Add("actions", JToken.FromObject(actions, new JsonSerializer {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            }

            if (!string.IsNullOrEmpty(name))
            {
                jsonObj.Add("name", name);
            }

            string jsonString = JsonConvert.SerializeObject(jsonObj, new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            HttpClient client = await GetHttpClient().ConfigureAwait(false);

            //Create group with the lights we want to target
            var response = await client.PostAsync(new Uri(String.Format("{0}rules", ApiBase)), new JsonContent(jsonString)).ConfigureAwait(false);

            var jsonResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            HueResults rulesResult = DeserializeDefaultHueResult(jsonResult);

            if (rulesResult.Count > 0 && rulesResult.First().Success != null && !string.IsNullOrEmpty(rulesResult.First().Success.Id))
            {
                return(rulesResult.First().Success.Id);
            }

            if (rulesResult.HasErrors())
            {
                throw new HueException(rulesResult.Errors.First().Error.Description);
            }

            return(null);
        }
 public async Task SendEventData(IEnumerable <CoffeeMachineData> coffeeMachineData)
 {
     var body     = JsonConvert.SerializeObject(coffeeMachineData);
     var content  = new StringContent(body, Encoding.UTF8, "application/json");
     var response = await client.PostAsync("https://localhost:44347/event/send", content);
 }
Пример #48
0
        /// <summary>
        /// 调用api方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="aparmList"></param>
        /// <returns></returns>
        public static ClientResult InvokeApi(string url, List <ParmField> aparmList)
        {
            //  File.AppendAllText("D:\\crm.invoke.api.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + url +"   ==>start \r\n");
            if (!url.StartsWith("http"))
            {
                string tempt = System.Configuration.ConfigurationManager.AppSettings["appurl"];
                if (tempt.EndsWith("/"))
                {
                    tempt = tempt.Remove(tempt.Length - 1, 1);
                }
                if (!url.StartsWith("/"))
                {
                    url = "/" + url;
                }
                url = tempt + url;
            }



            ClientResult result = new ClientResult();
            HttpClient   client = new HttpClient();
            Task <HttpResponseMessage> resultTask;

            try
            {
                List <ParmField> curParmList = new List <ParmField>();
                curParmList = aparmList;
                //curParmList.Add(new StringField("sign", sign));
                string      boundary = "------------------------------7dXiaoXiao";
                byte[]      bodybyte = getBody(curParmList, boundary);
                HttpContent content  = new ByteArrayContent(bodybyte, 0, bodybyte.Length);
                content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data;boundary=" + boundary);
                //string httpcode = WebLib.Sys.BytesToStr(bodybyte);
                resultTask = client.PostAsync(url, content);
                resultTask.Wait();
                result.statuscode = (int)resultTask.Result.StatusCode;
                if (result.statuscode == 404)
                {
                    result.code      = -100;
                    result.msg       = "您正在查找的资源不可用!";
                    result.resString = "您正在查找的资源不可用!";
                    return(result);
                }
                try
                {
                    result.responseContentType = resultTask.Result.Content.Headers.ContentType.MediaType.ToLower();
                }
                catch
                {
                    result.responseContentType = "applicaiton/octet-stream";
                }
                if (result.responseContentType == "application/json" || result.responseContentType == "text/html")
                {
                    Task <string> strTask = resultTask.Result.Content.ReadAsStringAsync();
                    strTask.Wait();
                    result.resString = strTask.Result;
                    result.total     = 0;
                    if (result.statuscode == 200)
                    {
                        try
                        {
                            result.repObject = JObject.Parse(result.resString);
                            result.code      = result.repObject["code"].Value <int>();
                            result.msg       = result.repObject["msg"] != null ? result.repObject["msg"].Value <string>() : "";
                            result.total     = result.repObject["total"] != null ? result.repObject["total"].Value <long>() : 0L;
                        }
                        catch// (Exception ex)
                        {
                            result.code = -100;
                            result.msg  = "返回json解析出错,源json请查看result.resString.";
                        }
                    }
                    else
                    {
                        result.code = -100;
                        result.msg  = "请求出错,请查看result.statuscode";
                    }
                    return(result);
                }
                else
                {
                    //文件流返回,
                    //result.code = -100;
                    //result.msg = "此外为文件下载,如需要此功能,请编写。如非文件下载,请检查 result.responseContentType ";
                    //   return result;
                    #region
                    result.code = 1;
                    Task <Stream> streamTask = resultTask.Result.Content.ReadAsStreamAsync();
                    streamTask.Wait();
                    result.responseStream      = streamTask.Result;
                    result.responseContentType = resultTask.Result.Content.Headers.ContentType.MediaType;
                    if (result.responseStream == null)
                    {
                        result.code       = -100;
                        result.statuscode = -1;
                        result.msg        = "下载文件时发生错误!";
                        return(result);
                    }
                    else
                    {
                        if (resultTask.Result.Content.Headers.ContentDisposition.FileName == null)
                        {
                            result.resString = resultTask.Result.Content.Headers.ContentDisposition.FileNameStar;
                        }
                        else
                        {
                            result.resString = resultTask.Result.Content.Headers.ContentDisposition.FileName;
                        }
                        return(result);
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                result.code = -100;
                if (ex.InnerException != null)
                {
                    if (ex.InnerException is System.Net.Http.HttpRequestException)
                    {
                        result.msg = "连接服务器[" + url + "]时发生错误!";
                    }
                    else
                    {
                        result.msg = ex.InnerException.Message;
                    }
                }
                else
                {
                    result.msg = ex.Message;
                }
                return(result);
            }
            finally
            {
                // File.AppendAllText("D:\\crm.invoke.api.txt", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + url + "   ==>end\r\n");
                client.Dispose();
            }
        }
Пример #49
0
        public async Task <UserModel> AddAsync(UserModel item)
        {
            try
            {
                if (App.HasNetwork)
                {
                    using (HttpClient client = new HttpClient {
                        BaseAddress = new Uri(App.ApiAddress)
                    })
                    {
                        HttpResponseMessage response;
                        if (string.IsNullOrEmpty(item.Id))
                        {
                            response = await client.PostAsync
                                       (
                                $"Account",
                                new StringContent
                                (
                                    JsonConvert.SerializeObject
                                    (
                                        new RegisterCommand
                                        (
                                            item.Email,
                                            item.RegistrationNumber,
                                            item.Password,
                                            item.Name,
                                            item.PhoneCountryCode,
                                            item.PhoneNumber,
                                            true,
                                            RoleOptions.Other,
                                            false
                                        )
                                    ),
                                    Encoding.UTF8,
                                    "application/json"
                                )
                                       );
                        }
                        else
                        {
                            var oldUser = await GetAsync(item.Id);

                            if (oldUser != null)
                            {
                                response = await client.PutAsync
                                           (
                                    $"Account/{item.Id}",
                                    new StringContent
                                    (
                                        JsonConvert.SerializeObject
                                        (
                                            new RegisterCommand
                                            (
                                                item.Email,
                                                item.RegistrationNumber,
                                                item.Password,
                                                item.Name,
                                                item.PhoneCountryCode,
                                                item.PhoneNumber,
                                                !oldUser.Email.Equals(item.Email, StringComparison.OrdinalIgnoreCase),
                                                oldUser.Role,
                                                oldUser.Status
                                            )
                                        ),
                                        Encoding.UTF8,
                                        "application/json"
                                    )
                                           );
                            }
                            else
                            {
                                throw new HttpRequestException($"User {item.Email} not found !");
                            }
                        }
                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();

                            var user = JsonConvert.DeserializeObject <UserDto>(json);
                            return(new UserModel
                                   (
                                       user.UserId,
                                       user.Email,
                                       user.RegistrationNumber,
                                       user.PhoneCountryCode,
                                       user.PhoneNumber,
                                       user.FullName,
                                       user.CreatedAt,
                                       new ObservableCollection <InteractionModel>
                                       (
                                           user.ProductInteractions?.Select
                                           (
                                               x =>
                                               new InteractionModel
                                               (
                                                   x.UserId,
                                                   x.ProductId,
                                                   x.InteractionType,
                                                   x.Count,
                                                   x.Content,
                                                   x.CreatedAt
                                               )
                                           ).ToList() ?? new List <InteractionModel>()
                                       ),
                                       user.Token,
                                       user.TokenExpiresIn,
                                       user.IsEmailVerified,
                                       user.Role,
                                       user.Status
                                   ));
                        }
                        else
                        {
                            throw new HttpRequestException(await response.Content.ReadAsStringAsync());
                        }
                    }
                }
                else
                {
                    throw new HttpRequestException("No internet connection !");
                }
            }
            catch (HttpRequestException ex)
            {
                throw ex;
            }
            catch (TaskCanceledException)
            {
                throw new HttpRequestException("Cannot join the server!");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #50
0
        public StatsService(DiscordSocketClient client, CommandHandler cmdHandler,
                            IBotCredentials creds, EvilMortyBot evilMorty,
                            IDataCache cache)
        {
            _log    = LogManager.GetCurrentClassLogger();
            _client = client;
            _creds  = creds;
            _redis  = cache.Redis;

            _started = DateTime.UtcNow;
            _client.MessageReceived    += _ => Task.FromResult(Interlocked.Increment(ref _messageCounter));
            cmdHandler.CommandExecuted += (_, e) => Task.FromResult(Interlocked.Increment(ref _commandsRan));

            _client.ChannelCreated += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Increment(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Increment(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.ChannelDestroyed += (c) =>
            {
                var _ = Task.Run(() =>
                {
                    if (c is ITextChannel)
                    {
                        Interlocked.Decrement(ref _textChannels);
                    }
                    else if (c is IVoiceChannel)
                    {
                        Interlocked.Decrement(ref _voiceChannels);
                    }
                });

                return(Task.CompletedTask);
            };

            _client.GuildAvailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.JoinedGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, tc);
                    Interlocked.Add(ref _voiceChannels, vc);
                });
                return(Task.CompletedTask);
            };

            _client.GuildUnavailable += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            _client.LeftGuild += (g) =>
            {
                var _ = Task.Run(() =>
                {
                    var tc = g.Channels.Count(cx => cx is ITextChannel);
                    var vc = g.Channels.Count - tc;
                    Interlocked.Add(ref _textChannels, -tc);
                    Interlocked.Add(ref _voiceChannels, -vc);
                });

                return(Task.CompletedTask);
            };

            if (_client.ShardId == 0)
            {
                _carbonitexTimer = new Timer(async(state) =>
                {
                    if (string.IsNullOrWhiteSpace(_creds.CarbonKey))
                    {
                        return;
                    }
                    try
                    {
                        using (var http = new HttpClient())
                        {
                            using (var content = new FormUrlEncodedContent(
                                       new Dictionary <string, string> {
                                { "servercount", evilMorty.GuildCount.ToString() },
                                { "key", _creds.CarbonKey }
                            }))
                            {
                                content.Headers.Clear();
                                content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                                await http.PostAsync("https://www.carbonitex.net/discord/data/botdata.php", content).ConfigureAwait(false);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
            }

            _botlistTimer = new Timer(async(state) =>
            {
                if (string.IsNullOrWhiteSpace(_creds.BotListToken))
                {
                    return;
                }
                try
                {
                    using (var http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "shard_count", _creds.TotalShards.ToString() },
                            { "shard_id", client.ShardId.ToString() },
                            { "server_count", client.Guilds.Count().ToString() }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            http.DefaultRequestHeaders.Add("Authorization", _creds.BotListToken);

                            await http.PostAsync($"https://discordbots.org/api/bots/{client.CurrentUser.Id}/stats", content).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                    // ignored
                }
            }, null, TimeSpan.FromMinutes(5), TimeSpan.FromHours(1));

            var platform = "other";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                platform = "linux";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                platform = "osx";
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                platform = "windows";
            }

            _dataTimer = new Timer(async(state) =>
            {
                try
                {
                    using (var http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(
                                   new Dictionary <string, string> {
                            { "id", string.Concat(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(_creds.ClientId.ToString())).Select(x => x.ToString("X2"))) },
                            { "guildCount", evilMorty.GuildCount.ToString() },
                            { "version", BotVersion },
                            { "platform", platform }
                        }))
                        {
                            content.Headers.Clear();
                            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                            await http.PostAsync("https://selfstats.evilMortybot.me/", content).ConfigureAwait(false);
                        }
                    }
                }
                catch
                {
                    // ignored
                }
            }, null, TimeSpan.FromSeconds(1), TimeSpan.FromHours(1));
        }
Пример #51
0
        /// <summary>
        /// Gets the analysis of the specified image file by using
        /// the Computer Vision REST API.
        /// </summary>
        /// <param name="byteData">A byte array of the image file to analyze.</param>
        async Task <String> MakeComputerVisionRequest(byte[] byteData)
        {
            try
            {
                HttpClient client = new HttpClient();

                // Request headers.
                client.DefaultRequestHeaders.Add(
                    "Ocp-Apim-Subscription-Key", localSettings.Values["ComputerVisionSubKey"].ToString());

                // Request parameters. A third optional parameter is "details".
                // The Analyze Image method returns information about the following
                // visual features:
                // Categories:  categorizes image content according to a
                //              taxonomy defined in documentation.
                // Description: describes the image content with a complete
                //              sentence in supported languages.
                // Color:       determines the accent color, dominant color,
                //              and whether an image is black & white.
                string requestParameters =
                    "visualFeatures=Categories,Description,Color";

                //Get Computer Vision URI from settings
                string tempUri = localSettings.Values["ComputerVisionEndpointUrl"].ToString();
                //remote trailing "/" if present
                tempUri = tempUri.EndsWith("/") ? tempUri.Substring(0, tempUri.Length - 1) : tempUri;
                //Add request parameters
                string uri = tempUri + "?" + requestParameters;

                HttpResponseMessage response;

                // Read the contents of the specified local image
                // into a byte array.
                //byte[] byteData = GetImageAsByteArray(imageFilePath);

                // Add the byte array as an octet stream to the request body.
                using (ByteArrayContent content = new ByteArrayContent(byteData))
                {
                    // This example uses the "application/octet-stream" content type.
                    // The other content types you can use are "application/json"
                    // and "multipart/form-data".
                    content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");

                    // Asynchronously call the REST API method.
                    response = await client.PostAsync(uri, content);
                }

                // Asynchronously get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                // Display the JSON response.
                //Debug.WriteLine("\nResponse:\n\n{0}\n", JToken.Parse(contentString).ToString());
                //Now extract just the description generated by Computer Vision Service using JSON.Net
                try
                {
                    JObject jObject = JObject.Parse(contentString);
                    //Get the first Caption that is proviced using JPath
                    JToken value = jObject.SelectToken("$.description.captions[0]['text']");
                    Debug.WriteLine(value.ToString());
                    return(value.ToString());
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    return("");
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("\n" + e.Message);
                return("");
            }
        }
Пример #52
0
        static void Main(string[] args)
        {
            // Populate with the appropriate values for your environment
            string clientId       = "{your client ID here}";
            string clientSecret   = "{your client secret here}";
            string tenantId       = "{your tenant ID here}";
            string subscriptionId = "{your subscription ID here}";
            string resourceId     = "/subscriptions/{your subscription ID here}/resourceGroups/{your resource group name here}/providers/Microsoft.Compute/virtualMachines/{your VM name here}";
            string accessToken    = string.Empty;

            // Authenticate
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri($"https://login.microsoftonline.com");
            List <KeyValuePair <string, string> > postBody = new List <KeyValuePair <string, string> >();

            postBody.Add(new KeyValuePair <string, string>("grant_type", "client_credentials"));
            postBody.Add(new KeyValuePair <string, string>("client_id", clientId));
            postBody.Add(new KeyValuePair <string, string>("client_secret", clientSecret));
            postBody.Add(new KeyValuePair <string, string>("resource", "https://management.core.windows.net/"));

            FormUrlEncodedContent content  = new FormUrlEncodedContent(postBody);
            HttpResponseMessage   response = client.PostAsync($"/{tenantId}/oauth2/token", content).Result;

            if (response.IsSuccessStatusCode)
            {
                Stream responseStream = response.Content.ReadAsStreamAsync().Result;
                using (StreamReader streamReader = new StreamReader(responseStream))
                {
                    string  responseContent = streamReader.ReadToEnd();
                    JObject responseObject  = JObject.Parse(responseContent);
                    accessToken = responseObject["access_token"].Value <string>();
                }

                if (!string.IsNullOrEmpty(accessToken))
                {
                    // Query activity for the last 7 days - adjust the timeframe as needed
                    HttpClient httpClient = new HttpClient();
                    httpClient.BaseAddress = new Uri("https://management.azure.com/");
                    DateTime endDateTime         = DateTime.UtcNow;
                    DateTime startDateTime       = endDateTime.AddDays(-7);
                    string   startDateTimeString = startDateTime.ToString("yyyy-MM-ddTHH:mm:ss.sssZ");
                    string   endDateTimeString   = endDateTime.ToString("yyyy-MM-ddTHH:mm:ss.sssZ");
                    string   filter     = $"eventTimestamp ge '{startDateTimeString}' and eventTimestamp le '{endDateTimeString}' and resourceUri eq '{resourceId}'";
                    string   requestUri = $"/subscriptions/{subscriptionId}/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&$filter={filter}";
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage logResponse = httpClient.GetAsync(requestUri).Result;
                    if (logResponse.IsSuccessStatusCode)
                    {
                        Stream logResponseStream = logResponse.Content.ReadAsStreamAsync().Result;
                        using (StreamReader streamReader = new StreamReader(logResponseStream))
                        {
                            string  logContent = streamReader.ReadToEnd();
                            JObject logEntries = JObject.Parse(logContent);
                            foreach (KeyValuePair <string, JToken> logEntry in logEntries)
                            {
                                foreach (JToken activity in logEntry.Value)
                                {
                                    string operationName = activity["operationName"]["localizedValue"].Value <string>();
                                    string status        = activity["status"]["localizedValue"].Value <string>();

                                    // Extract the successful start and stop virtual machine events
                                    if ((operationName.Contains("Start Virtual Machine") ||
                                         operationName.Contains("Deallocate Virtual Machine")) &&
                                        status == "Succeeded")
                                    {
                                        Console.WriteLine("\tEvent: " + activity["eventName"]["localizedValue"].Value <string>());
                                        Console.WriteLine("\tOperation: " + operationName);
                                        Console.WriteLine("\tCaller: " + activity["caller"].Value <string>());
                                        Console.WriteLine("\tCorrelationId: " + activity["correlationId"].Value <string>());
                                        Console.WriteLine("\tSubscriptionId: " + activity["subscriptionId"].Value <string>());
                                        Console.WriteLine("\tEventTimeStamp: " + activity["eventTimestamp"].Value <string>());
                                        Console.WriteLine("\tStatus: " + status);
                                        Console.WriteLine();
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Management API call Failed!");
                    }
                }
            }
            else
            {
                Console.WriteLine("Authentication Failed!");
            }
        }
Пример #53
0
        public async Task <string> PerformLoginActions(string username, string password)
        {
            try
            {
                bool           success = false;
                HttpStatusCode code;
                string         responseBody = "";
                string         ApiToken;
                using (Httpclient = new HttpClient())
                {
                    Httpclient.DefaultRequestHeaders.Clear();
                    Httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var values = new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("username", username),
                        new KeyValuePair <string, string> ("Password", password)
                    };

                    FormUrlEncodedContent postBody = new FormUrlEncodedContent(values);
                    Task taskDownload = Httpclient.PostAsync((myserviceurl()), postBody)
                                        .ContinueWith(task =>
                    {
                        if (task.Status == TaskStatus.RanToCompletion)
                        {
                            var response = task.Result;

                            if (response.IsSuccessStatusCode)
                            {
                                success          = true;
                                code             = response.StatusCode;
                                responseBody     = response.Content.ReadAsStringAsync().Result;
                                ApiToken         = responseBody;
                                TokenGrant token = JsonConvert.DeserializeObject <TokenGrant>
                                                       (ApiToken.ToString());
                                ApiToken      = token.access_token;
                                DataValues md = TokenDecode.GetInstance()
                                                .Decode(token);
                                md.UserName = username;
                                ApplicationsVariables.Username   = username;
                                ApplicationsVariables.Token      = md.Token;
                                ApplicationsVariables.Datavalues = md;
                            }
                            else
                            {
                                code         = response.StatusCode;
                                responseBody = response.Content.ReadAsStringAsync().Result;
                            }
                        }
                    });
                    taskDownload.Wait();
                }
                if (success)
                {
                    responseBody = "ok";
                }
                return(responseBody);

                //if (success)
                //    return "ok";
                //else if (responseBody.Contains("invalid_grant"))
                //    return responseBody;
                //else if (responseBody.Contains("no_confirmed"))
                //    return responseBody;
                throw new Exception();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Пример #54
0
        public async Task<TestingSystemResponse> CheckSolution(SolutionTestingRequest solutionRequest)
        {
            try
            {
                var solution = _db.Solutions.Find(solutionRequest.SolutionId);

                if (solution != null && solution.File != null)
                {
                    var taskTests = _db.TaskTests.Where(t => t.TaskId == solution.TaskId).ToArray();

                    if (taskTests != null && taskTests.Length > 0)
                    {
                        var isAlive = await CheckIfAlive(_config.CompilerServicesOrchestrator);

                        if (isAlive)
                        {
                            //var dataBytes = await file.GetBytes();                        
                            var codeStyleTask = taskTests.FirstOrDefault(t => t.TestType == "codeStyleTest");

                            var req = new TestRequest
                            {
                                SolutionId = solutionRequest.SolutionId,
                                TestId = codeStyleTask is null ? -1 : codeStyleTask.Id,
                                ReCheck = solutionRequest.ReCheck,
                            };

                            string url = _config.CompilerServicesOrchestrator.GetFullTestLinkFrom(_config.TestingSystemWorker);
                            using var httpClient = new HttpClient();
                            using var form = JsonContent.Create(req);
                            HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            string apiResponse = await response.Content.ReadAsStringAsync();
                            if (response.IsSuccessStatusCode)
                            {
                                TestResponse compResponse = JsonConvert.DeserializeObject<TestResponse>(apiResponse);

                                if (compResponse.OK && compResponse.Result == ResultCode.OK)
                                {
                                    var compResult = _db.CompilationResults.Find(solutionRequest.SolutionId);

                                    if (compResult != null)
                                    {
                                        if (compResult.ResultCode != ResultCode.CE && compResult.File != null)
                                        {
                                            var testTasks = new List<Task<TestResponse>>();
                                            foreach (var test in taskTests)
                                            {
                                                if (_config.Tests.ContainsKey(test.TestType))
                                                {
                                                    testTasks.Add(StartTest(test.TestType, solutionRequest.SolutionId, test.Id, solutionRequest.ReCheck));
                                                }
                                                else
                                                {
                                                    testTasks.Add(Task.Run(() => NoTestFound(test.TestType, solutionRequest.SolutionId, test.Id)));
                                                }
                                            }
                                            await Task.WhenAll(testTasks);

                                            var responses = testTasks.Select(t => t.Result).ToArray();
                                            var results = responses.Join(taskTests, i => i.TestId, o => o.Id, (i, o) => new { Result = i, Definition = o }).ToArray();

                                            double totalScore = 0;
                                            ResultCode totalResult = results.Select(r => r.Result.Result).Max();

                                            foreach (var res in results)
                                            {
                                                if (res.Definition.Block && res.Result.Score == 0)
                                                {
                                                    totalScore = 0;

                                                    break;
                                                }
                                                else
                                                {
                                                    totalScore += res.Result.Score * res.Definition.Weight;
                                                }
                                            }

                                            return WriteToDb(solution, totalResult, totalScore, "success", true, responses);
                                        }
                                        else
                                        {
                                            return WriteToDb(solution, compResult.ResultCode, 0, "compilation error!", true);
                                        }
                                    }
                                    else
                                    {
                                        return WriteToDb(solution, compResponse.Result, 0, "can't find compilation! Inner message: " + compResponse.Message, false);
                                    }
                                }
                                else
                                {
                                    return WriteToDb(solution, compResponse.Result, 0, "something went wrong during compilation! Inner message: " + compResponse.Message, false);
                                }
                            }
                            else
                            {
                                return WriteToDb(solution, ResultCode.IE, 0, "bad response from compilation container: " + response.StatusCode, false);
                            }
                        }
                        else
                        {
                            return WriteToDb(solution, ResultCode.IE, 0, "Compiler Service Is Dead!", false);
                        }
                    }
                    else
                    {
                        return WriteToDb(null, ResultCode.IE, 0, "Can't find task tests!", false);
                    }
                }
                else
                {
                    return WriteToDb(null, ResultCode.IE, 0, "Can't find solution!", false);
                }
            }
            catch
            {
                return new TestingSystemResponse();
            }
        }
Пример #55
0
        private async void recognizeButtonCloud_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.FileTypeFilter.Add(".bmp");
            fileOpenPicker.FileTypeFilter.Add(".png");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
            var inputFile = await fileOpenPicker.PickSingleFileAsync();

            if (inputFile == null)
            {
                // The user cancelled the picking operation
                return;
            }
            TimeSpan duration;

            imageLabelCloud.Text       = "";
            imageLabelCloud.FontSize   = 28;
            imageLabelCloud.Foreground = new SolidColorBrush(Windows.UI.Colors.Black);
            imageLabelCloud.Text       = "Recognizing...";
            DateTime       startTime = DateTime.UtcNow;
            SoftwareBitmap softwareBitmap;


            using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.Read))
            {
                // Create the decoder from the stream
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                // Get the SoftwareBitmap representation of the file
                softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore);
                var source = new SoftwareBitmapSource();
                await source.SetBitmapAsync(softwareBitmap);

                previewImage.Source = source;

                HttpClient          client = new HttpClient();
                HttpResponseMessage response;
                string result;
                client.DefaultRequestHeaders.Add("Prediction-key", APIInfo.predictionKey);
                Uri RequestUri = new Uri(
                    string.Format("https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/{0}/image?iterationId={1}", APIInfo.projectId, APIInfo.iterationId));
                using (HttpStreamContent httpStreamContent = new HttpStreamContent(stream))
                {
                    httpStreamContent.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");
                    try
                    {
                        response = await client.PostAsync(RequestUri, httpStreamContent);

                        result = await response.Content.ReadAsStringAsync();

                        if (response.IsSuccessStatusCode)
                        {
                            CustomVisionResponse customVisionResponse = JsonConvert.DeserializeObject <CustomVisionResponse>(result);
                            string topTagName     = "";
                            float  topProbability = 0;
                            string labelText      = "";
                            foreach (PredictionResult predictionResult in customVisionResponse.Predictions)
                            {
                                if (predictionResult.Probability > topProbability)
                                {
                                    topProbability = predictionResult.Probability;
                                    topTagName     = predictionResult.TagName;
                                }
                            }
                            labelText           += string.Format("{0}\r\n", topTagName);
                            duration             = DateTime.UtcNow - startTime;
                            labelText           += string.Format("\r\n\r\n\r\n\r\n{0:#}ms", duration.TotalMilliseconds);
                            imageLabelCloud.Text = labelText;
                        }
                        else
                        {
                            imageLabelCloud.Text = response.StatusCode.ToString() + "\r\n" + result;
                        }
                    }
                    catch (Exception ex)
                    {
                        imageLabelCloud.FontSize   = 22;
                        imageLabelCloud.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
                        imageLabelCloud.Text       = ex.Message;
                    }
                }
            }
        }
Пример #56
0
        private async void BtnGuardarPr_Clicked(object sender, EventArgs e)
        {
            if (CrossConnectivity.Current.IsConnected)
            {
                if (!string.IsNullOrWhiteSpace(pickedID_TP.ToString()) || (!string.IsNullOrEmpty(pickedID_TP.ToString())))
                {
                    if (!string.IsNullOrWhiteSpace(nombrePEntry.Text) || (!string.IsNullOrEmpty(nombrePEntry.Text)))
                    {
                        if (!string.IsNullOrWhiteSpace(precioventaEntry.Text) || (!string.IsNullOrEmpty(precioventaEntry.Text)))
                        {
                            if (!string.IsNullOrWhiteSpace(stockProductoEntry.Text) || (!string.IsNullOrEmpty(stockProductoEntry.Text)))
                            {
                                if (!string.IsNullOrWhiteSpace(stockValoradoProductoEntry.Text) || (!string.IsNullOrEmpty(stockValoradoProductoEntry.Text)))
                                {
                                    if (!string.IsNullOrWhiteSpace(promedioProductoEntry.Text) || (!string.IsNullOrEmpty(promedioProductoEntry.Text)))
                                    {
                                        if (!string.IsNullOrWhiteSpace(alertaProductoEntry.Text) || (!string.IsNullOrEmpty(alertaProductoEntry.Text)))
                                        {
                                            try
                                            {
                                                Models.Producto producto = new Models.Producto()
                                                {
                                                    nombre_producto  = nombrePEntry.Text,
                                                    id_tipo_producto = pickedID_TP,
                                                    stock            = Convert.ToInt32(stockProductoEntry.Text),
                                                    stock_valorado   = Convert.ToDecimal(stockValoradoProductoEntry.Text),
                                                    promedio         = Convert.ToDecimal(promedioProductoEntry.Text),
                                                    precio_venta     = Convert.ToDecimal(precioventaEntry.Text),
                                                    producto_alerta  = Convert.ToDecimal(alertaProductoEntry.Text)
                                                };

                                                var        json    = JsonConvert.SerializeObject(producto);
                                                var        content = new StringContent(json, Encoding.UTF8, "application/json");
                                                HttpClient client  = new HttpClient();
                                                var        result  = await client.PostAsync("https://dmrbolivia.com/api_distribuidora/productos/agregarProducto.php", content);

                                                if (result.StatusCode == HttpStatusCode.OK)
                                                {
                                                    await DisplayAlert("Guardado", "Se agrego correctamente", "OK");

                                                    await Shell.Current.Navigation.PopAsync();
                                                }
                                                else
                                                {
                                                    await DisplayAlert("Error", "Algo salio mal, intentelo de nuevo", "OK");

                                                    await Shell.Current.Navigation.PopAsync();
                                                }
                                            }
                                            catch (Exception error)
                                            {
                                                await DisplayAlert("Error", "Algo salio mal, intentelo de nuevo", "OK");
                                            }
                                        }
                                        else
                                        {
                                            await DisplayAlert("Campo vacio", "El campo de Alerta esta vacio", "Ok");
                                        }
                                    }
                                    else
                                    {
                                        await DisplayAlert("Campo vacio", "El campo de Promedio esta vacio", "Ok");
                                    }
                                }
                                else
                                {
                                    await DisplayAlert("Campo vacio", "El campo de Stock Valorado esta vacio", "Ok");
                                }
                            }
                            else
                            {
                                await DisplayAlert("Campo vacio", "El campo de Stock esta vacio", "Ok");
                            }
                        }
                        else
                        {
                            await DisplayAlert("Campo vacio", "El campo de Precio de venta esta vacio", "Ok");
                        }
                    }
                    else
                    {
                        await DisplayAlert("Campo vacio", "El campo de Nombre esta vacio", "Ok");
                    }
                }
                else
                {
                    await DisplayAlert("Campo vacio", "El campo de Tipo de producto esta vacio", "Ok");
                }
            }
            else
            {
                await DisplayAlert("Error", "Necesitas estar conectado a internet", "OK");
            }
        }
Пример #57
0
        /// <summary>
        /// Gets the analysis of the specified image file by using
        /// the Computer Vision REST API.
        /// </summary>
        /// <param name="byteData">A byte array of the image file to analyze.</param>
        async Task <ObjectIdentifier> MakeComputerVisionObjectRequest(byte[] byteData)
        {
            try
            {
                HttpClient client = new HttpClient();

                // Request headers.
                client.DefaultRequestHeaders.Add(
                    "Ocp-Apim-Subscription-Key", localSettings.Values["ComputerVisionSubKey"].ToString());

                // Request parameters. A third optional parameter is "details".
                // The Analyze Image method returns information about the following
                // visual features:
                // Categories:  categorizes image content according to a
                //              taxonomy defined in documentation.
                // Description: describes the image content with a complete
                //              sentence in supported languages.
                // Color:       determines the accent color, dominant color,
                //              and whether an image is black & white.
                string requestParameters =
                    "visualFeatures=objects";

                //Get Computer Vision URI from settings
                string tempUri = localSettings.Values["ComputerVisionEndpointUrl"].ToString();
                //remote trailing "/" if present
                tempUri = tempUri.EndsWith("/") ? tempUri.Substring(0, tempUri.Length - 1) : tempUri;
                //Add request parameters
                string uri = tempUri + "?" + requestParameters;

                HttpResponseMessage response;

                // Read the contents of the specified local image
                // into a byte array.
                //byte[] byteData = GetImageAsByteArray(imageFilePath);

                // Add the byte array as an octet stream to the request body.
                using (ByteArrayContent content = new ByteArrayContent(byteData))
                {
                    // This example uses the "application/octet-stream" content type.
                    // The other content types you can use are "application/json"
                    // and "multipart/form-data".
                    content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");

                    // Asynchronously call the REST API method.
                    response = await client.PostAsync(uri, content);
                }

                // Asynchronously get the JSON response.
                string contentString = await response.Content.ReadAsStringAsync();

                Debug.WriteLine(contentString);
                try
                {
                    JObject jObject = JObject.Parse(contentString);

                    //TODO: Delete these lines after testing of new solution
                    //JToken tagName = jObject.SelectToken("$.predictions[0]['tagName']");
                    //JToken probability = jObject.SelectToken("$.predictions[0]['probability']");

                    //Sort the JSON Response by probability descending to get the most accurate prediction
                    IEnumerable <JToken> tokenCollection = jObject.SelectToken("$.objects").OrderByDescending(c => c["confidence"].Value <double>());
                    if (tokenCollection.Count() > 0)
                    {
                        JToken token = tokenCollection.First();
                        //JToken boundingBox = jObject.SelectToken("$.predictions[0]['boundingBox']");
                        JToken tagName     = token.SelectToken("$.object");
                        JToken boundingBox = token.SelectToken("$.rectangle");
                        JToken probability = token.SelectToken("$.confidence");

                        ObjectIdentifier objIdent = new ObjectIdentifier();
                        objIdent.Left   = (double)boundingBox.SelectToken("x");
                        objIdent.Top    = (double)boundingBox.SelectToken("y");
                        objIdent.Width  = (double)boundingBox.SelectToken("w");
                        objIdent.Height = (double)boundingBox.SelectToken("h");
                        objIdent.Tag    = tagName.ToString() + "; " + probability.ToString();
                        return(objIdent);
                    }
                    return(null);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    return(null);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("\n" + e.Message);
                return(null);
            }
        }
Пример #58
-1
 public async Task<DateTime?> DoCheckInOrOutAsync(string userName, string password)
 {
     var regexSuccessCheckIn = new Regex(@"success:\s*true");
     var checkInOrOutUri = new Uri(baseUri, "SaveTimmingEvent");
     var httpClient = new HttpClient();
     var checkinDateTime = await RemoteDatetimeAsync();
     try
     {
         var content = new Windows.Web.Http.HttpFormUrlEncodedContent(BuildHttpFormContentForCheckInOrOut(userName, password));
         var response = await httpClient.PostAsync(checkInOrOutUri, content);
         var responseContent = await response.Content.ReadAsStringAsync();
         var responseJson = FixJson(responseContent);
         var responseType = new { success = false, msg = new { type = 0, msg = "" } };
         var responseObject = JsonConvert.DeserializeAnonymousType(responseJson, responseType);
         if (IsCheckSaved((int)responseObject.msg.type) && responseObject.success)
         {
             return checkinDateTime;
         }
         else
         {
             return null;
         }
     }
     catch { }
     return null;
 }
Пример #59
-1
        public async Task<long> UploadFileAsync( string fileName, Stream fileContent )
        {
            var client = new HttpClient();
            foreach ( var pair in _headers.Current )
            {
                client.DefaultRequestHeaders.Add( pair.Key, pair.Value );
            }

            string downloadUrl = _settings.Configuration.ServerBaseUrl + PluginName;
            var uri = new Uri( downloadUrl, UriKind.Absolute );

            var streamContent = new HttpStreamContent( fileContent.AsInputStream() );
            var content = new HttpMultipartFormDataContent
            {
                { streamContent, FileContentName },
            };
            // It's important to set this here and not before;
            // HttpMultipartFormDataContent overwrites the headers of its contents.
            streamContent.Headers.ContentDisposition.FileName = fileName;
            var response = await client.PostAsync( uri, content );
            if ( response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired )
            {
                throw new AuthenticationRequiredException();
            }
            response.EnsureSuccessStatusCode();
            var responseStream = await response.Content.ReadAsInputStreamAsync();

            var serializer = new DataContractJsonSerializer( typeof( CloudPrintUploadResponse ) );
            var responseObj = (CloudPrintUploadResponse) serializer.ReadObject( responseStream.AsStreamForRead() );
            return responseObj.DocumentId;
        }
Пример #60
-3
        public async Task<bool> SendRemoteCommandForAppAsync(string pressedApp)
        {
            bool succeeded = false;
            string address = String.Empty;

            if (!string.IsNullOrWhiteSpace(pressedApp) && !string.IsNullOrWhiteSpace(_ipAddress))
            {
                
                address = "http://" + _ipAddress + "/Applications/Lifecycle/open?appId=" + pressedApp;

                var uri = new Uri(address, UriKind.Absolute);

                using (HttpClient client = new HttpClient())
                {
                    HttpRequestMessage request = new HttpRequestMessage();

                    request.RequestUri = new Uri(address);

                    IHttpContent httpContent = new HttpStringContent(String.Empty);
                    try
                    {
                        await client.PostAsync(uri, httpContent);
                    }
                    catch (Exception)
                    {
                        return succeeded = false;
                    }

                    return succeeded = true;
                }
            }
            return succeeded = false;
        }