public static async Task <string> GetData(HttpClient httpClient, string link, ResponseType type,
                                                  string section = "Student", string param = "")
        {
            var requestLink = $"{link}/HomeAccess/Content/{section}/{type.ToString()}.aspx{param}";

            try {
                foreach (var(key, value) in Login.HandlerProperties)
                {
                    httpClient.DefaultRequestHeaders.Add(key, value);
                }

                // tries to post a request with the http client
                try {
                    var response = await httpClient.GetStringAsync(requestLink);

                    return(response);
                }
                catch (HttpRequestException e) {
                    SentrySdk.CaptureException(e);
                    return(null);
                }
            }
            catch {
                return(null);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Constructs an authorize url.
        /// </summary>
        public static string BuildAuthorizeUrl(
            string clientId, 
            string redirectUrl, 
            IEnumerable<string> scopes, 
            ResponseType responseType,
            DisplayType display,
            ThemeType theme,
            string locale,
            string state)
        {
            Debug.Assert(!string.IsNullOrEmpty(clientId));
            Debug.Assert(!string.IsNullOrEmpty(redirectUrl));
            Debug.Assert(!string.IsNullOrEmpty(locale));

            IDictionary<string, string> options = new Dictionary<string, string>();
            options[AuthConstants.ClientId] = clientId;
            options[AuthConstants.Callback] = redirectUrl;
            options[AuthConstants.Scope] = BuildScopeString(scopes);
            options[AuthConstants.ResponseType] = responseType.ToString().ToLowerInvariant();
            options[AuthConstants.Display] = display.ToString().ToLowerInvariant();
            options[AuthConstants.Locale] = locale;
            options[AuthConstants.ClientState] = EncodeAppRequestState(state);

            if (theme != ThemeType.None)
            {
                options[AuthConstants.Theme] = theme.ToString().ToLowerInvariant();
            }

            return BuildAuthUrl(AuthEndpointsInfo.AuthorizePath, options);
        }
 public static ResponseStatus createResponse(ResponseType type)
 {
     if (type == ResponseType.SUCCESS)
     {
         return(new ResponseStatus()
         {
             IsSuccess = true,
             Detail = type.ToString(),
         });
     }
     return(new ResponseStatus()
     {
         IsSuccess = false,
         Detail = type.ToString(),
     });
 }
Exemplo n.º 4
0
 public ResponseFormat(ResponseType type, bool isSuccess, dynamic data, string msg)
 {
     Type      = type.ToString();
     IsSuccess = isSuccess;
     Data      = data;
     Message   = msg;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Constructs an authorize url.
        /// </summary>
        public static string BuildAuthorizeUrl(
            string clientId,
            string redirectUrl,
            IEnumerable <string> scopes,
            ResponseType responseType,
            DisplayType display,
            ThemeType theme,
            string locale,
            string state)
        {
            Debug.Assert(!string.IsNullOrEmpty(clientId));
            Debug.Assert(!string.IsNullOrEmpty(redirectUrl));
            Debug.Assert(!string.IsNullOrEmpty(locale));

            IDictionary <string, string> options = new Dictionary <string, string>();

            options[AuthConstants.ClientId]     = clientId;
            options[AuthConstants.Callback]     = redirectUrl;
            options[AuthConstants.Scope]        = BuildScopeString(scopes);
            options[AuthConstants.ResponseType] = responseType.ToString().ToLowerInvariant();
            options[AuthConstants.Display]      = display.ToString().ToLowerInvariant();
            options[AuthConstants.Locale]       = locale;
            options[AuthConstants.ClientState]  = EncodeAppRequestState(state);

            if (theme != ThemeType.None)
            {
                options[AuthConstants.Theme] = theme.ToString().ToLowerInvariant();
            }

            return(BuildAuthUrl(AuthEndpointsInfo.AuthorizePath, options));
        }
Exemplo n.º 6
0
        T Request <T>(HttpMethod method, StringBuilder requestUri, ResponseType responseType) where T : BaseResponse
        {
            AddUriParameter(requestUri, "responseType", responseType.ToString());
            HttpContent content = new StringContent("");

            var client = CreateHttpClient();

            var httpResponse = method == HttpMethod.Get
                ? client.GetAsync(requestUri.ToString()).Result
                : client.PostAsync(requestUri.ToString(), content).Result;
            var    responseContent = httpResponse.Content;
            string responseBody    = responseContent.ReadAsStringAsync().Result;

            if (httpResponse.IsSuccessStatusCode)
            {
                return(GetResponse <T>(responseType, responseBody));
            }
            if (httpResponse.StatusCode == HttpStatusCode.MethodNotAllowed)
            {
                throw new BoletoFacilMethodNotAllowedException(
                          $"A chamada {GetAPIActionName(requestUri)} não suporta o método {method}. " +
                          "Verifique se existe alguma atualização do SDK ou entre em contato com a equipe do Boleto Fácil.");
            }
            ErrorResponse error = GetResponse <ErrorResponse>(responseType, responseBody);

            throw new BoletoFacilRequestException((int)httpResponse.StatusCode, error);
        }
Exemplo n.º 7
0
        private void AddMediaFile(object parameters)
        {
            MessageBox.Show("AddMediaFile");
            MediaFile mediaFile;

            if (parameters is MediaFile)
            {
                mediaFile = (MediaFile)parameters;
            }
            else
            {
                throw new ArgumentException();
            }
            using (HttpClient _httpClient = new HttpClient())
            {
                _httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings.Get("MediaServiceUri"));
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = _httpClient.PostAsJsonAsync("api/db/PostMediaFile", mediaFile).Result;

                var answer = (response.IsSuccessStatusCode)
                ? response.Content.ReadAsStringAsync().Result
                : null;

                answer = response.Content.ReadAsStringAsync().Result;
                ResponseType result = (ResponseType)Convert.ToInt32(answer);

                MessageBox.Show(result.ToString());
            }
        }
        public static async Task <string> GetDataWithBody(HttpClient httpClient, string link, ResponseType type,
                                                          string body, string section = "Student")
        {
            try {
                httpClient.DefaultRequestHeaders.Referrer =
                    new Uri($"{link}/HomeAccess/Content/{section}/{type.ToString()}.aspx");
                httpClient.DefaultRequestHeaders.CacheControl   = CacheControlHeaderValue.Parse("max-age=0");
                httpClient.DefaultRequestHeaders.ExpectContinue = false;
                httpClient.DefaultRequestHeaders.Add("Origin", @$ "{link}/");
                foreach (var(key, value) in Login.HandlerProperties)
                {
                    httpClient.DefaultRequestHeaders.Add(key, value);
                }

                var data = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

                // tries to post a request with the http client
                try {
                    var response = await httpClient.PostAsync(link, data);

                    response.EnsureSuccessStatusCode();

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

                    return(responseBody);
                }
                catch (HttpRequestException e) {
                    SentrySdk.CaptureException(e);
                    return(null);
                }
            }
            catch {
                return(null);
            }
        }
Exemplo n.º 9
0
 public ResponseMessage(ResponseType type, bool isSuccess, dynamic data, string msg, HttpStatusCode statusCode)
 {
     Type       = type.ToString();
     IsSuccess  = isSuccess;
     Data       = data;
     Message    = msg;
     StatusCode = statusCode;
 }
Exemplo n.º 10
0
        public virtual string GetAuthorizeUrl(ResponseType responseType = ResponseType.Code)
        {
            UriBuilder           uriBuilder       = new UriBuilder(this.Option.AuthorizeUrl);
            List <RequestOption> authorizeOptions = new List <RequestOption>()
            {
                new RequestOption()
                {
                    Name = "client_id", Value = this.Option.ClientId
                },
                new RequestOption()
                {
                    Name = "redirect_uri", Value = this.Option.CallbackUrl
                },
                new RequestOption()
                {
                    Name = "response_type", Value = responseType.ToString().ToLower()
                }
            };

            if (!String.IsNullOrEmpty(this.Option.Display))
            {
                authorizeOptions.Add(new RequestOption()
                {
                    Name = "display", Value = this.Option.Display
                });
            }
            if (!String.IsNullOrEmpty(this.Option.State))
            {
                authorizeOptions.Add(new RequestOption()
                {
                    Name = "state", Value = this.Option.State
                });
            }
            if (!String.IsNullOrEmpty(this.Option.Scope))
            {
                authorizeOptions.Add(new RequestOption()
                {
                    Name = "scope", Value = this.Option.Scope
                });
            }

            List <String> keyValuePairs = new List <String>();

            foreach (var item in authorizeOptions)
            {
                if (item.IsBinary)
                {
                    continue;
                }
                var value = String.Format("{0}", item.Value);
                if (!String.IsNullOrEmpty(value))
                {
                    keyValuePairs.Add(String.Format("{0}={1}", Uri.EscapeDataString(item.Name), Uri.EscapeDataString(value)));
                }
            }
            uriBuilder.Query = String.Join("&", keyValuePairs.ToArray());
            return(uriBuilder.Uri.ToString());
        }
Exemplo n.º 11
0
 protected Uri BuildAuthenticateUri(AuthenticationPermissions scope, ResponseType responseType)
 {
     var builder = new HttpUriBuilder(AuthenticationUrl);
     builder.AddQueryStringParameter("client_id", this.ClientId);
     builder.AddQueryStringParameter("response_type", responseType.ToString().ToLower());
     builder.AddQueryStringParameter("scope", scope.GetParameterValue());
     builder.AddQueryStringParameter("redirect_uri", RedirectUri);
     return builder.Build();
 }
Exemplo n.º 12
0
 /// <summary>
 /// Build authentication link.
 /// </summary>
 /// <param name="instagramOAuthUri">The instagram o authentication URI.</param>
 /// <param name="clientId">The client identifier.</param>
 /// <param name="callbackUri">The callback URI.</param>
 /// <param name="scopes">The scopes.</param>
 /// <param name="responseType">Type of the response.</param>
 /// <returns>The authentication uri</returns>
 private static string BuildAuthUri(string instagramOAuthUri, string clientId, string callbackUri, ResponseType responseType, string scopes)
 {
     return(string.Format("{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}", new object[] {
         instagramOAuthUri.ToLower(),
         clientId.ToLower(),
         callbackUri.ToLower(),
         responseType.ToString().ToLower(),
         scopes.ToLower()
     }));
 }
      public string GetRequestUrl(string requestUrl,double latitude,double longitude,ResponseType responseType)
      {
          if (_postArgumentList == null)
              _postArgumentList = new List<KeyValuePair<string, object>>();

          _postArgumentList.Add(new KeyValuePair<string,object>("lat",latitude));
          _postArgumentList.Add(new KeyValuePair<string, object>("long", longitude));
          _postArgumentList.Add(new KeyValuePair<string, object>("output", responseType.ToString().ToLower()));

          return requestUrl;
      }
Exemplo n.º 14
0
            public string ToURL()
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                query["response_type"] = ResponseType.ToString();
                query["client_id"]     = ClientId;
                query["redirect_uri"]  = RedirectUri;
                query["state"]         = State;
                query["scope"]         = string.Join(" ", Scopes);
                query["service_id"]    = ServiceId.ToString();
                query["login_hint"]    = LoginHint;
                return($"{Constants.URL.Browser.Authorize}?{query.ToString()}");
            }
        public string GetRequestUrl(string requestUrl, double latitude, double longitude, ResponseType responseType)
        {
            if (_postArgumentList == null)
            {
                _postArgumentList = new List <KeyValuePair <string, object> >();
            }

            _postArgumentList.Add(new KeyValuePair <string, object>("lat", latitude));
            _postArgumentList.Add(new KeyValuePair <string, object>("long", longitude));
            _postArgumentList.Add(new KeyValuePair <string, object>("output", responseType.ToString().ToLower()));

            return(requestUrl);
        }
Exemplo n.º 16
0
        public string GetAuthorizeUrl(ResponseType response = ResponseType.Code)
        {
            Dictionary<string, object> config = new Dictionary<string, object>()
            {
                {"client_id",ClientID},
                {"redirect_uri",CallbackUrl},
                {"response_type",response.ToString().ToLower()},
            };
            UriBuilder builder = new UriBuilder(AuthorizeUrl);
            builder.Query = Utility.BuildQueryString(config);

            return builder.ToString();
        }
        public string GetWeChatOauthUrl(string requestUrl, string appId, ResponseType responseType, string redirectUrl, 
            string scope = "post_timeline", string state="")
        {
            requestUrl += "oauth";      

            Dictionary<string,object> mergeArgumentDic=new Dictionary<string,object>();
            mergeArgumentDic.Add("appid", appId);
            mergeArgumentDic.Add("response_type", responseType.ToString().ToLower());
            mergeArgumentDic.Add("redirect_uri", redirectUrl);

            mergeArgumentDic.Add("scope", scope);
            mergeArgumentDic.Add("state", state);
            return  base.MergeRequestArgument(requestUrl,mergeArgumentDic);
        }
        public string GetWeChatOauthUrl(string requestUrl, string appId, ResponseType responseType, string redirectUrl,
                                        string scope = "post_timeline", string state = "")
        {
            requestUrl += "oauth";

            Dictionary <string, object> mergeArgumentDic = new Dictionary <string, object>();

            mergeArgumentDic.Add("appid", appId);
            mergeArgumentDic.Add("response_type", responseType.ToString().ToLower());
            mergeArgumentDic.Add("redirect_uri", redirectUrl);

            mergeArgumentDic.Add("scope", scope);
            mergeArgumentDic.Add("state", state);
            return(base.MergeRequestArgument(requestUrl, mergeArgumentDic));
        }
Exemplo n.º 19
0
        /// <summary>
        /// OAuth2的authorize接口
        /// </summary>
        /// <param name="response">返回类型,支持code、token,默认值为code。</param>
        /// <param name="state">用于保持请求和回调的状态,在回调时,会在Query Parameter中回传该参数。 </param>
        /// <param name="display">授权页面的终端类型,取值见下面的说明。
        /// default 默认的授权页面,适用于web浏览器。
        /// mobile 移动终端的授权页面,适用于支持html5的手机。
        /// popup 弹窗类型的授权页,适用于web浏览器小窗口。
        /// wap1.2 wap1.2的授权页面。
        /// wap2.0 wap2.0的授权页面。
        /// js 微博JS-SDK专用授权页面,弹窗类型,返回结果为JSONP回掉函数。
        /// apponweibo 默认的站内应用授权页,授权后不返回access_token,只刷新站内应用父框架。
        /// </param>
        /// <returns></returns>
        public string GetAuthorizeURL(ResponseType response = ResponseType.Code, string state = null, DisplayType display = DisplayType.Default)
        {
            var config = new Dictionary <string, string> {
                { "client_id", this.AppKey },
                { "redirect_uri", this.CallbackUrl },
                { "response_type", response.ToString().ToLower() },
                { "state", state ?? string.Empty },
                { "display", display.ToString().ToLower() },
            };
            var builder = new UriBuilder(AUTHORIZE_URL);

            builder.Query = Utility.BuildQueryString(config);

            return(builder.ToString());
        }
Exemplo n.º 20
0
        protected override List <KeyValuePair <string, string> > ConstructExtraData()
        {
            var retVal = new List <KeyValuePair <string, string> >(2 + choices.Length)
            {
                // Extra data is ResponseType
                { "ResponseType", responseType.ToString() }
            };

            // And the choices
            for (int i = 0; i < choices.Length; i++)
            {
                retVal.Add("C" + i, choices[i]);
            }

            return(retVal);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Ferme la session ouverte dans le menu LoginWindow
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        protected void OnCloseSessionsClicked(object sender, EventArgs e)
        {
            MessageDialog md = new MessageDialog (this, DialogFlags.Modal, MessageType.Question,
                                   ButtonsType.YesNo, "Êtes-vous sûr de vouloir fermer la session");
            ResponseType rt = new ResponseType ();
            rt = (ResponseType)md.Run ();

            if (rt.ToString () == "Yes") {
                md.Destroy ();
                this.Destroy ();
                LoginWindow lw = new LoginWindow ();
                lw.Show ();
            } else {
                md.Destroy ();
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Build authentication link.
        /// </summary>
        /// <param name="instagramOAuthUri">The instagram o authentication URI.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="callbackUri">The callback URI.</param>
        /// <param name="scopes">The scopes.</param>
        /// <param name="responseType">Type of the response.</param>
        /// <param name="state">Optional parameter to "carry through a server-specific state"</param>
        /// <returns>The authentication uri</returns>
        private static string BuildAuthUri(string instagramOAuthUri, string clientId, string callbackUri, ResponseType responseType, string scopes, string state = null)
        {
            var authUri = string.Format("{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}", new object[] {
                instagramOAuthUri.ToLower(),
                clientId.ToLower(),
                callbackUri,
                responseType.ToString().ToLower(),
                scopes.ToLower()
            });

            if (state != null)
            {
                authUri = $"{authUri}&state={state}";
            }

            return(authUri);
        }
Exemplo n.º 23
0
        public static void SetMessageBoxProperties(Controller controller, ResponseType responseType, string messageSummary = default(string), string messageHeader = default(string))
        {
            if (string.IsNullOrEmpty(messageHeader))
            {
                string GenericDataSuccessMessageHeader = string.IsNullOrEmpty(WebHelper.getApplicationSetting("GenericDataSuccessMessageHeader"))
                                                      ? "Data Saved Successfully!"
                                                      : WebHelper.getApplicationSetting("GenericDataSuccessMessageHeader");
                string GenericDataErrorMessageHeader = string.IsNullOrEmpty(WebHelper.getApplicationSetting("GenericDataErrorMessageHeader"))
                                                      ? "Please correct below error first!"
                                                      : WebHelper.getApplicationSetting("GenericDataErrorMessageHeader");
                messageHeader = responseType == ResponseType.Error ? GenericDataErrorMessageHeader : messageHeader;
                messageHeader = responseType == ResponseType.Success ? GenericDataSuccessMessageHeader : messageHeader;
            }

            controller.ViewBag.ShowMessage    = true;
            controller.ViewBag.MessageType    = responseType.ToString();
            controller.ViewBag.MessageHeader  = messageHeader;
            controller.ViewBag.MessageSummary = messageSummary;
        }
Exemplo n.º 24
0
        public virtual string GetAuthorizeUrl(ResponseType responseType = ResponseType.Code)
        {
            UriBuilder uriBuilder = new UriBuilder(this.Option.AuthorizeUrl);
            List<RequestOption> authorizeOptions = new List<RequestOption>() { 
				new RequestOption(){ Name= "client_id", Value= this.Option.ClientId},
				new RequestOption(){ Name="redirect_uri", Value = this.Option.CallbackUrl},
                new RequestOption(){ Name="response_type", Value = responseType.ToString().ToLower()}
			};
            if (!String.IsNullOrEmpty(this.Option.Display)) authorizeOptions.Add(new RequestOption() { Name = "display", Value = this.Option.Display });
            if (!String.IsNullOrEmpty(this.Option.State)) authorizeOptions.Add(new RequestOption() { Name = "state", Value = this.Option.State });
            if (!String.IsNullOrEmpty(this.Option.Scope)) authorizeOptions.Add(new RequestOption() { Name = "scope", Value = this.Option.Scope });

            List<String> keyValuePairs = new List<String>();
            foreach (var item in authorizeOptions)
            {
                if (item.IsBinary) continue;
                var value = String.Format("{0}", item.Value);
                if (!String.IsNullOrEmpty(value)) keyValuePairs.Add(String.Format("{0}={1}", Uri.EscapeDataString(item.Name), Uri.EscapeDataString(value)));
            }
            uriBuilder.Query = String.Join("&", keyValuePairs.ToArray());
            return uriBuilder.Uri.ToString();
        }
Exemplo n.º 25
0
        public static void Remove(string path)
        {
            try
            {
                byte[] data = File.ReadAllBytes(path);

                CertificateManager manager  = new CertificateManager();
                ResponseType       response = manager.RemoveCertificate(data);

                if (response == ResponseType.Success)
                {
                    Console.WriteLine("Removed Certificate: " + Path.GetFullPath(path));
                }
                else
                {
                    Console.WriteLine("Error: " + response.ToString());
                }
            }
            catch
            {
                Console.WriteLine("Error: File doesn't exist at: " + Path.GetFullPath(path));
            }
        }
Exemplo n.º 26
0
        protected override List <KeyValuePair <string, string> > ConstructExtraData()
        {
            var retVal = new List <KeyValuePair <string, string> >(3 + (choices.Length * 2)) // Assume two choices per list to begin with
            {
                // Extra data is ResponseType
                { "ResponseType", responseType.ToString() },

                // And ChoiceFormat
                { "ChoiceFormat", choiceFormat }
            };

            // And the choices
            for (int i = 0; i < choices.Length; i++)
            {
                string section = ((char)('A' + i)).ToString();
                for (int j = 0; j < choices[i].Length; j++)
                {
                    retVal.Add(section, choices[i][j]);
                }
            }

            return(retVal);
        }
Exemplo n.º 27
0
        public void ProofThatCatchingExceptionsIsSlow(ResponseType responseType, int callstackSize)
        {
            var service = new Service();

            var timer = new Stopwatch();

            var codeToExecute = GetCodeToExecute(responseType);

            timer.Start();

            try
            {
                var response = service.SomeServiceCall(codeToExecute, callstackSize);
            }
            catch (Exception)
            {
            }

            timer.Stop();

            output.WriteLine($"handling an {responseType.ToString()} response with a {callstackSize} deep callstack took {timer.Elapsed.Milliseconds}ms");

            Assert.True(timer.Elapsed.Milliseconds < 2);
        }
Exemplo n.º 28
0
 public override string ToString()
 {
     return(Method.ToString().ToUpper() + " " + Url + "." + ResponseType.ToString().ToLower());
 }
Exemplo n.º 29
0
 public override string ToString()
 {
     return($"{ResponseType.ToString()}: {Message}.");
 }
Exemplo n.º 30
0
 public override string ToString()
 {
     return(base.ToString() + ":" + ResponseType.ToString());
 }
Exemplo n.º 31
0
 /// <summary>
 /// Build authentication link.
 /// </summary>
 /// <param name="instagramOAuthUri">The instagram o authentication URI.</param>
 /// <param name="clientId">The client identifier.</param>
 /// <param name="callbackUri">The callback URI.</param>
 /// <param name="scopes">The scopes.</param>
 /// <param name="responseType">Type of the response.</param>
 /// <returns>The authentication uri</returns>
 private static string BuildAuthUri(string instagramOAuthUri, string clientId, string callbackUri, ResponseType responseType, string scopes)
 {
     return string.Format("{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}", new object[] {
         instagramOAuthUri.ToLower(),
         clientId.ToLower(),
         callbackUri,
         responseType.ToString().ToLower(),
         scopes.ToLower()
     });
 }
Exemplo n.º 32
0
        /* COPY OF _request method START  */
        /**
         * Http Get Request
         *
         * @param List<string> request of URL directories.
         * @return List<object> from JSON response.
         */
        private bool _urlRequest(List<string> url_components, ResponseType type, Action<object> usercallback, bool reconnect)
        {
            List<object> result = new List<object>();
            string channelName = getChannelName(url_components, type);

            StringBuilder url = new StringBuilder();

            // Add Origin To The Request
            url.Append(this.ORIGIN);

            // Generate URL with UTF-8 Encoding
            foreach (string url_bit in url_components)
            {
                url.Append("/");
                url.Append(_encodeURIcomponent(url_bit));
            }

            if (type == ResponseType.Presence || type == ResponseType.Subscribe)
            {
                url.Append("?uuid=");
                url.Append(this.sessionUUID);
            }

            if (type == ResponseType.DetailedHistory)
                url.Append(parameters);

            // Temporary fail if string too long
            if (url.Length > this.LIMIT)
            {
                result.Add(0);
                result.Add("Message Too Long.");
                // return result;
            }

            Uri requestUri = new Uri(url.ToString());

            // Force canonical path and query
            string paq = requestUri.PathAndQuery;
            FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
            ulong flags = (ulong)flagsFieldInfo.GetValue(requestUri);
            flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
            flagsFieldInfo.SetValue(requestUri, flags);

            try
            {
                // Create Request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
                request.Timeout = PUBNUB_WEBREQUEST_CALLBACK_INTERVAL_IN_SEC * 1000;
                if ((!_channelSubscription.ContainsKey(channelName) && type == ResponseType.Subscribe)
                    || (!_channelPresence.ContainsKey(channelName) && type == ResponseType.Presence))
                {
                    if (appSwitch.TraceInfo)
                    {
                        Trace.WriteLine(string.Format("DateTime {0}, Due to Unsubscribe, request aborted for channel={1}", DateTime.Now.ToString(), channelName));
                    }
                    request.Abort();
                }

                if (appSwitch.TraceInfo)
                {
                    Trace.WriteLine(string.Format("DateTime {0}, Request={1}", DateTime.Now.ToString(), requestUri.ToString()));
                }

                RequestState pubnubRequestState = new RequestState();
                pubnubRequestState.request = request;
                pubnubRequestState.channel = channelName;

                if (type == ResponseType.Subscribe || type == ResponseType.Presence)
                {
                    _channelRequest.AddOrUpdate(channelName, pubnubRequestState, (key, oldState) => pubnubRequestState);
                }

                // Make request with the following inline Asynchronous callback
                IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback((asynchronousResult) =>
                {
                    try
                    {
                        RequestState asynchRequestState = (RequestState)asynchronousResult.AsyncState;
                        HttpWebRequest aRequest = (HttpWebRequest)asynchRequestState.request;

                        if (aRequest != null)
                        {
                            using (HttpWebResponse aResponse = (HttpWebResponse)aRequest.EndGetResponse(asynchronousResult))
                            {
                                pubnubRequestState.response = aResponse;

                                using (StreamReader streamReader = new StreamReader(aResponse.GetResponseStream()))
                                {
                                    // Deserialize the result
                                    string jsonString = streamReader.ReadToEnd();
                                    streamReader.Close();

                                    heartBeatTimer.Change(
                                        (-1 == PUBNUB_HEARTBEAT_TIMEOUT_CALLBACK_IN_SEC) ? -1 : PUBNUB_HEARTBEAT_TIMEOUT_CALLBACK_IN_SEC * 1000,
                                        (-1 == PUBNUB_HEARTBEAT_TIMEOUT_CALLBACK_IN_SEC) ? -1 : PUBNUB_HEARTBEAT_TIMEOUT_CALLBACK_IN_SEC * 1000);

                                    if (appSwitch.TraceInfo)
                                    {
                                        Trace.WriteLine(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channelName, type.ToString(), jsonString));
                                    }

                                    result = WrapResultBasedOnResponseType(type, jsonString, url_components, reconnect);
                                }
                                aResponse.Close();
                            }
                        }
                        else
                        {
                            if (appSwitch.TraceInfo)
                            {
                                Trace.WriteLine(string.Format("DateTime {0}, Request aborted for channel={1}", DateTime.Now.ToString(), channelName));
                            }
                        }

                        if (result != null && result.Count >= 1 && usercallback != null)
                        {
                            responseToUserCallback(result, type, channelName, usercallback);
                        }

                        switch (type)
                        {
                            case ResponseType.Subscribe:
                                subscribeInternalCallback(result, usercallback);
                                break;
                            case ResponseType.Presence:
                                presenceInternalCallback(result, usercallback);
                                break;
                            default:
                                break;
                        }
                    }
                    catch (WebException webEx)
                    {
                        RequestState state = (RequestState)asynchronousResult.AsyncState;
                        if (state.response != null)
                            state.response.Close();

                        if (appSwitch.TraceError)
                        {
                            Trace.WriteLine(string.Format("DateTime {0}, WebException: {1} for URL: {2}", DateTime.Now.ToString(), webEx.Message, requestUri.ToString()));
                        }
                        if (type == ResponseType.Subscribe)
                        {
                            subscribeExceptionHandler(channelName, usercallback, false);
                        }
                        else if (type == ResponseType.Presence)
                        {
                            presenceExceptionHandler(channelName, usercallback, false);
                        }
                        else if (type == ResponseType.Publish)
                        {
                            publishExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.Here_Now)
                        {
                            hereNowExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.DetailedHistory)
                        {
                            detailedHistoryExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.Time)
                        {
                            timeExceptionHandler(usercallback);
                        }
                    }
                    catch (Exception ex)
                    {
                        RequestState state = (RequestState)asynchronousResult.AsyncState;
                        if (state.response != null)
                            state.response.Close();

                        if (appSwitch.TraceError)
                        {
                            Trace.WriteLine(string.Format("DateTime {0} Exception= {1} for URL: {2}", DateTime.Now.ToString(), ex.ToString(), requestUri.ToString()));
                        }
                        if (type == ResponseType.Subscribe)
                        {
                            subscribeExceptionHandler(channelName, usercallback, false);
                        }
                        else if (type == ResponseType.Presence)
                        {
                            presenceExceptionHandler(channelName, usercallback, false);
                        }
                        else if (type == ResponseType.Publish)
                        {
                            publishExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.Here_Now)
                        {
                            hereNowExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.DetailedHistory)
                        {
                            detailedHistoryExceptionHandler(channelName, usercallback);
                        }
                        else if (type == ResponseType.Time)
                        {
                            timeExceptionHandler(usercallback);
                        }
                    }

                }), pubnubRequestState);

                ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, new WaitOrTimerCallback(OnPubnubWebRequestTimeout), pubnubRequestState, PUBNUB_WEBREQUEST_CALLBACK_INTERVAL_IN_SEC * 1000, true);

                return true;
            }
            catch (System.Exception ex)
            {
                if (appSwitch.TraceError)
                {
                    Trace.WriteLine(string.Format("DateTime {0} Exception={1}", DateTime.Now.ToString(), ex.ToString()));
                }
                return false;
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// OAuth2的authorize接口
        /// </summary>
        /// <param name="response">返回类型,支持code、token,默认值为code。</param>
        /// <param name="state">用于保持请求和回调的状态,在回调时,会在Query Parameter中回传该参数。 </param>
        /// <param name="display">授权页面的终端类型,取值见下面的说明。 
        /// default 默认的授权页面,适用于web浏览器。 
        /// mobile 移动终端的授权页面,适用于支持html5的手机。 
        /// popup 弹窗类型的授权页,适用于web浏览器小窗口。 
        /// wap1.2 wap1.2的授权页面。 
        /// wap2.0 wap2.0的授权页面。 
        /// js 微博JS-SDK专用授权页面,弹窗类型,返回结果为JSONP回掉函数。
        /// apponweibo 默认的站内应用授权页,授权后不返回access_token,只刷新站内应用父框架。 
        /// </param>
        /// <returns></returns>
        public string GetAuthorizeURL(ResponseType response= ResponseType.Code,string state=null, DisplayType display = DisplayType.Default)
        {
            Dictionary<string, string> config = new Dictionary<string, string>()
            {
                {"client_id",AppKey},
                {"redirect_uri",CallbackUrl},
                {"response_type",response.ToString().ToLower()},
                {"state",state??string.Empty},
                {"display",display.ToString().ToLower()},
            };
            UriBuilder builder = new UriBuilder(AUTHORIZE_URL);
            builder.Query = Utility.BuildQueryString(config);

            return builder.ToString();
        }
Exemplo n.º 34
0
        /// <summary>

        /// Creates a new instance of the <see cref="MessageBuilder"/> class

        /// used to build a response message.

        /// </summary>

        /// <param name="messageType">The <see cref="ResponseType"/> of the message</param>

        public MessageBuilder(ResponseType messageType) : this("-" + messageType.ToString(), null, false)

        {
        }
Exemplo n.º 35
0
 /// <summary>
 ///  استفاده نمایید “token” یا “id_token” و برای اپلیکیشن های موبایل از , “code” برای احرازهویت در اپلیکیشن های وب از
 /// </summary>
 public Builder SetResponseType(ResponseType responseType)
 {
     this.responseType = responseType.ToString();
     return(this);
 }
Exemplo n.º 36
0
        public override void Render(System.IO.TextWriter writer)
        {
            if (string.IsNullOrEmpty(Src))
            {
                return;
            }
            string localSrc = Src;

            if (AppendCultureInfo && MyDataContext != null && !string.IsNullOrEmpty(MyDataContext.Culture))
            {
                string[] cparts = MyDataContext.Culture.Split(new char[] { '-' });
                char     splitter;
                if (localSrc.Contains("?"))
                {
                    splitter = '&';
                }
                else
                {
                    splitter = '?';
                }
                if (cparts.Length >= 2)
                {
                    localSrc += String.Concat(splitter, "lang=", cparts[0], "&country=", cparts[1]);
                }
                else
                {
                    localSrc += String.Concat(splitter, "lang=", cparts[0]);
                }
            }

            localSrc = MyDataContext.ResolveVariables(localSrc);

            //look for server-side override
            if (ServerResolvedValue != null || !string.IsNullOrEmpty(ResultKey))
            {
                if (string.IsNullOrEmpty(ServerResolvedValue))
                {
                    ServerResolvedValue = DataContext.VARIABLE_START + DataContext.RESERVED_KEY_FETCHED_MARKUP + "." + ResultKey + DataContext.VARIABLE_END;
                }
                if (ServerResolvedValue.Contains(DataContext.VARIABLE_START) &&
                    ServerResolvedValue.Contains(DataContext.VARIABLE_END))
                {
                    writer.Write(MyDataContext.ResolveVariables(ServerResolvedValue));
                }
                else
                {
                    writer.Write(ServerResolvedValue);
                }
                return;
            }

            if (string.IsNullOrEmpty(Method))
            {
                Method = "GET";
            }

            string targetId = TargetElement;

            if (string.IsNullOrEmpty(targetId))
            {
                if (string.IsNullOrEmpty(ID))
                {
                    ID = GetUniqueID();
                }
                targetId = ID;
            }

            if (GenerateDomElement)
            {
                writer.Write("<div id=\"");
                writer.Write(ID);
                writer.WriteLine("\"></div>");
            }


            string regLine = "MyOpenSpace.ClientRequestProcessor.addRequest('##URL##', '##RESPONSE_TARGET##', '##ID##', crrParams);";

            if (ClientResponseType.Render == ResponseType)
            {
                regLine = regLine.Replace("##URL##", localSrc)
                          .Replace("##RESPONSE_TARGET##", ResponseType.ToString().ToLower())
                          .Replace("##ID##", targetId);
            }
            else
            {
                regLine = regLine.Replace("##URL##", localSrc)
                          .Replace("##RESPONSE_TARGET##", ResponseType.ToString().ToLower())
                          .Replace("##ID##", DataKey);
            }

            writer.Write(GadgetMaster.JS_START_BLOCK_TAGS);
            writer.Write(BuildJsRequestParamsObject("crrParams"));
            writer.WriteLine(regLine);
            writer.WriteLine("delete crrParams;");
            writer.Write(GadgetMaster.JS_END_BLOCK_TAGS);
            //"MyOpenSpace.TemplateProcessor.ClientRenderRequest.addRequest"
        }
Exemplo n.º 37
0
        internal static void CommonExceptionHandler <T> (string message, string channelName, bool requestTimeout,
                                                         Action <PubnubClientError> errorCallback, PubnubErrorFilter.Level errorLevel, ResponseType responseType)
        {
            if (requestTimeout)
            {
                message = "Operation Timeout";
                #if (ENABLE_PUBNUB_LOGGING)
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} response={2}", DateTime.Now.ToString(), responseType.ToString(), message), LoggingMethod.LevelInfo);
                #endif

                PubnubCallbacks.CallErrorCallback <T> (message, null, channelName,
                                                       Helpers.GetTimeOutErrorCode(responseType), PubnubErrorSeverity.Critical, errorCallback, errorLevel);
            }
            else
            {
                #if (ENABLE_PUBNUB_LOGGING)
                LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} response={2}", DateTime.Now.ToString(), responseType.ToString(), message), LoggingMethod.LevelInfo);
                #endif

                PubnubCallbacks.CallErrorCallback <T> (message, null, channelName,
                                                       PubnubErrorCode.None, PubnubErrorSeverity.Critical, errorCallback, errorLevel);
            }
        }
Exemplo n.º 38
0
        public static string GetMsg(this ResponseType responseType)
        {
            string msg;

            switch (responseType)
            {
            case ResponseType.LoginExpiration:
                msg = "登陸已過期,請重新登陸"; break;

            case ResponseType.TokenExpiration:
                msg = "Token已過期,請重新登陸"; break;

            case ResponseType.AccountLocked:
                msg = "帳號已被鎖定"; break;

            case ResponseType.LoginSuccess:
                msg = "登陸成功"; break;

            case ResponseType.ParametersLack:
                msg = "參數不完整"; break;

            case ResponseType.NoPermissions:
                msg = "沒有許可權操作"; break;

            case ResponseType.NoRolePermissions:
                msg = "角色沒有許可權操作"; break;

            case ResponseType.ServerError:
                msg = "伺服器好像出了點問題....."; break;

            case ResponseType.LoginError:
                msg = "使用者名稱或密碼錯誤"; break;

            case ResponseType.SaveSuccess:
                msg = "儲存成功"; break;

            case ResponseType.NoKey:
                msg = "沒有主鍵不能編輯"; break;

            case ResponseType.NoKeyDel:
                msg = "沒有主鍵不能刪除"; break;

            case ResponseType.KeyError:
                msg = "主鍵不正確或沒有傳入主鍵"; break;

            case ResponseType.EidtSuccess:
                msg = "編輯成功"; break;

            case ResponseType.DelSuccess:
                msg = "刪除成功"; break;

            case ResponseType.RegisterSuccess:
                msg = "註冊成功"; break;

            case ResponseType.AuditSuccess:
                msg = "審核成功"; break;

            case ResponseType.ModifyPwdSuccess:
                msg = "密碼修改成功"; break;

            case ResponseType.OperSuccess:
                msg = "操作成功"; break;

            case ResponseType.PINError:
                msg = "驗證碼不正確"; break;

            default: msg = responseType.ToString(); break;
            }
            return(msg);
        }
Exemplo n.º 39
0
        /// <summary>
        /// Build authentication link.
        /// </summary>
        /// <param name="instagramOAuthUri">The instagram o authentication URI.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="callbackUri">The callback URI.</param>
        /// <param name="scopes">The scopes.</param>
        /// <param name="responseType">Type of the response.</param>
        /// <param name="state">Optional parameter to "carry through a server-specific state"</param>
        /// <returns>The authentication uri</returns>
        private static string BuildAuthUri(string instagramOAuthUri, string clientId, string callbackUri, ResponseType responseType, string scopes, string state = null)
        {
            var authUri = string.Format("{0}?client_id={1}&redirect_uri={2}&response_type={3}&scope={4}", new object[] {
                instagramOAuthUri.ToLower(),
                clientId.ToLower(),
                callbackUri,
                responseType.ToString().ToLower(),
                scopes.ToLower()
            });

            if (state != null)
            {
                authUri = $"{authUri}&state={state}";
            }

            return authUri;
        }
Exemplo n.º 40
0
        private string SaveCIFData(string jsonString, int patientID, int userID)
        {
            bool         responseStatus;
            ResponseType ObjResponse = new ResponseType();

            try
            {
                // HTSClientIntake CIform = SerializerUtil.ConverToObject<HTSClientIntake>(jsonString);
                IHTSClientIntake clientIntake;
                clientIntake        = (IHTSClientIntake)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BHTSClientIntake, BusinessProcess.Clinical");
                responseStatus      = clientIntake.SaveClientIntakeFormData(jsonString, patientID, userID);
                ObjResponse.Success = responseStatus.ToString();
            }
            catch (Exception ex)
            {
                CLogger.WriteLog(ELogLevel.ERROR, "GetClientIntakeFormData() exception: " + ex.ToString());
                ResponseType response = new ResponseType()
                {
                    Success = EnumUtil.GetEnumDescription(Success.False)
                };
                responseStatus      = Convert.ToBoolean(SerializerUtil.ConverToJson <ResponseType>(response.ToString()));
                ObjResponse.Success = responseStatus.ToString();
            }
            string result = SerializerUtil.ConverToJson <ResponseType>(ObjResponse);

            return(result);
        }
 /// <summary>
 /// Creates a new instance of the <see cref="MessageBuilder"/> class
 /// used to build a response message.
 /// </summary>
 /// <param name="messageType">The <see cref="ResponseType"/> of the message</param>
 public MessageBuilder(ResponseType messageType)
     : this("-" + messageType.ToString(), null, false)
 {
 }
        private void HandleMultiplexException <T> (object sender, EventArgs ea)
        {
            ExceptionHandlers.MultiplexException -= HandleMultiplexException <T>;
            MultiplexExceptionEventArgs <T> mea = ea as MultiplexExceptionEventArgs <T>;

            UnityEngine.Debug.Log(mea.responseType.Equals(CRequestType));
            UnityEngine.Debug.Log(string.Join(",", mea.channels).Equals(ExceptionChannel));
            UnityEngine.Debug.Log(mea.resumeOnReconnect.Equals(ResumeOnReconnect));

            UnityEngine.Debug.Log(string.Format("HandleMultiplexException LOG: {0} {1} {2} {3} {4} {5} {6} {7} {8} {9}",
                                                mea.responseType.Equals(CRequestType),
                                                string.Join(",", mea.channels).Equals(ExceptionChannel),
                                                mea.resumeOnReconnect.Equals(ResumeOnReconnect), CRequestType.ToString(),
                                                ExceptionChannel, ResumeOnReconnect, mea.responseType,
                                                string.Join(",", mea.channels), mea.resumeOnReconnect, resultPart1
                                                ));
            bool resultPart2 = false;

            if (mea.responseType.Equals(CRequestType) &&
                string.Join(",", mea.channels).Equals(ExceptionChannel) &&
                mea.resumeOnReconnect.Equals(ResumeOnReconnect))
            {
                resultPart2 = true;
            }
            Assert.IsTrue(resultPart1 && resultPart2);
        }