Inheritance: APIObject
Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:FuelSDK.PostReturn"/> class.
        /// </summary>
        /// <param name="obj">Object.</param>
        public PostReturn(FuelObject obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            var response = ExecuteFuel(obj, obj.RequiredURLProperties, "POST", true);

            if (string.IsNullOrEmpty(response))
            {
                Results = new ResultDetail[0];
            }
            else if (response.StartsWith("["))
            {
                Results = JArray.Parse(response)
                          .Select(x => new ResultDetail {
                    Object = (APIObject)Activator.CreateInstance(obj.GetType(), BindingFlags.Public | BindingFlags.Instance, null, new object[] { x }, null)
                }).ToArray();
            }
            else
            {
                var x = JObject.Parse(response);
                Results = new[] { new ResultDetail {
                                      Object = (APIObject)Activator.CreateInstance(obj.GetType(), BindingFlags.Public | BindingFlags.Instance, null, new object[] { x }, null)
                                  } };
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:FuelSDK.DeleteReturn"/> class.
 /// </summary>
 /// <exception cref="System.ArgumentNullException">
 /// <param name="obj">FuelObject</param>
 public DeleteReturn(FuelObject obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException("obj");
     }
     ExecuteFuel(obj, obj.URLProperties, "DELETE", false);
 }
Ejemplo n.º 3
0
        protected string ExecuteFuel(FuelObject obj, string[] required, string method, bool postValue)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            obj.AuthStub.RefreshToken();

            object propValue;
            string propValueAsString;
            var    completeURL = obj.Endpoint;

            if (required != null)
            {
                foreach (string urlProp in required)
                {
                    var match = false;
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        if (prop.Name == "UniqueID")
                        {
                            continue;
                        }
                        if (obj.URLProperties.Contains(prop.Name) && (propValue = prop.GetValue(obj, null)) != null)
                        {
                            if ((propValueAsString = propValue.ToString().Trim()).Length > 0 && propValueAsString != "0")
                            {
                                match = true;
                            }
                        }
                    }
                    if (!match)
                    {
                        throw new Exception("Unable to process request due to missing required property: " + urlProp);
                    }
                }
            }
            foreach (var prop in obj.GetType().GetProperties())
            {
                if (prop.Name == "UniqueID")
                {
                    continue;
                }
                if (obj.URLProperties.Contains(prop.Name) && (propValue = prop.GetValue(obj, null)) != null)
                {
                    if ((propValueAsString = propValue.ToString().Trim()).Length > 0 && propValueAsString != "0")
                    {
                        completeURL = completeURL.Replace("{" + prop.Name + "}", propValueAsString);
                    }
                }
            }

            // Clean up not required URL parameters
            if (obj.URLProperties != null)
            {
                foreach (string urlProp in obj.URLProperties)
                {
                    completeURL = completeURL.Replace("{" + urlProp + "}", string.Empty);
                }
            }

            if (obj.Page.HasValue && obj.Page.Value > 0)
            {
                completeURL += "?page=" + obj.Page.ToString();
            }

            var request = (HttpWebRequest)WebRequest.Create(completeURL.Trim());

            request.Headers.Add("Authorization", "Bearer " + obj.AuthStub.AuthToken);
            request.Method      = method;
            request.ContentType = "application/json";
            request.UserAgent   = ETClient.SDKVersion;

            if (postValue)
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                    streamWriter.Write(JsonConvert.SerializeObject(obj));
            }

            // Get the response
            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                    using (var dataStream = response.GetResponseStream())
                        using (var reader = new StreamReader(dataStream))
                        {
                            Code        = (int)response.StatusCode;
                            Status      = (response.StatusCode == HttpStatusCode.OK);
                            MoreResults = false;
                            Message     = (Status ? string.Empty : response.ToString());
                            return(Status ? reader.ReadToEnd() : null);
                        }
            }
            catch (WebException we)
            {
                Code        = (int)((HttpWebResponse)we.Response).StatusCode;
                Status      = false;
                MoreResults = false;
                using (var stream = we.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                        Message = reader.ReadToEnd();
                return(null);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:FuelSDK.GetReturn"/> class.
        /// </summary>
        /// <param name="obj">Object.</param>
        public GetReturn(FuelObject obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            var response = ExecuteFuel(obj, obj.RequiredURLProperties, "GET", false);

            if (string.IsNullOrEmpty(response))
            {
                return;
            }
            var parsedResponse = JObject.Parse(response);

            // Check on the paging information from response
            if (parsedResponse["page"] != null)
            {
                LastPageNumber = int.Parse(parsedResponse["page"].Value <string>().Trim());
                var pageSize = int.Parse(parsedResponse["pageSize"].Value <string>().Trim());

                var count = -1;
                if (parsedResponse["count"] != null)
                {
                    count = int.Parse(parsedResponse["count"].Value <string>().Trim());
                }
                else if (parsedResponse["totalCount"] != null)
                {
                    count = int.Parse(parsedResponse["totalCount"].Value <string>().Trim());
                }
                if (count != -1 && (count > (LastPageNumber * pageSize)))
                {
                    MoreResults = true;
                }
            }

            // Sub-response
            string subResponse;

            if (parsedResponse["items"] != null)
            {
                subResponse = parsedResponse["items"].ToString().Trim();
            }
            else if (parsedResponse["entities"] != null)
            {
                subResponse = parsedResponse["entities"].ToString().Trim();
            }
            else
            {
                subResponse = response.Trim();
            }
            if (string.IsNullOrEmpty(subResponse))
            {
                return;
            }

            var responseAsJSon = JsonConvert.DeserializeObject(response);

            if (responseAsJSon == null || responseAsJSon.ToString().Length <= 0)
            {
                Results = new APIObject[0];
            }
            else
            if (subResponse.StartsWith("["))
            {
                Results = JArray.Parse(subResponse)
                          .Select(x => (APIObject)Activator.CreateInstance(obj.GetType(), BindingFlags.Public | BindingFlags.Instance, null, new object[] { x }, null)).ToArray();
            }
            else
            {
                var x = JObject.Parse(subResponse);
                Results = new[] { (APIObject)Activator.CreateInstance(obj.GetType(), BindingFlags.Public | BindingFlags.Instance, null, new object[] { x }, null) };
            }
        }
        public PostReturn(FuelObject theObject)
        {
            this.Message = "";
            this.Status = true;
            this.MoreResults = false;
            string completeURL = theObject.Endpoint;
            string additionalQS;

            theObject.AuthStub.refreshToken();

            foreach (PropertyInfo prop in theObject.GetType().GetProperties())
            {
                if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
                    if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                        completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
            }

            bool match;
            if (theObject.RequiredURLProperties != null)
            {
                foreach (string urlProp in theObject.RequiredURLProperties)
                {
                    match = false;

                    foreach (PropertyInfo prop in theObject.GetType().GetProperties())
                    {
                        if (theObject.URLProperties.Contains(prop.Name))
                            if (prop.GetValue(theObject, null) != null)
                            {
                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                                    match = true;
                            }
                    }
                    if (match == false)
                        throw new Exception("Unable to process request due to missing required property: " + urlProp);

                }
            }

            // Clean up not required URL parameters
            int j = 0;
            if (theObject.URLProperties != null)
            {
                foreach (string urlProp in theObject.URLProperties)
                {
                    completeURL = completeURL.Replace("{" + urlProp + "}", "");
                    j++;
                }
            }

            additionalQS = "access_token=" + theObject.AuthStub.authToken;
            completeURL = completeURL + "?" + additionalQS;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(completeURL.Trim());
            request.Method = "POST";
            request.ContentType = "application/json";
            request.UserAgent = theObject.AuthStub.SDKVersion;

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string jsonPayload = JsonConvert.SerializeObject(theObject);
                streamWriter.Write(jsonPayload);
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();

                if (response != null)
                    this.Code = (int)response.StatusCode;
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        this.Status = true;
                        List<ResultDetail> AllResults = new List<ResultDetail>();

                        if (responseFromServer.ToString().StartsWith("["))
                        {
                            JArray jsonArray = JArray.Parse(responseFromServer.ToString());
                            foreach (JObject obj in jsonArray)
                            {
                                APIObject currentObject = (APIObject)Activator.CreateInstance(theObject.GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { obj }, null);
                                ResultDetail result = new ResultDetail();
                                result.Object = currentObject;
                                AllResults.Add(result);
                            }

                            this.Results = AllResults.ToArray();
                        }
                        else
                        {
                            JObject jsonObject = JObject.Parse(responseFromServer.ToString());
                            ResultDetail result = new ResultDetail();
                            APIObject currentObject = (APIObject)Activator.CreateInstance(theObject.GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new object[] { jsonObject }, null);
                            result.Object = currentObject;
                            AllResults.Add(result);
                            this.Results = AllResults.ToArray();
                        }

                    }
                    else
                    {
                        this.Status = false;
                        this.Message = response.ToString();
                    }
                }

                response.Close();
            }
            catch (WebException we)
            {
                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
                this.Status = false;
                this.Results = new ResultDetail[] { };
                using (var stream = we.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Message = reader.ReadToEnd();
                }
            }
        }
        private void restGet(ref FuelObject theObject, string url)
        {
            //Build the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Trim());
            request.Method = "GET";
            request.ContentType = "application/json";
            request.UserAgent = theObject.AuthStub.SDKVersion;

            //Get the response
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();

                if (response != null)
                    this.Code = (int)response.StatusCode;
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        this.Status = true;
                        if (responseFromServer != null)
                        {
                            JObject parsedResponse = JObject.Parse(responseFromServer);
                            //Check on the paging information from response
                            if (parsedResponse["page"] != null)
                            {
                                this.LastPageNumber = int.Parse(parsedResponse["page"].Value<string>().Trim());
                                int pageSize = int.Parse(parsedResponse["pageSize"].Value<string>().Trim());

                                int count = -1;
                                if (parsedResponse["count"] != null)
                                {
                                    count = int.Parse(parsedResponse["count"].Value<string>().Trim());
                                }
                                else if (parsedResponse["totalCount"] != null)
                                {
                                    count = int.Parse(parsedResponse["totalCount"].Value<string>().Trim());
                                }

                                if (count != -1 && (count > (this.LastPageNumber * pageSize)))
                                {
                                    this.MoreResults = true;
                                }
                            }

                            APIObject[] getResults = new APIObject[] { };

                            if (parsedResponse["items"] != null)
                                getResults = processResults(parsedResponse["items"].ToString().Trim(), theObject.GetType());
                            else if (parsedResponse["entities"] != null)
                                getResults = processResults(parsedResponse["entities"].ToString().Trim(), theObject.GetType());
                            else
                                getResults = processResults(responseFromServer.Trim(), theObject.GetType());

                            this.Results = getResults.ToArray();
                        }
                    }
                    else
                    {
                        this.Status = false;
                        this.Message = response.ToString();
                    }
                }
                response.Close();
            }
            catch (WebException we)
            {
                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
                this.Status = false;
                using (var stream = we.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    this.Message = reader.ReadToEnd();
                }
            }
        }
        public GetReturn(FuelObject theObject)
        {
            this.Message = "";
            this.Status = true;
            this.MoreResults = false;
            this.Results = new APIObject[] { };

            theObject.AuthStub.refreshToken();

            string completeURL = theObject.Endpoint;
            string additionalQS = "";
            bool boolAdditionalQS = false;

            if (theObject != null)
            {
                foreach (PropertyInfo prop in theObject.GetType().GetProperties())
                {
                    if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
                        if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                            completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
                }
            }

            ////props code for paging
            if (theObject.Page != 0)
            {
                additionalQS += "$page=" + theObject.Page;
                boolAdditionalQS = true;
            }

            bool match;
            if (theObject.RequiredURLProperties != null)
            {
                foreach (string urlProp in theObject.RequiredURLProperties)
                {
                    match = false;
                    if (theObject != null)
                    {
                        foreach (PropertyInfo prop in theObject.GetType().GetProperties())
                        {
                            if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                                    match = true;
                        }

                        if (match == false)
                            throw new Exception("Unable to process request due to missing required prop: " + urlProp);
                    }
                    else
                        throw new Exception("Unable to process request due to missing required prop: " + urlProp);
                }
            }

            //Clean up not required URL parameters
            int j = 0;
            if (theObject.URLProperties != null)
            {
                foreach (string urlProp in theObject.URLProperties)
                {
                    completeURL = completeURL.Replace("{" + urlProp + "}", "");
                    j++;
                }
            }

            if (!boolAdditionalQS)
                additionalQS += "access_token=" + theObject.AuthStub.authToken;
            else
                additionalQS += "&access_token=" + theObject.AuthStub.authToken;

            completeURL = completeURL + "?" + additionalQS;
            restGet(ref theObject, completeURL);
        }
        private void restDelete(FuelObject theObject, string url)
        {
            //Build the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.Trim());
            request.Method = "DELETE";
            request.ContentType = "application/json";
            request.UserAgent = theObject.AuthStub.SDKVersion;

            //Get the response
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();

                if (response != null)
                    this.Code = (int)response.StatusCode;
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        this.Status = true;
                    }
                    else
                    {
                        this.Status = false;
                        this.Message = response.ToString();
                    }
                }

                response.Close();
            }
            catch (WebException we)
            {
                this.Code = (int)((HttpWebResponse)we.Response).StatusCode;
                this.Status = false;
                using (var stream = we.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    this.Message = reader.ReadToEnd();
                }
            }
        }
        public DeleteReturn(FuelObject theObject)
        {
            this.Message = "";
            this.Status = true;
            this.MoreResults = false;
            this.Results = new ResultDetail[] { };

            theObject.AuthStub.refreshToken();

            string completeURL = theObject.Endpoint;
            string additionalQS;

            // All URL Props are required when doing Delete
            bool match;
            if (theObject.URLProperties != null)
            {
                foreach (string urlProp in theObject.URLProperties)
                {
                    match = false;
                    if (theObject != null)
                    {
                        foreach (PropertyInfo prop in theObject.GetType().GetProperties())
                        {
                            if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
                                if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                                    match = true;
                        }
                        if (match == false)
                            throw new Exception("Unable to process request due to missing required prop: " + urlProp);
                    }
                    else
                        throw new Exception("Unable to process request due to missing required prop: " + urlProp);
                }
            }

            if (theObject != null)
            {
                foreach (PropertyInfo prop in theObject.GetType().GetProperties())
                {
                    if (theObject.URLProperties.Contains(prop.Name) && prop.GetValue(theObject, null) != null)
                        if (prop.GetValue(theObject, null).ToString().Trim() != "" && prop.GetValue(theObject, null).ToString().Trim() != "0")
                            completeURL = completeURL.Replace("{" + prop.Name + "}", prop.GetValue(theObject, null).ToString());
                }
            }

            additionalQS = "access_token=" + theObject.AuthStub.authToken;
            completeURL = completeURL + "?" + additionalQS;
            restDelete(theObject, completeURL);
        }