예제 #1
0
        public void DeserialseResponseTest()
        {
            //given
            var response = new FHResponse(HttpStatusCode.OK, "[{ \"name\": \"test\" }, { \"name\": \"erik\" }]");

            //when
            var result = response.GetResponseAs <List <Person> >();

            //then
            Assert.IsNotNull(result);
            Assert.AreEqual(result[0].Name, "test");
        }
        async partial void onAuthCallTouched(UIButton sender)
        {
            string     authPolicy = "TestGooglePolicy";
            FHResponse res        = await FH.Auth(authPolicy);

            if (null == res.Error)
            {
                ShowMessage(res.RawResponse);
            }
            else
            {
                ShowMessage(res.Error.Message);
            }
        }
        async partial void onMbaasCallTouched(UIButton sender)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data.Add("act", "create");
            data.Add("type", COLLECTION_NAME);
            //create the collection first
            FHResponse createRes = await FH.Mbaas("db", data);

            ShowMessage(createRes.RawResponse);

            //read device id
            string deviceId = GetDeviceId();

            //check if it exists
            data = new Dictionary <string, object>();
            data.Add("type", COLLECTION_NAME);
            data.Add("act", "list");
            Dictionary <string, string> deviceIdField = new Dictionary <string, string>();

            deviceIdField.Add("deviceId", deviceId);
            data.Add("eq", deviceIdField);
            FHResponse listRes = await FH.Mbaas("db", data);

            ShowMessage(listRes.RawResponse);

            IDictionary <string, object> listResDic = listRes.GetResponseAsDictionary();

            if (Convert.ToInt16(listResDic["count"]) == 0)
            {
                data = new Dictionary <string, object>();
                data.Add("act", "create");
                data.Add("type", COLLECTION_NAME);
                data.Add("fields", GetDeviceInfo());

                FHResponse dataCreateRes = await FH.Mbaas("db", data);

                ShowMessage(dataCreateRes.RawResponse);
            }
            else
            {
                ShowMessage("Device is already created!");
            }
        }
        async partial void onCloudCallTouched(UIButton sender)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            data.Add("hello", "world");
            string     message = null;
            FHResponse res     = await FH.Cloud("hello", "GET", null, data);

            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                message = (string)res.GetResponseAsDictionary()["msg"];
            }
            else
            {
                message = "Error";
            }

            ShowMessage(message);
        }
예제 #5
0
        /// <summary>
        ///     Send request to the remote uri
        /// </summary>
        /// <param name="uri">The remote uri</param>
        /// <param name="requestMethod">The http request method</param>
        /// <param name="headers">The http reqeust headers</param>
        /// <param name="requestData">The request data</param>
        /// <param name="timeout">Timeout in milliseconds</param>
        /// <returns>Server response</returns>
        public static async Task <FHResponse> SendAsync(Uri uri, string requestMethod,
                                                        IDictionary <string, string> headers, object requestData, TimeSpan timeout)
        {
            var timer = new Stopwatch();

            var logger = ServiceFinder.Resolve <ILogService>();
            var online = await IsOnlineAsync();

            FHResponse fhres;

            if (!online)
            {
                var exception = new FHException("offline", FHException.ErrorCode.NetworkError);
                fhres = new FHResponse(exception);
                return(fhres);
            }
            Contract.Assert(null != uri, "No request uri defined");
            Contract.Assert(null != requestMethod, "No http request method defined");
            var httpClient = FHHttpClientFactory.Get();

            try
            {
                logger.d(LogTag, "Send request to " + uri, null);
                httpClient.DefaultRequestHeaders.Add("User-Agent", "FHSDK/DOTNET");
                httpClient.MaxResponseContentBufferSize = BufferSize;
                httpClient.Timeout = timeout;


                var requestMessage = new HttpRequestMessage(new HttpMethod(requestMethod),
                                                            BuildUri(uri, requestMethod, requestData));
                if (null != headers)
                {
                    foreach (var item in headers)
                    {
                        requestMessage.Headers.Add(item.Key, item.Value);
                    }
                }

                if (requestMethod != null && ("POST".Equals(requestMethod.ToUpper()) || "PUT".Equals(requestMethod.ToUpper())))
                {
                    if (null != requestData)
                    {
                        var requestDataStr = JsonConvert.SerializeObject(requestData);
                        requestMessage.Content = new StringContent(requestDataStr, Encoding.UTF8, "application/json");
                    }
                }

                timer.Start();
                var responseMessage = await httpClient.SendAsync(requestMessage, CancellationToken.None);

                timer.Stop();
                logger.d(LogTag, "Reqeust Time: " + timer.ElapsedMilliseconds + "ms", null);
                var responseStr = await responseMessage.Content.ReadAsStringAsync();

                logger.d(LogTag, "Response string is " + responseStr, null);
                if (responseMessage.IsSuccessStatusCode)
                {
                    fhres = new FHResponse(responseMessage.StatusCode, responseStr);
                }
                else
                {
                    var ex = new FHException("ServerError", FHException.ErrorCode.ServerError);
                    fhres = new FHResponse(responseMessage.StatusCode, responseStr, ex);
                }
            }
            catch (HttpRequestException he)
            {
                logger.e(LogTag, "HttpRequestException", he);
                var fhexception = new FHException("HttpError", FHException.ErrorCode.HttpError, he);
                fhres = new FHResponse(fhexception);
            }
            catch (Exception e)
            {
                logger.e(LogTag, "Exception", e);
                var fhexception = new FHException("UnknownError", FHException.ErrorCode.UnknownError, e);
                fhres = new FHResponse(fhexception);
            }
            httpClient.Dispose();
            return(fhres);
        }
예제 #6
0
        /// <summary>
        /// Execute the authentication request. If the authencation type is OAuth and an OAuthHandler is set, it will be called automatically to redirect users to login.
        /// </summary>
        /// <returns>the authentication details</returns>
		public override async Task<FHResponse> ExecAsync()
		{
			var fhres = await base.ExecAsync();
			if (null == this._oauthClient)
			{
				return fhres;
			}
			else
			{
                if (null != fhres.Error) return fhres;
			    var resData = fhres.GetResponseAsJObject();
			    var status = (string)resData["status"];
			    if ("ok" == status)
			    {
			        JToken oauthurl = null;
			        JToken sessionToken = null;
			        resData.TryGetValue("url", out oauthurl);
			        resData.TryGetValue("sessionToken", out sessionToken);
			        if (null != sessionToken)
			        {
			            var authSession = FHAuthSession.GetInstance;
			            FHAuthSession.SaveSession((string)sessionToken);
			        }
			        if (null == oauthurl)
			        {
			            return fhres;
			        }
			        var oauthLoginResult = await this._oauthClient.Login((string)oauthurl);
			        FHResponse authRes = null;
			        switch (oauthLoginResult.Result)
			        {
			            case OAuthResult.ResultCode.Ok:
			                authRes = new FHResponse(HttpStatusCode.OK, oauthLoginResult.ToString());
			                break;
			            case OAuthResult.ResultCode.Failed:
			                authRes = new FHResponse(null, new FHException("Authentication Failed. Message = " + oauthLoginResult.Error.Message, FHException.ErrorCode.AuthenticationError, oauthLoginResult.Error));
			                break;
			            case OAuthResult.ResultCode.Cancelled:
			                authRes = new FHResponse(null, new FHException("Cancelled", FHException.ErrorCode.Cancelled));
			                break;
			            default:
			                authRes = new FHResponse(null, new FHException("Unknown Error", FHException.ErrorCode.UnknownError, oauthLoginResult.Error));
			                break;
			        }
			        return authRes;
			    }
			    else
			    {
			        var authRes = new FHResponse(HttpStatusCode.BadRequest, fhres.RawResponse, new FHException("Authentication Failed", FHException.ErrorCode.AuthenticationError));
			        return authRes;
			    }
			}
		}
예제 #7
0
        /// <summary>
        /// Execute the authentication request. If the authencation type is OAuth and an OAuthHandler is set, it will be called automatically to redirect users to login.
        /// </summary>
        /// <returns>the authentication details</returns>
		public override async Task<FHResponse> execAsync()
		{
			FHResponse fhres = await base.execAsync();
			if (null == this.oauthClient)
			{
				return fhres;
			}
			else
			{
				if (null == fhres.Error)
				{
					JObject resData = fhres.GetResponseAsJObject();
					string status = (string)resData["status"];
					if ("ok" == status)
					{
						JToken oauthurl = null;
                        JToken sessionToken = null;
						resData.TryGetValue("url", out oauthurl);
                        resData.TryGetValue("sessionToken", out sessionToken);
                        if (null != sessionToken)
                        {
                            FHAuthSession authSession = FHAuthSession.Instance;
                            authSession.SaveSession((string)sessionToken);
                        }
						if (null == oauthurl)
						{
							return fhres;
						}
						else
						{
							OAuthResult oauthLoginResult = await this.oauthClient.Login((string)oauthurl);
							FHResponse authRes = null;
							if (oauthLoginResult.Result == OAuthResult.ResultCode.OK)
							{
								authRes = new FHResponse(HttpStatusCode.OK, oauthLoginResult.ToString());
							}
							else if (oauthLoginResult.Result == OAuthResult.ResultCode.FAILED)
							{
								authRes = new FHResponse(null, new FHException("Authentication Failed. Message = " + oauthLoginResult.Error.Message, FHException.ErrorCode.AuthenticationError, oauthLoginResult.Error));
							}
							else if (oauthLoginResult.Result == OAuthResult.ResultCode.CANCELLED)
							{
								authRes = new FHResponse(null, new FHException("Cancelled", FHException.ErrorCode.Cancelled));
							}
							else
							{
								authRes = new FHResponse(null, new FHException("Unknown Error", FHException.ErrorCode.UnknownError, oauthLoginResult.Error));
							}
							return authRes;
						}
					}
					else
					{
						FHResponse authRes = new FHResponse(HttpStatusCode.BadRequest, fhres.RawResponse, new FHException("Authentication Failed", FHException.ErrorCode.AuthenticationError));
						return authRes;
					}
				}
				else
				{
					return fhres;
				}
			}
		}
예제 #8
0
        /// <summary>
        /// Execute the authentication request. If the authencation type is OAuth and an OAuthHandler is set, it will be called automatically to redirect users to login.
        /// </summary>
        /// <returns>the authentication details</returns>
        public override async Task <FHResponse> ExecAsync()
        {
            var fhres = await base.ExecAsync();

            if (null == this._oauthClient)
            {
                return(fhres);
            }
            else
            {
                if (null != fhres.Error)
                {
                    return(fhres);
                }
                var resData = fhres.GetResponseAsJObject();
                var status  = (string)resData["status"];
                if ("ok" == status)
                {
                    JToken oauthurl     = null;
                    JToken sessionToken = null;
                    resData.TryGetValue("url", out oauthurl);
                    resData.TryGetValue("sessionToken", out sessionToken);
                    if (null != sessionToken)
                    {
                        var authSession = FHAuthSession.GetInstance;
                        FHAuthSession.SaveSession((string)sessionToken);
                    }
                    if (null == oauthurl)
                    {
                        return(fhres);
                    }
                    var oauthLoginResult = await this._oauthClient.Login((string)oauthurl);

                    FHResponse authRes = null;
                    switch (oauthLoginResult.Result)
                    {
                    case OAuthResult.ResultCode.Ok:
                        authRes = new FHResponse(HttpStatusCode.OK, oauthLoginResult.ToString());
                        break;

                    case OAuthResult.ResultCode.Failed:
                        authRes = new FHResponse(null, new FHException("Authentication Failed. Message = " + oauthLoginResult.Error.Message, FHException.ErrorCode.AuthenticationError, oauthLoginResult.Error));
                        break;

                    case OAuthResult.ResultCode.Cancelled:
                        authRes = new FHResponse(null, new FHException("Cancelled", FHException.ErrorCode.Cancelled));
                        break;

                    default:
                        authRes = new FHResponse(null, new FHException("Unknown Error", FHException.ErrorCode.UnknownError, oauthLoginResult.Error));
                        break;
                    }
                    return(authRes);
                }
                else
                {
                    var authRes = new FHResponse(HttpStatusCode.BadRequest, fhres.RawResponse, new FHException("Authentication Failed", FHException.ErrorCode.AuthenticationError));
                    return(authRes);
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Send request to the remote uri
        /// </summary>
        /// <param name="uri">The remote uri</param>
        /// <param name="requestMethod">The http request method</param>
        /// <param name="headers">The http reqeust headers</param>
        /// <param name="requestData">The request data</param>
        /// <param name="timeout">Timeout in milliseconds</param>
        /// <returns>Server response</returns>
		public static async Task<FHResponse> SendAsync(Uri uri, string requestMethod, IDictionary<string, string> headers, object requestData, TimeSpan timeout)
        {
			Stopwatch timer = new Stopwatch ();

			ILogService logger = ServiceFinder.Resolve<ILogService> ();
            bool online = await IsOnlineAsync();
            FHResponse fhres = null;
            if (!online)
            {
                FHException exception = new FHException("offline", FHException.ErrorCode.NetworkError);
                fhres = new FHResponse(exception);
                return fhres;
            }
			Contract.Assert (null != uri, "No request uri defined");
			Contract.Assert (null != requestMethod, "No http request method defined");
			HttpClient httpClient = FHHttpClientFactory.Get ();

            try
            {
				logger.d(LOG_TAG, "Send request to " + uri, null);
				httpClient.DefaultRequestHeaders.Add("User-Agent", "FHSDK/DOTNET");
                httpClient.MaxResponseContentBufferSize = BUFFER_SIZE;
				httpClient.Timeout = timeout;
                

				HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(requestMethod), BuildUri(uri, requestMethod, requestData));
				if(null != headers){
					foreach (var item in headers) {
						requestMessage.Headers.Add(item.Key, item.Value);
					}
				}

				if("POST".Equals(requestMethod.ToUpper()) || "PUT".Equals(requestMethod.ToUpper())){
					if(null != requestData){
						string requestDataStr = JsonConvert.SerializeObject(requestData);
						requestMessage.Content = new StringContent(requestDataStr, Encoding.UTF8, "application/json");
					}
				}

				timer.Start ();
				HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
				timer.Stop();
				logger.d(LOG_TAG, "Reqeust Time: " + timer.ElapsedMilliseconds + "ms", null);
                string responseStr = await responseMessage.Content.ReadAsStringAsync();
				logger.d(LOG_TAG, "Response string is " + responseStr, null);
                if (responseMessage.IsSuccessStatusCode)
                {
                    fhres = new FHResponse(responseMessage.StatusCode, responseStr);
                }
                else
                {
                    FHException ex = new FHException("ServerError", FHException.ErrorCode.ServerError);
                    fhres = new FHResponse(responseMessage.StatusCode, responseStr, ex);
                }
            }
            catch (HttpRequestException he)
            {
				logger.e (LOG_TAG, "HttpRequestException", he);
                FHException fhexception = new FHException("HttpError", FHException.ErrorCode.HttpError, he);
                fhres = new FHResponse(fhexception);
            }
            catch (Exception e)
            {
				logger.e (LOG_TAG, "Exception", e);
                FHException fhexception = new FHException("UnknownError", FHException.ErrorCode.UnknownError, e);
                fhres = new FHResponse(fhexception);
            }
            httpClient.Dispose();
            return fhres;
        }
예제 #10
0
        protected async override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            FH.SetLogLevel((int)LogService.LogLevels.DEBUG);
            //use ModernHttpClient
            FHHttpClientFactory.Get = (() => new HttpClient(new OkHttpNetworkHandler()));

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            await FHClient.Init();

            ShowMessage("App Ready!");

            Button cloudButton = (Button)FindViewById(Resource.Id.button1);
            Button authButton  = (Button)FindViewById(Resource.Id.button2);
            Button mbaasButton = (Button)FindViewById(Resource.Id.button3);

            cloudButton.Click += async(object sender, EventArgs e) => {
                Dictionary <string, object> data = new Dictionary <string, object>();
                data.Add("hello", "world");
                string     message = null;
                FHResponse res     = await FH.Cloud("hello", "GET", null, data);

                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    message = (string)res.GetResponseAsDictionary()["msg"];
                }
                else
                {
                    message = "Error";
                }

                ShowMessage(message);
            };

            authButton.Click += async(object sender, EventArgs e) => {
                string     authPolicy = "TestGooglePolicy";
                FHResponse res        = await FH.Auth(authPolicy);

                ShowMessage(res.RawResponse);
            };

            mbaasButton.Click += async(object sender, EventArgs e) => {
                Dictionary <string, object> data = new Dictionary <string, object>();
                data.Add("act", "create");
                data.Add("type", COLLECTION_NAME);
                //create the collection first
                FHResponse createRes = await FH.Mbaas("db", data);

                ShowMessage(createRes.RawResponse);

                //read device id
                string deviceId = GetDeviceId();

                //check if it exists
                data = new Dictionary <string, object>();
                data.Add("type", COLLECTION_NAME);
                data.Add("act", "list");
                Dictionary <string, string> deviceIdField = new Dictionary <string, string>();
                deviceIdField.Add("deviceId", deviceId);
                data.Add("eq", deviceIdField);
                FHResponse listRes = await FH.Mbaas("db", data);

                ShowMessage(listRes.RawResponse);

                IDictionary <string, object> listResDic = listRes.GetResponseAsDictionary();
                if (Convert.ToInt16(listResDic["count"]) == 0)
                {
                    data = new Dictionary <string, object>();
                    data.Add("act", "create");
                    data.Add("type", COLLECTION_NAME);
                    data.Add("fields", GetDeviceInfo());

                    FHResponse dataCreateRes = await FH.Mbaas("db", data);

                    ShowMessage(dataCreateRes.RawResponse);
                }
                else
                {
                    ShowMessage("Device is already created!");
                }
            };
        }