/// <summary>
        /// Sign a web request using Auth.
        /// </summary>
        /// <param name="method">Http method GET, POST or DELETE</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post in xml or json fromat</param>
        /// <returns>The web server response.</returns>
        protected AuthResponse AuthWebRequest(QueryMethod method, string url, string postData, bool isBinary)
        {
            Uri uri = new Uri(url);

            string nonce     = this.GenerateNonce();
            string timeStamp = this.GenerateTimeStamp();

            string authheader = this.GenerateAuthorizationHeader(uri,
                                                                 method.ToString(),
                                                                 timeStamp,
                                                                 nonce);

            string querystringUri = this.GenerateQueryString(uri,
                                                             method.ToString(),
                                                             timeStamp,
                                                             nonce);

            HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(querystringUri);

            webRequest.Method      = method.ToString();
            webRequest.Credentials = CredentialCache.DefaultCredentials;
            webRequest.Headers.Add("x-app-name", ApiKeys.AppName);
            webRequest.Headers.Add("x-api-version", ApiKeys.ApiVersion);
            webRequest.Headers.Add("Authorization", authheader);

            if (ApiKeys.UseCompression)
            {
                webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
                webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            if (method == QueryMethod.POST || method == QueryMethod.PUT || method == QueryMethod.DELETE)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //Write the data.
                StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                }
            }

            AuthResponse authResponse = WebResponseGet(webRequest, isBinary);

            authResponse.Method = method;

            return(authResponse);
        }
Ejemplo n.º 2
0
 private AuthResponse RunRequest(QueryMethod method, string url, string data)
 {
     AuthRequest authRequest = new AuthRequest(_consumerKey, _consumerSecret, _appName);
     using (authRequest)
     {
         OnRequest(this, new RequestEventArgs(method.ToString(), url, data));
         AuthResponse authResponse = authRequest.AuthWebRequest(method, url, data);
         OnResponse(this, new ResponseEventArgs(authResponse.Status, authResponse.Data));
         return authResponse;
     }
 }
Ejemplo n.º 3
0
        private AuthResponse ExecuteRequest(QueryMethod method, string url, string data)
        {
            string      appName     = this.GetAppName();
            AuthRequest authRequest = new AuthRequest(_consumerKey, _consumerSecret, appName, _useCompression, _apiVersion);

            using (authRequest)
            {
                OnRequest(this, new RequestEventArgs(method.ToString(), url, data));
                AuthResponse authResponse = authRequest.AuthWebRequest(method, url, data);
                OnResponse(this, new ResponseEventArgs(authResponse.Status, authResponse.Data));
                return(authResponse);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Signut a web request using Auth.
        /// </summary>
        /// <param name="method">Http method GET, POST or DELETE</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post in xml or json fromat</param>
        /// <returns>The web server response.</returns>
        public AuthResponse AuthWebRequest(QueryMethod method, string url, string postData)
        {
            string querystring = "";
            string authheader = "";

            Uri uri = new Uri(url);

            string nonce = this.GenerateNonce();
            string timeStamp = this.GenerateTimeStamp();

            authheader = this.GenerateAuthorizationHeader(uri,
                method.ToString(),
                timeStamp,
                nonce);

            querystring = this.GenerateQueryString(uri,
                method.ToString(),
                timeStamp,
                nonce);

            AuthResponse authResponse = WebRequest(method, querystring, postData, authheader);
            return authResponse;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sign a web request using Auth.
        /// </summary>
        /// <param name="method">Http method GET, POST or DELETE</param>
        /// <param name="url">The full url, including the querystring.</param>
        /// <param name="postData">Data to post in xml or json fromat</param>
        /// <returns>The web server response.</returns>
        public AuthResponse AuthWebRequest(QueryMethod method, string url, string postData, bool isBinary)
        {
            string querystring = string.Empty;
            string authheader  = string.Empty;

            Uri uri = new Uri(url);

            string nonce     = this.GenerateNonce();
            string timeStamp = this.GenerateTimeStamp();

            authheader = this.GenerateAuthorizationHeader(uri,
                                                          method.ToString(),
                                                          timeStamp,
                                                          nonce);

            querystring = this.GenerateQueryString(uri,
                                                   method.ToString(),
                                                   timeStamp,
                                                   nonce);

            AuthResponse authResponse = WebRequest(method, querystring, postData, authheader, isBinary);

            return(authResponse);
        }
Ejemplo n.º 6
0
        private AuthResponse WebRequest(QueryMethod method, string url, string postData, string authheader, bool isBinary)
        {
            HttpWebRequest webRequest    = null;
            StreamWriter   requestWriter = null;

            webRequest             = (HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Method      = method.ToString();
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            webRequest.Headers.Add("x-app-name", _appName);
            webRequest.Headers.Add("x-api-version", _apiVersion);
            webRequest.Headers.Add("Authorization", authheader);

            if (_useCompression == true)
            {
                webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
                webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            if (method == QueryMethod.POST || method == QueryMethod.PUT || method == QueryMethod.DELETE)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //Write the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            AuthResponse authResponse = WebResponseGet(webRequest, isBinary);

            authResponse.Method = method;

            webRequest = null;

            return(authResponse);
        }
Ejemplo n.º 7
0
        public void Write(string timeSpan, QueryMethod method)
        {
            if (!File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write);
                fs.Flush();
                fs.Close();
                fs = null;
            }
            StreamWriter writer = new StreamWriter(path, true, System.Text.Encoding.Default);

            writer.WriteLine(timeSpan + "         " + method.ToString());
            writer.Flush();
            writer.Close();
            writer.Dispose();
        }
Ejemplo n.º 8
0
        private AuthResponse WebRequest(QueryMethod method, string url, string postData, string authheader)
        {
            HttpWebRequest webRequest    = null;
            StreamWriter   requestWriter = null;

            webRequest             = (HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Method      = method.ToString();
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            webRequest.Headers.Add("x-api-version", "2.1");
            webRequest.Headers.Add("x-app-name", _appName);

            //Add authorization header
            webRequest.Headers.Add("Authorization", authheader);

            if (method == QueryMethod.POST)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //POST the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            AuthResponse authResponse = WebResponseGet(webRequest);

            authResponse.Method = method;

            webRequest = null;

            return(authResponse);
        }
Ejemplo n.º 9
0
        private WebResponse RunRegularRequest(QueryMethod method, string url, string data)
        {
            WebRequest request = WebRequest.Create(url);

            request.Proxy       = WebRequest.DefaultWebProxy;
            request.ContentType = "application/json";
            request.Method      = method.ToString();

            if (method == QueryMethod.POST)
            {
                using (StreamWriter writter = new StreamWriter(request.GetRequestStream()))
                {
                    writter.Write(data);
                }
            }

            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    using (HttpWebResponse exResponse = (HttpWebResponse)e.Response)
                    {
                        OnError(this, new ResponseErrorEventArgs(null, exResponse.StatusCode, exResponse.StatusDescription));
                    }
                }
                else
                {
                    OnError(this, new ResponseErrorEventArgs(null, HttpStatusCode.BadRequest, e.Message));
                }
            }

            return(response as WebResponse);
        }
Ejemplo n.º 10
0
        private AuthResponse WebRequest(QueryMethod method, string url, string postData, string authheader)
        {
            HttpWebRequest webRequest = null;
            StreamWriter requestWriter = null;

            webRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Method = method.ToString();
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            webRequest.Headers.Add("x-app-name", _appName);
            webRequest.Headers.Add("x-api-version", "4.0");
            webRequest.Headers.Add("Authorization", authheader);

            if (_useCompression == true)
            {
                webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
                webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            }

            if (method == QueryMethod.POST || method == QueryMethod.PUT || method == QueryMethod.DELETE)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //Write the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            AuthResponse authResponse = WebResponseGet(webRequest);
            authResponse.Method = method;

            webRequest = null;

            return authResponse;
        }
Ejemplo n.º 11
0
 void System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
 {
     writer.WriteAttributeString("xmlns", "i", null, Namespaces.SchemaInstance);
     writer.WriteAttributeString("xmlns", "q", null, Namespaces.Query);
     writer.WriteAttributeString("Id", _id.ToString());
     writer.WriteAttributeString("Method", _method.ToString());
     writer.WriteAttributeString("StoredProcedureProvider", _storedProcedureProvider ?? "");
     writer.WriteAttributeString("IsSelectDistinct", IsSelectDistinct.ToString());
     writer.WriteAttributeString("IgnoreRegisterUserInfo", IgnoreRegisterUserInfo.ToString());
     writer.WriteAttributeString("IsolationLevel", IsolationLevel.ToString());
     writer.WriteAttributeString("CommandTimeout", CommandTimeout.ToString());
     writer.WriteAttributeString("ProviderName", ProviderName.ToString());
     writer.WriteAttributeString("IgnoreTypeSchema", IgnoreTypeSchema.ToString());
     WriteItem <Projection>(writer, "Projection", _projection);
     WriteItem <QueryExecutePredicate>(writer, "ExecutePredicate", _executePredicate);
     writer.WriteStartElement("Entities", Namespaces.Query);
     if (_entities != null)
     {
         foreach (System.Xml.Serialization.IXmlSerializable i in _entities)
         {
             writer.WriteStartElement("EntityInfo", Namespaces.Query);
             i.WriteXml(writer);
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
     writer.WriteStartElement("Joins", Namespaces.Query);
     if (_joins != null)
     {
         foreach (System.Xml.Serialization.IXmlSerializable i in _joins)
         {
             writer.WriteStartElement("JoinInfo", Namespaces.Query);
             i.WriteXml(writer);
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
     WriteItem <ConditionalContainer>(writer, "Where", _whereClause);
     WriteItem <Sort>(writer, "Sort", _sort);
     WriteItem <GroupBy>(writer, "GroupBy", _groupby);
     WriteItem <ConditionalContainer>(writer, "Having", _having);
     WriteItem <TakeParameters>(writer, "TakeParameters", _takeParameters);
     writer.WriteStartElement("NestedQueries", Namespaces.Query);
     if (_nestedQueries != null)
     {
         foreach (System.Xml.Serialization.IXmlSerializable i in _nestedQueries)
         {
             writer.WriteStartElement("QueryInfo", Namespaces.Query);
             i.WriteXml(writer);
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
     writer.WriteStartElement("Parameters", Namespaces.Query);
     if (_parameters != null)
     {
         foreach (System.Xml.Serialization.IXmlSerializable i in _parameters)
         {
             writer.WriteStartElement("QueryParameter", Namespaces.Query);
             i.WriteXml(writer);
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
     WriteItem <StoredProcedureName>(writer, "StoredProcedureName", _storedProcedureName ?? StoredProcedureName.Empty);
     writer.WriteStartElement("Unions", Namespaces.Query);
     if (_unions != null)
     {
         foreach (System.Xml.Serialization.IXmlSerializable i in _unions)
         {
             writer.WriteStartElement("Union", Namespaces.Query);
             i.WriteXml(writer);
             writer.WriteEndElement();
         }
     }
     writer.WriteEndElement();
 }
Ejemplo n.º 12
0
        private WebResponse RunRegularRequest(QueryMethod method, string url, string data)
        {
            WebRequest request = WebRequest.Create(url);
            request.Proxy = WebRequest.DefaultWebProxy;
            request.ContentType = "application/json";
            request.Method = method.ToString();

            if (method == QueryMethod.POST)
            {
                using (StreamWriter writter = new StreamWriter(request.GetRequestStream()))
                {
                    writter.Write(data);
                }
            }

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    using (HttpWebResponse exResponse = (HttpWebResponse)e.Response)
                    {
                        OnError(this, new ResponseErrorEventArgs(null, exResponse.StatusCode, exResponse.StatusDescription));
                    }
                }
                else
                {
                    OnError(this, new ResponseErrorEventArgs(null, HttpStatusCode.BadRequest, e.Message));
                }
            }

            return response as WebResponse;
        }
Ejemplo n.º 13
0
 private AuthResponse ExecuteRequest(QueryMethod method, string url, string data)
 {
     string appName = this.GetAppName();
     AuthRequest authRequest = new AuthRequest(_consumerKey, _consumerSecret, appName, _useCompression, _apiVersion);
     using (authRequest)
     {
         OnRequest(this, new RequestEventArgs(method.ToString(), url, data));
         AuthResponse authResponse = authRequest.AuthWebRequest(method, url, data);
         OnResponse(this, new ResponseEventArgs(authResponse.Status, authResponse.Data));
         return authResponse;
     }
 }
Ejemplo n.º 14
0
        private AuthResponse WebRequest(QueryMethod method, string url, string postData, string authheader)
        {
            HttpWebRequest webRequest = null;
            StreamWriter requestWriter = null;

            webRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
            webRequest.Method = method.ToString();
            webRequest.Credentials = CredentialCache.DefaultCredentials;

            webRequest.Headers.Add("x-api-version", "2.1");
            webRequest.Headers.Add("x-app-name", _appName);

            //Add authorization header
            webRequest.Headers.Add("Authorization", authheader);

            if (method == QueryMethod.POST)
            {
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //POST the data.
                requestWriter = new StreamWriter(webRequest.GetRequestStream());
                try
                {
                    requestWriter.Write(postData);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    requestWriter.Close();
                    requestWriter = null;
                }
            }

            AuthResponse authResponse = WebResponseGet(webRequest);
            authResponse.Method = method;

            webRequest = null;

            return authResponse;
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The http request method
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="method">Query method</param>
        /// <param name="apiKey">Api key</param>
        /// <param name="accessToken">Access token</param>
        /// <param name="url">Url</param>
        /// <param name="payload">Payload</param>
        /// <param name="logger">Optional, logger</param>
        /// <param name="isDictionary">Is json string is a dictionary object. Default value is false</param>
        /// <returns></returns>
        private static T QueryHttp <T>(QueryMethod method, string apiKey, string accessToken, string url, string payload = null, IKiteLogger logger = null, bool isDictionary = false)
        {
            if (!Enum.IsDefined(typeof(QueryMethod), method))
            {
                return(default(T));
            }

            if (string.IsNullOrEmpty(url))
            {
                return(default(T));
            }

            try
            {
                logger?.OnLog($"{method}|apiKey={apiKey}, accessToken= {accessToken}, Url={url}, Payload= {payload}");
            }
            catch (Exception ex)
            {
            }

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method            = method.ToString().ToUpper();
                request.AllowAutoRedirect = true;

                request.Headers.Add(versionHeader, version);

                request.Headers.Add("Authorization", $"token {apiKey}:{accessToken}");

                if (method == QueryMethod.POST || method == QueryMethod.PUT)
                {
                    request.ContentType = "application/x-www-form-urlencoded";

                    if (!string.IsNullOrEmpty(payload))
                    {
                        byte[] postData = Encoding.ASCII.GetBytes(payload);
                        request.ContentLength = postData.Length;

                        using (Stream stream = request.GetRequestStream())
                        {
                            stream.Write(postData, 0, postData.Length);
                        }
                    }
                }

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        //if logger is not null we will log the json string
                        if (logger != null)
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                Response <T> obj = ParseString <Response <T> >(reader.ReadToEnd(), logger: logger, methodName: typeof(T).Name, isDictionary: isDictionary);

                                if (obj == null)
                                {
                                    return(default(T));
                                }

                                return(obj.data);
                            }
                        }
                        else //we serialize straight away
                        {
                            DataContractJsonSerializer serializer = null;
                            if (isDictionary)
                            {
                                serializer = new DataContractJsonSerializer(typeof(Response <T>), new DataContractJsonSerializerSettings()
                                {
                                    UseSimpleDictionaryFormat = true
                                });
                            }
                            else
                            {
                                serializer = new DataContractJsonSerializer(typeof(Response <T>));
                            }

                            Response <T> obj = serializer.ReadObject(response.GetResponseStream()) as Response <T>;

                            if (obj == null)
                            {
                                return(default(T));
                            }

                            return(obj.data);
                        }
                    }
                }
            }
            catch (WebException we)
            {
                try
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ServerError));
                    ServerError se = serializer.ReadObject(we.Response.GetResponseStream()) as ServerError;
                    if (se != null)
                    {
                        try
                        {
                            logger?.OnLog($"{se.error_type} | {se.status} | {se.message}");
                        }
                        catch (Exception ex)
                        {
                        }

                        try
                        {
                            logger?.OnException(new ServerException(se, we.Status, typeof(T)));
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        logger?.OnException(ex);
                    }
                    catch (Exception ex1)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    logger?.OnException(ex);
                }
                catch (Exception ex1)
                {
                }
            }

            return(default(T));
        }