コード例 #1
0
        private void ParseRates(HttpStatusCode statusCode, JArray args)
        {
            var result = new DataModelListQc();

            if (statusCode.Equals(HttpStatusCode.OK))
            {
                try
                {
                    _repository.UpdateQc(_parseResponseQc(args));
                    result.QcUpdatedList = _repository.UpdatedQuotations;
                    result.Status        = EQcResponseStatus.Success;
                }
                catch (ParseException)
                {
                    result.Status = EQcResponseStatus.Error;
                }
            }
            else if (statusCode.Equals(HttpStatusCode.Gone))
            {
                result.Status = EQcResponseStatus.Gone;
            }
            else
            {
                result.Status = EQcResponseStatus.Error;
            }

            OnRecieveModel?.Invoke(result);
        }
コード例 #2
0
        public string SendPushMessage(string RegistrationId, string Message, string AuthString)
        {
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["PushMessageUrl"]);

            Request.Method    = "POST";
            Request.KeepAlive = false;

            //-- Create Query String --//
            NameValueCollection postFieldNameValue = new NameValueCollection();

            postFieldNameValue.Add("registration_id", RegistrationId);
            postFieldNameValue.Add("collapse_key", "fav_Message");
            postFieldNameValue.Add("data.message", Message);
            postFieldNameValue.Add("additional_value", DateTime.Now.Ticks.ToString());

            string postData = GetPostStringFrom(postFieldNameValue);

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);


            Request.ContentType   = "application/x-www-form-urlencoded;charset=UTF-8";
            Request.ContentLength = byteArray.Length;


            // This is to be sent as a header and not as a param .
            Request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + AuthString);



            try
            {
                //-- Create Stream to Write Byte Array --//
                Stream dataStream = Request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;

                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    return("Unauthorized - need new token");
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    return("Response from web service isn't OK");
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = Reader.ReadLine();
                Reader.Close();

                return(responseLine);
            }
            catch
            {
                throw;
            }
        }
コード例 #3
0
        public static Session GetSession(string login, string password, string postDataContentType = "application/x-www-form-urlencoded")
        {
            Session session = new Session();

            try
            {
                string applicationId = ConfigurationManager.AppSettings["QB-ApplicationId"];
                string authKey       = ConfigurationManager.AppSettings["QB-AuthKey"];
                string unixTimestamp = (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds.ToString();
                string nonce         = new Random().Next().ToString();
                string signature     = GenerateSignature(applicationId, authKey, nonce, unixTimestamp, login, password);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.quickblox.com/session.json");
                request.Method      = "POST";
                request.KeepAlive   = false;
                request.ContentType = postDataContentType;
                request.Headers.Add(string.Format("QuickBlox-REST-API-Version: {0}", quickBloxRESTAPIVersion));
                // form data parameters
                NameValueCollection data = HttpUtility.ParseQueryString(String.Empty);
                data.Add("application_id", applicationId);
                data.Add("auth_key", authKey);
                data.Add("timestamp", unixTimestamp);
                data.Add("nonce", nonce);
                data.Add("signature", signature);
                data.Add("user[login]", login);
                data.Add("user[password]", password);

                string postData  = data.ToString();
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                request.ContentLength = byteArray.Length;

                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse    response     = request.GetResponse();
                HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;
                if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
                {
                    // var text = "Unauthorized - need new token";
                }
                else if (!responseCode.Equals(HttpStatusCode.OK))
                {
                    StreamReader reader      = new StreamReader(response.GetResponseStream());
                    var          result      = reader.ReadToEnd();
                    var          rootSession = JsonConvert.DeserializeObject <RootSession>(result);
                    session = rootSession.Session;

                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(session);
        }
コード例 #4
0
    public string SendGCMNotification()
    {
        if (registration_ids.Count == 0)
        {
            return("");
        }

        var serializer = new JavaScriptSerializer();

        var serializedResult = serializer.Serialize(this);

        //  MESSAGE CONTENT
        byte[] byteArray = Encoding.UTF8.GetBytes(serializedResult);

        //  CREATE REQUEST
        string         requestTo = "https://gcm-http.googleapis.com/gcm/send";
        HttpWebRequest Request   = (HttpWebRequest)WebRequest.Create(requestTo);

        Request.Method      = "POST";
        Request.KeepAlive   = false;
        Request.ContentType = "application/json";
        Request.Headers.Add(string.Format("Authorization: key={0}", WebConfigurationManager.AppSettings["apiKey"]));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();


        //  SEND MESSAGE
        try
        {
            WebResponse    Response     = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                //var text = "Unauthorized - need new token";
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                //var text = "Response from web service isn't OK";
            }

            StreamReader Reader       = new StreamReader(Response.GetResponseStream());
            string       responseLine = Reader.ReadToEnd();
            Reader.Close();


            return(responseLine);
        }
        catch (Exception e)
        {
        }
        return("error");
    }
コード例 #5
0
        /* public async Task<string> sendPushNotifcationToFirebase()
         * {
         *   bool sent;
         *   //string senderId = "510346677298";
         *
         *
         *   var sizeOfListRejectedStatusCode = getCountOfOnlyRejectedStatusCodeWithDesc();
         *
         *   var txtTitle = "You have new MSS notification";
         *   var txtBody = "There is " + sizeOfListRejectedStatusCode + " new Rejected Transactions";
         *   object data = null;
         *
         *
         *   var tokens = new string[2];
         *
         *   for (int i=0; i < tokens.Length; i++)
         *   {
         *       tokens[0] = deviceId;
         *       tokens[1] = senderId;
         *   }
         *
         *
         *   //sent = await StatusCodeTransactionsPushNotification.SendPushNotification(deviceId, txtTitle, txtBody, data);
         *
         *   var result = await StatusCodeTransactionsPushNotification.SendPushNotification(deviceId, txtTitle, txtBody, data);
         *
         *   return result;
         * }  */


        /// <summary>
        /// Send a Google Cloud Message. Uses the GCM service and your provided api key.
        /// </summary>
        /// <param name="apiKey">Your Server Key In Your Firebase Parameters</param>
        /// <param name="postData">Data to post via Firebase</param>
        /// <param name="postDataContentType">Content of data in Json</param>
        /// <returns>The response string from the google servers</returns>
        private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

            //
            //  MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //
            //  CREATE REQUEST   //https://android.googleapis.com/gcm/send
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");

            Request.Method      = "POST";
            Request.KeepAlive   = false;
            Request.ContentType = postDataContentType;
            Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            Stream dataStream = Request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //
            //  SEND MESSAGE
            string responseLine = "";

            try
            {
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                    Console.WriteLine(text);
                    responseLine = text;
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                    Console.WriteLine(text);
                    responseLine = text;
                }

                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                responseLine = Reader.ReadToEnd();
                Reader.Close();

                return(responseLine);
            }
            catch (Exception e)
            {
            }
            return("error");
        }
コード例 #6
0
        /// <summary>
        /// Send a Google Cloud Message. Uses the GCM service and your provided api key.
        /// </summary>
        /// <param name="apiKey"></param>
        /// <param name="postData"></param>
        /// <param name="postDataContentType"></param>
        /// <returns>The response string from the google servers</returns>
        private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            // from here:
            // http://stackoverflow.com/questions/11431261/unauthorized-when-calling-google-gcm
            //
            // original:
            // http://www.codeproject.com/Articles/339162/Android-push-notification-implementation-using-ASP

            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);

            //
            //  MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //
            //  CREATE REQUEST
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");

            Request.Method      = "POST";
            Request.KeepAlive   = false;
            Request.ContentType = postDataContentType;
            Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            Stream dataStream = Request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //
            //  SEND MESSAGE
            try
            {
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = Reader.ReadToEnd();
                Reader.Close();

                return(responseLine);
            }
            catch (Exception e)
            {
            }
            return("error");
        }
コード例 #7
0
        public async Task <string> SendGcmNotification(string apiKey, string postData, string postDataContentType = "application/json")
        {
            //
            //  MESSAGE CONTENT
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //
            //  CREATE REQUEST
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(_appSettings.GCMPushNotification);

            Request.Method = "POST";
            //Request.KeepAlive = false;
            Request.ContentType = postDataContentType;
            //Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.Headers["Authorization"] = "key=" + apiKey + "";
            //Request.Headers["Sender"] = "id=411981033294";
            Request.Headers["ContentLength"] = byteArray.Length.ToString();
            //Request.ContentLength = byteArray.Length;

            Stream dataStream = await Request.GetRequestStreamAsync();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Dispose();

            //
            //  SEND MESSAGE
            try
            {
                WebResponse Response = await Request.GetResponseAsync();

                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = await Reader.ReadToEndAsync();

                Reader.Dispose();

                return(responseLine);
            }
            catch (Exception e)
            {
            }
            return("error");
        }
コード例 #8
0
        public bool Send(string data)
        {
            try
            {
                string     URI = "https://android.googleapis.com/gcm/send";
                WebRequest req = WebRequest.Create(URI);

                req.ContentType = "application/json";
                string apiKey = ApiKey;
                req.Headers.Add("Authorization", "key=" + apiKey);
                req.Method = "POST";


                String encryptedData = encryptor.Encrypt(data, "TheDataIsEncrypted");
                data = "{\"meetings\":\"" + encryptedData + "\"}";


                string sendData = "{\"registration_ids\":[\"" + RegistrationId + "\"],\"data\":" + data + "}";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(sendData);
                req.ContentLength = bytes.Length;
                System.IO.Stream os = req.GetRequestStream();
                os.Write(bytes, 0, bytes.Length); //Push it out there
                os.Close();

                System.Net.WebResponse resp = req.GetResponse();
                if (resp == null)
                {
                    return(false);
                }

                HttpStatusCode ResponseCode = ((HttpWebResponse)resp).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    return(false);
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    return(false);
                }

                System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
                string response           = sr.ReadToEnd().Trim();
                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
        }
コード例 #9
0
        /* Call API */
        public static JObject CallAPI(string url, API_Method method, object request)
        {
            string  json = "";
            JObject data = null;

            try
            {
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);


                Request.Method      = method.ToString();
                Request.KeepAlive   = false;
                Request.ContentType = "application/json; charset=UTF-8";
                //Request.Headers.Add(string.Format("Authorization: key={0}",""));

                if (method == API_Method.POST)
                {
                    Byte[] byteArray = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(request));
                    Request.ContentLength = byteArray.Length;
                    Stream dataStream = Request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                }
                /*Kiểm tra kết quả trả về */
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    string description = "Unauthorized - need new token";
                    // FileLog.WriteLogCallAPI(description, url);
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    string description = "Response from web service isn't OK";
                    //FileLog.WriteLogCallAPI(description, url);
                }
                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                json = Reader.ReadToEnd();
                //  FileLog.WriteLogCallAPI(json, url);
                Reader.Close();
                data = JObject.Parse(json);
            }
            catch (Exception ex)
            {
                string description = "Lỗi try catch";
                // FileLog.WriteLogCallAPI(description + ":" + ex.Message, url);
            }
            return(data);
        }
コード例 #10
0
        private MiddleResult GetMiddleResult(HttpResponseMessage httpResponseMessage)
        {
            //将httpResponseMessage转换为MiddleResult
            HttpStatusCode status = httpResponseMessage.StatusCode;

            if (status.Equals(HttpStatusCode.OK) || status.Equals(HttpStatusCode.Created) || status.Equals(HttpStatusCode.Accepted))
            {
                string httpJsonString = httpResponseMessage.Content.ReadAsStringAsync().Result;
                return(MiddleResult.JsonToMiddleResult(httpJsonString));
            }
            else
            {
                throw new FrameException($"{HttpConst}服务调用错误:{httpResponseMessage.Content.ReadAsStringAsync()}");
            }
        }
コード例 #11
0
        public bool SendMyPublicKey(InfoClients infoClients)
        {
            bool result = false;

            FileWriter.WriteOnEvents(EventLevel.Info, "Llamado al servidor para entrega de llave privada.");
            try
            {
                ServerRequest         callPartner = new ServerRequest(parameters.Value.EndpointServer, parameters.Value.RequestKeyPartner, parameters.Value.GetRequest);
                HttpStatusCode        resultCode  = new HttpStatusCode();
                Task <HttpStatusCode> response    = callPartner.RequestPartnerKey(infoClients);
                response.ContinueWith(task => {
                    resultCode = task.Result;
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
                //Check the response values, if isn´t success set false
                if (resultCode.Equals(HttpStatusCode.NotFound))
                {
                    FileWriter.WriteOnEvents(EventLevel.Atention, "Respuesta no satisfactoria. resultCode:" + resultCode);
                    result = false;
                }
                else
                {
                    FileWriter.WriteOnEvents(EventLevel.Info, "Llave enviada de forma satisfactoria. resultCode:" + resultCode);
                    result = true;
                }
            }
            catch (System.Exception ex)
            {
                FileWriter.WriteOnEvents(EventLevel.Exception, "Excepcion en GeneratekeyEncrypts. " + ex.Message);
                result = false;
            }
            return(result);
        }
コード例 #12
0
 public RoadIdNotFoundException(HttpStatusCode Status, string RoadId) : base(RoadId + " Is not a valid road")
 {
     if (Status.Equals(HttpStatusCode.NotFound))
     {
         Console.WriteLine(RoadId + " Is not a valid road");
     }
 }
コード例 #13
0
        public static Tuple <string, string> GetMensagemService(Exception ex, HttpResponseBase response)
        {
            AdicionaBadRequestCustomizado(response);

            string msgExibicao = string.Empty;
            string msgAnalise  = string.Empty;

            bool           erroMapeado       = false;
            HttpStatusCode statusCodeRetorno = new HttpStatusCode();

            try
            {
                statusCodeRetorno = ((ApiException)ex).StatusCode;
                erroMapeado       = true;
            }
            catch (Exception) { }


            if (erroMapeado && statusCodeRetorno.Equals(HttpStatusCode.BadRequest))
            {
                msgExibicao = GetRetornoDeErros(((ApiException)ex));
            }
            else
            {
                msgExibicao = "Erro desconhecido!";
                msgAnalise  = $"Mensagem da Exception; {ex.Message}";
            }

            return(new Tuple <string, string>(msgExibicao, msgAnalise));
        }
コード例 #14
0
        public HttpResponseMessage ResponseBasicJson(HttpStatusCode statusCode, object content)
        {
            if (content == null)
            {
                return(new HttpResponseMessage()
                {
                    StatusCode = statusCode
                });
            }

            if (statusCode.Equals(HttpStatusCode.NoContent))
            {
                return new HttpResponseMessage()
                       {
                           StatusCode = statusCode
                       }
            }
            ;

            var retorno = new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content    = new StringContent(JsonConvert.SerializeObject(content
                                                                           , new JsonSerializerSettings {
                    ContractResolver = new JsonNameToPropertyNameContractResolver()
                })
                                               , System.Text.Encoding.UTF8, "application/json")
            };

            return(retorno);
        }
    }
コード例 #15
0
        static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                var a = e.Result;
            }
            catch (WebException ex)
            {
                using (var response = (HttpWebResponse)ex.Response)
                {
                    if (response == null)
                    {
                        return;
                    }

                    HttpStatusCode status = response.StatusCode;
                    // Whatever
                    if (status.Equals(426))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(!string.IsNullOrWhiteSpace(response.StatusDescription) ? response.StatusDescription : "Hay una actualización disponible. Esta versión no será más soportada en poco tiempo. Diríjase al Store y actualícela."));
                    }
                }
            }
            catch (Exception)
            { }
        }
コード例 #16
0

        
コード例 #17
0
 public void ShouldHave(HttpStatusCode expectedStatusCode)
 {
     if (!_statusCode.Equals(expectedStatusCode))
     {
         HttpStatusCode sc  = (HttpStatusCode)_statusCode;
         string         sc1 = Enum.GetName(typeof(HttpStatusCode), sc);
         Assert.Fail(string.Format(CultureInfo.InvariantCulture, "Wrong status code. Expected {0}, but was {1}",
                                   expectedStatusCode, sc.ToString()));
     }
 }
コード例 #18
0
        /// <summary>
        /// Send Push Message to Device
        /// </summary>
        /// <param name="RegistrationID">RegistrationID or Token</param>
        /// <param name="Message">Message to be sent on device</param>
        /// <param name="AuthString">Authentication string</param>
        public String SendMessage(string RegistrationID, string Message /*, string AuthString*/)
        {
            string apiKey     = "AIzaSyB-F65OMBU7Uz7oFV6c8xCw2hbR5fmcaaw";
            string browserKey = "AIzaSyAUjsENtFuYc7y8JrEhAA3JV0HBJE7rtK0";

            try
            {
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
                Request.Method    = "POST";
                Request.KeepAlive = false;
                string postData  = "{ \"registration_ids\": [ \"" + RegistrationID + "\" ], \"data\": {\"message\": \"" + Message + "\"}}";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                Request.ContentType = "application/json";
                Request.Headers.Add(HttpRequestHeader.Authorization, string.Concat("key=", browserKey));
                //-- Create Stream to Write Byte Array --//
                Stream dataStream = Request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                //-- Post a Message --//
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = Reader.ReadLine();
                Reader.Close();

                return(responseLine);
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(ExceptionUtility.NotificationErrorMessage);
            }
        }
コード例 #19
0
ファイル: TokenManager.cs プロジェクト: cymarce/volta
        private string GetToken(bool ssl)
        {
            string requestUri = (ssl ? "https" : "http") + "://" + _hostName + "/sit-auth/OAuth/token";

            ServicePointManager.ServerCertificateValidationCallback += (RemoteCertificateValidationCallback)((sender, cert, chain, sslPolicyErrors) => true);
            string userName = string.IsNullOrEmpty(_domain) ? _loggedUserName : _domain + "\\" + _loggedUserName;

            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", (object)"clientID", (object)"clientPsw"))));
                Dictionary <string, string> dictionary = new Dictionary <string, string>()
                {
                    {
                        "grant_type",
                        "password"
                    },
                    {
                        "username",
                        userName
                    },
                    {
                        "password",
                        _loggedUserPassword
                    },
                    {
                        "scope",
                        "global"
                    }
                };
                HttpResponseMessage result     = httpClient.PostAsync(requestUri, (HttpContent) new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)dictionary)).Result;
                HttpStatusCode      statusCode = result.StatusCode;
                if (!statusCode.Equals((object)HttpStatusCode.Found))
                {
                    statusCode = result.StatusCode;
                    if (!statusCode.Equals((object)HttpStatusCode.OK))
                    {
                        throw new Exception("TokenNotFound");
                    }
                }
                return(JObject.Parse(result.Content.ReadAsStringAsync().Result).Value <string>("access_token"));
            }
        }
コード例 #20
0
        //This is the interface of the entire library. Every request that is made outside of this class will use this method to communicate.
        protected override async Task <string> HandleRequest(string url, Call call = Call.GET, List <Param> parameters = null, List <Param> headers = null, object content = null, HttpStatusCode statusCode = HttpStatusCode.OK)
        {
            Request request = new Request(ConvertToMethod(call));

            request.UriPath = url;

            // this is done on purpose to handle ObserveDevice from DeviceController
            if (statusCode.Equals(HttpStatusCode.Continue))
            {
                request.MarkObserve();
                request.Respond += (Object sender, ResponseEventArgs e) =>
                {
                    ((Action <Response>)content).Invoke(request.Response);
                };
            }

            if (content != null && !statusCode.Equals(HttpStatusCode.Continue))
            {
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                };

                request.SetPayload(JsonConvert.SerializeObject(content, settings));
            }

            Task <Response> t = new Task <Response>(() =>
            {
                return(_coapClient.Send(request));
            });

            t.Start();

            Response resp = await t;

            if (MapToHttpStatusCode(resp.StatusCode) != (int)statusCode)
            {
                RequestException <Response> .ConvertToException(MapToHttpStatusCode(resp.StatusCode), resp.StatusCode.ToString(), resp.UriQuery, "", resp.ResponseText, resp);
            }

            return(resp.ResponseText);
        }
コード例 #21
0
    private static void SendMessage(string authTokenString, string registrationId, string message)
    {
        //Certeficate was not being accepted for the sercure call
        //ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GoogleMessageUrl);

        request.Method    = PostWebRequest;
        request.KeepAlive = false;
        NameValueCollection postFieldNameValue = new NameValueCollection();

        postFieldNameValue.Add(RegistrationIdParam, registrationId);
        postFieldNameValue.Add(CollapseKeyParam, "0");
        postFieldNameValue.Add(DelayWhileIdleParam, "0");
        postFieldNameValue.Add(DataPayloadParam, message);
        string postData = GetPostStringFrom(postFieldNameValue);

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentType   = "application/x-www-form-urlencoded;charset=UTF-8";
        request.ContentLength = byteArray.Length;
        request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + authTokenString);
        Stream dataStream = request.GetRequestStream();

        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        WebResponse    response     = request.GetResponse();
        HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;

        if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
        {
            Console.WriteLine("Unauthorized - need new token");
        }
        else if (!responseCode.Equals(HttpStatusCode.OK))
        {
            Console.WriteLine("Response from web service not OK :");
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        }
        StreamReader reader       = new StreamReader(response.GetResponseStream());
        string       responseLine = reader.ReadLine();

        reader.Close();
    }
コード例 #22
0
        //****//
        private static string SendGCMNotification(string apiKey, string postData)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            //create request
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");

            Request.Method      = "POST";
            Request.KeepAlive   = false;
            Request.ContentType = "application/json";
            Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
            Request.ContentLength = byteArray.Length;

            Stream dataStream = Request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //send Message
            try
            {
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode Responsecode = ((HttpWebResponse)Response).StatusCode;
                if (Responsecode.Equals(HttpStatusCode.Unauthorized) || Responsecode.Equals(HttpStatusCode.Forbidden))
                {
                    //var text = "unauthorize - need new token";
                }
                else if (!Responsecode.Equals(HttpStatusCode.OK))
                {
                    //var text = "response from web service isn't OK";
                }
                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = Reader.ReadToEnd();
                Reader.Close();

                return(responseLine);
            }
            catch (Exception e)
            {
                return("error");
            }
        }
コード例 #23
0
        /// <summary>
        /// 异步POST请求WEBAPI
        /// </summary>
        /// <param name="PostUrl">接口地址</param>
        /// <param name="ParamData">提交数据(json或参数&连接字符串)</param>
        /// <param name="Ret">返回消息</param>
        /// <param name="ContentType">数据类型,默认为json</param>
        /// <returns>是否成功提交数据</returns>
        public static bool HttpAsyncPost(string PostUrl, string ParamData, out string Ret, string ContentType = "application/json")
        {
            Ret = string.Empty;
            bool Result = true;

            if (DataDic.IsDebug)
            {
                LogHelper.Info("请求的接口url:" + PostUrl);
                LogHelper.Info("提交给接口的参数:" + ParamData);
            }
            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(PostUrl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType));
            StringContent content = new StringContent(ParamData, Encoding.UTF8, ContentType);

            try
            {
                var            result = client.PostAsync(PostUrl, content).Result;
                HttpStatusCode code   = result.StatusCode;
                if (DataDic.IsDebug)
                {
                    LogHelper.Info("HttpStatusCode:" + code.ToString());
                }
                if (code.Equals(HttpStatusCode.OK))
                {
                    Ret = result.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    Result = false;
                    Ret    = result.ReasonPhrase;
                }
                if (DataDic.IsDebug)
                {
                    LogHelper.Info("接口返回内容:" + Ret);
                }
            }
            catch (Exception ex)
            {
                Result = false;
                LogHelper.Error("HttpAsyncPost请求接口出错,出错信息:" + ex.Message + ex.StackTrace + ex.TargetSite + ex.Source + ex.InnerException);
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }
            return(Result);
        }
コード例 #24
0
        public void DeleteUser(string mobileNumber)
        {
            var            client     = new RestClient("https://test2-buyerapi.shophumm.co.nz");
            string         resource   = "api/test/v1/deleteuser?mobile=" + mobileNumber;
            var            request    = new RestRequest(resource);
            var            response   = client.Post(request);
            HttpStatusCode statusCode = response.StatusCode;

            if (statusCode.Equals(500))
            {
                throw new Exception($"Error after calling Delete User.  Status code is {statusCode.ToString()}");
            }
        }
コード例 #25
0
        /// <summary>
        /// When application throw any error, it will set the Context variable to display the error details
        /// Modified by: Maninder Singh Wadhva on 11/18/2014 to address ticket #942 Exception handeling in Gameplan.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs object.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            //// By default Internal server error.
            HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError;

            //// Evaluating current error status code.
            var ex = Server.GetLastError();

            if (ex != null && ex is HttpException)
            {
                var exception = ex as HttpException;
                httpStatusCode = (HttpStatusCode)exception.GetHttpCode();
            }

            //// Skip if current http status code is NotFound.
            if (!httpStatusCode.Equals(HttpStatusCode.NotFound))
            {
                var httpContext       = ((MvcApplication)sender).Context;
                var currentController = " ";
                var currentAction     = " ";
                var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

                if (currentRouteData != null)
                {
                    if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                    {
                        currentController = currentRouteData.Values["controller"].ToString();
                    }

                    if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                    {
                        currentAction = currentRouteData.Values["action"].ToString();
                    }
                }

                var controller = new ErrorController();
                var routeData  = new RouteData();
                var action     = "Error";

                httpContext.ClearError();
                httpContext.Response.Clear();
                httpContext.Response.StatusCode             = (int)httpStatusCode;
                httpContext.Response.TrySkipIisCustomErrors = true;

                routeData.Values["controller"] = "Error";
                routeData.Values["action"]     = action;

                controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
                ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
            }
        }
コード例 #26
0
        public string SendAPIRequestwithBodyNoAuth(string url, string httpMethod, string json, HttpStatusCode expectCode)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method      = httpMethod;
            request.ContentType = "application/json";

            byte[] btBodys = Encoding.UTF8.GetBytes(json);
            request.ContentLength = btBodys.Length;
            request.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            TestLog.WriteLine("-request = {0}", request);
            string responseTemp = string.Empty;

            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
                Assert.AreEqual(expectCode, httpWebResponse.StatusCode);
                if (expectCode.Equals(HttpStatusCode.NoContent))
                {
                    Assert.LessThanOrEqualTo(-1, httpWebResponse.ContentLength);
                }
                else
                {
                    Assert.LessThanOrEqualTo(0, httpWebResponse.ContentLength);
                }
                long resContLen = httpWebResponse.ContentLength;
                TestLog.WriteLine("-resContLen = {0}", resContLen);
                responseTemp = this.GetResponseString(httpWebResponse);
                return(responseTemp);
            }
            catch (Exception e)
            {
                responseTemp = "ERROR";
                e.ToString();
            }

            return(responseTemp);

            /*
             * StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
             * string responseContent = streamReader.ReadToEnd();
             * httpWebResponse.Close();
             * streamReader.Close();
             * request.Abort();
             * httpWebResponse.Close();
             * return responseContent;
             * */
        }
コード例 #27
0
        /// <summary>
        /// Returns true if APIError instances are equal
        /// </summary>
        /// <param name="other">Instance of APIError to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(APIError other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Category == other.Category ||
                     Category != null &&
                     Category.Equals(other.Category)
                     ) &&
                 (
                     Code == other.Code ||
                     Code != null &&
                     Code.Equals(other.Code)
                 ) &&
                 (
                     HttpStatusCode == other.HttpStatusCode ||
                     HttpStatusCode != null &&
                     HttpStatusCode.Equals(other.HttpStatusCode)
                 ) &&
                 (
                     Id == other.Id ||
                     Id != null &&
                     Id.Equals(other.Id)
                 ) &&
                 (
                     Message == other.Message ||
                     Message != null &&
                     Message.Equals(other.Message)
                 ) &&
                 (
                     PropertyName == other.PropertyName ||
                     PropertyName != null &&
                     PropertyName.Equals(other.PropertyName)
                 ) &&
                 (
                     RequestId == other.RequestId ||
                     RequestId != null &&
                     RequestId.Equals(other.RequestId)
                 ));
        }
コード例 #28
0
        public RetornoString realizaRequisicaoComPmt(object obj, string metodo, TipoRequisicao tipoRequisicao)
        {
            RetornoString ret  = new RetornoString();
            string        DATA = JsonConvert.SerializeObject(obj);
            string        URL  = getConfig("urlApiEveris");

            URL = URL + metodo;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Method        = tipoRequisicao.ToString();
            request.ContentType   = "application/json";
            request.Accept        = "application/json";
            request.ContentLength = DATA.Length;

            try
            {
                using (Stream webStream = request.GetRequestStream())
                    using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
                    {
                        requestWriter.Write(DATA);
                    }

                WebResponse webResponse = request.GetResponse();

                var            resp          = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
                HttpStatusCode response_code = ((HttpWebResponse)webResponse).StatusCode;

                if (response_code.Equals(HttpStatusCode.OK))
                {
                    ret.resposta = resp;
                    ret.sucesso  = true;
                    ret.erro     = string.Empty;
                }
                else
                {
                    Exception ex = new Exception("Não foi possível estabelecer uma conexão com o banco de dados.");
                }
                return(ret);
            }
            catch (Exception ex)
            {
                ret.erro     = ex.Message;
                ret.sucesso  = false;
                ret.resposta = ex.Message;
                return(ret);
            }
        }
コード例 #29
0
        public ActionResult ErrorBase(HttpStatusCode pErrorCode = HttpStatusCode.ExpectationFailed, bool pIsPartialView = false)
        {
            if (pErrorCode.Equals(HttpStatusCode.ExpectationFailed))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            string vViewTemplate = string.Format("~/Views/Errors/{0}.cshtml", (int)pErrorCode);

            if (pIsPartialView)
            {
                ViewBag.Layout = null;
                return(PartialView(vViewTemplate));
            }
            else
            {
                ViewBag.Layout = "~/Views/Shared/_ShortLayout.cshtml";
                return(View(vViewTemplate));
            }
        }
コード例 #30
0
ファイル: HttpClient.cs プロジェクト: davidsoloman/S4
        /// <summary>
        /// Make an API request and return the raw data from the response as an
        /// InputStream.
        /// </summary>
        /// <param name="target">the URL to request (relative URLs will resolve against the {@link #getBaseUrl() base URL}).</param>
        /// <param name="method">the request method (GET, POST, DELETE, etc.)</param>
        /// <param name="requestBody">the object that should be serialized to JSON as the request body. If <code>null</code> no request body is sent</param>
        /// <param name="extraHeaders">any additional HTTP headers, specified as an alternating sequence of header names and values</param>
        /// <returns>for a successful response, the response stream, or <code>null</code> for a 201 response</returns>
        public Stream requestForStream(String target, String method,
                                       ServiceRequest requestBody, WebHeaderCollection extraHeaders)
        {
            try
            {
                HttpWebResponse connection =
                    sendRequest(target, method, requestBody, extraHeaders);
                HttpStatusCode responseCode = connection.StatusCode;
                if (responseCode.Equals(HttpStatusCode.NoContent))
                {
                    // successful response with no content
                    return(null);
                }
                else if ((int)responseCode >= 400)
                {
                    readError(connection);
                    return(null); // not reachable, readError always throws exception
                }
                else if ((int)responseCode >= 300)
                {
                    // redirect - all redirects we care about from the S4
                    // APIs are 303. We have to follow them manually to make
                    // authentication work properly.
                    String location = connection.Headers.Get("Location");
                    // consume body
                    Stream stream = connection.GetResponseStream();
                    stream.SetLength(0);

                    stream.Close();
                    // follow the redirect
                    return(requestForStream(location, method, requestBody, extraHeaders));
                }
                else
                {
                    return(connection.GetResponseStream());
                }
            }
            catch (IOException e)
            {
                throw new HttpClientException(e.Message);
            }
        }
コード例 #31
0
        public bool SendCrmRequest(ref string RespBody, ref HttpStatusCode RespStatus)
        {
            logger.Info("CRM4cInterfaceAccessManager::SendCrmRequest() called ");

            bool ret = false;
            bool exitFlag = false;

            int retryDelay = Convert.ToInt32(ServiceConfigurationManager._CRMConnectionDetails["RETRYWAITDURATION"]);
            int retryDelay4CRM = Convert.ToInt32(ServiceConfigurationManager._CRMConnectionDetails["FAILOVERTIME"]);

            while(!exitFlag)
            {
                // retry mechanism (N + 1)
                int retries = Convert.ToInt32(ServiceConfigurationManager._CRMConnectionDetails["RETRYNUMBERS"]) + 1;
                int retryNumCount = 0;

                // to find out message processed CRMs
                switch (CRM4cInterfaceAvailabilityManager.getActiveCRMName.ToUpper())
                {
                    case "P":
                        CRM4cInterfaceAvailabilityManager.IsMsgGoing2Primary = true;
                        break;
                    case "B":
                        CRM4cInterfaceAvailabilityManager.IsMsgGoing2Backup = true;
                        break;
                    default:
                        CRM4cInterfaceAvailabilityManager.IsMsgGoing2Primary = true;
                        break;
                }

                while (retries > 0)
                {

                    TimeSpan reqSendTS = System.DateTime.Now.TimeOfDay;
                    logger.Info(string.Format("Request send to CRM 4c REST Interface at...  {0}", reqSendTS));

                    ret = SendRequest(ref RespBody, ref RespStatus);
                    TimeSpan resRecTS = System.DateTime.Now.TimeOfDay;

                    logger.Info(string.Format("Response received from CRM 4c REST Interface at...  {0}", resRecTS));
                    logger.Info(string.Format("Total Process Time...  {0}  [{1}  -  {2}]", resRecTS.Subtract(reqSendTS), resRecTS, reqSendTS));

                    // If success, jump out of while loop
                    if (ret)
                    {
                        exitFlag = true;
                        break;
                    }

                   // go for retry, If CRM returned error code matchs with service configuration HTTPErrorCodes / time out error occurs
                    if (ServiceConfigurationManager._lst4cRetryErrorCodes.Contains(RespBody) || RespStatus.Equals(HttpStatusCode.RequestTimeout) || ServiceConfigurationManager._lst4cRetryErrorCodes.Contains(Convert.ToInt32(RespStatus).ToString()))
                    {
                          retries--;
                          if (retries>0) // not required for 0
                          {
                              logger.Info(string.Format("Active CRM Name...  {0}  ||  Retry...  {1}", CRM4cInterfaceAvailabilityManager.getActiveCRMFullName, ++retryNumCount));
                              Thread.Sleep(retryDelay);
                              logger.Info(string.Format("Service waited {0} secs. before proceeding next try", retryDelay / 1000));
                          }
                    }
                    else // jumping out of while loop for other scenarios
                    {
                        exitFlag = true;
                        break;
                    }

                }

                // jump out of outer while loop for success or Backup CRM is not available in the service config file
                if (exitFlag || (!CRM4cInterfaceAvailabilityManager.IsBackupCRMExist))
                {
                    break;
                }

                // If both CRMs failed, reset the flags & jump out of outer while loop
                if (CRM4cInterfaceAvailabilityManager.IsMsgGoing2Primary && CRM4cInterfaceAvailabilityManager.IsMsgGoing2Backup)
                {
                    logger.Error("Sending message to both Primary & Backup CRMs failed");
                    CRM4cInterfaceAvailabilityManager.IsMsgGoing2Primary = false;
                    CRM4cInterfaceAvailabilityManager.IsMsgGoing2Backup = false;
                    CRM4cInterfaceAvailabilityManager.IsAllCRMsFailed = true;
                    CRM4cInterfaceAvailabilityManager.ActiveCRMURL = CRM4cInterfaceAvailabilityManager.changeActiveCRM(CRM4cInterfaceAvailabilityManager.getActiveCRMName);
                    break;
                }

                logger.Error(string.Format("{0} tries failed to get response from {1} ", retryNumCount, CRM4cInterfaceAvailabilityManager.ActiveCRMURL));

                CRM4cInterfaceAvailabilityManager.ActiveCRMURL = CRM4cInterfaceAvailabilityManager.changeActiveCRM(CRM4cInterfaceAvailabilityManager.getActiveCRMName);
                logger.Info(string.Format("Switching the CRM to {0} ", CRM4cInterfaceAvailabilityManager.ActiveCRMURL));

                Thread.Sleep(retryDelay4CRM);
                logger.Info(string.Format("Service is waited {0} secs before start processing messages with switched CRM", retryDelay4CRM / 1000));

            }

            logger.Info(string.Format("CRM4cInterfaceAccessManager::SendCrmRequest() returned {0}", ret));
            return ret;
        }