]> khamidou — GitHub mirrors - inbox.net.git/commitdiff
Added base InboxAPIObject class and RestfulModelCollection class master
authorGSonofNun <sonofnun@outlook.com>
Wed, 24 Sep 2014 20:19:58 +0000 (16:19 -0400)
committerGSonofNun <sonofnun@outlook.com>
Wed, 24 Sep 2014 20:19:58 +0000 (16:19 -0400)
inbox_net/Client.cs
inbox_net/DataModel/InboxAPIObject.cs [new file with mode: 0644]
inbox_net/DataModel/RestfulModelCollection.cs [new file with mode: 0644]
inbox_net/InboxException.cs [new file with mode: 0644]
inbox_net/Utilities.cs
inbox_net/inbox_net.csproj

index e2a2f6b2d0c1e06577eef57bff3d0d0525753c31..37b28c6cc5660aad375e18b7d1da0469b94973dc 100644 (file)
@@ -5,6 +5,9 @@ using System.Linq;
 using System.Net.Http;
 using System.Text;
 using System.Threading.Tasks;
 using System.Net.Http;
 using System.Text;
 using System.Threading.Tasks;
+using inbox_net.DataModel;
+using Newtonsoft.Json;
+using System.Net;
 
 namespace inbox_net
 {
 
 namespace inbox_net
 {
@@ -35,9 +38,11 @@ namespace inbox_net
             this.access_token_url = AUTH_SERVER + "/oauth/token";
             this.client = new HttpClient();
             this.client.DefaultRequestHeaders.Add("X-Inbox-API-Wrapper", "dotNET");
             this.access_token_url = AUTH_SERVER + "/oauth/token";
             this.client = new HttpClient();
             this.client.DefaultRequestHeaders.Add("X-Inbox-API-Wrapper", "dotNET");
-
+            this.Namespaces = new RestfulModelCollection<Namespace>(this);
         }
 
         }
 
+        public RestfulModelCollection<Namespace> Namespaces { get; set; }
+
         public string Access_Token
         {
             get
         public string Access_Token
         {
             get
@@ -56,7 +61,7 @@ namespace inbox_net
 
         public string authenticationUrl(string redirect_uri, string login_hint = "")
         {
 
         public string authenticationUrl(string redirect_uri, string login_hint = "")
         {
-            Dictionary<string, string> args = new Dictionary<string, string>();
+            Dictionary<string, object> args = new Dictionary<string, object>();
             args.Add("redirect_uri", redirect_uri);
             args.Add("client_id", this.app_id);
             args.Add("response_type", "code");
             args.Add("redirect_uri", redirect_uri);
             args.Add("client_id", this.app_id);
             args.Add("response_type", "code");
@@ -88,8 +93,122 @@ namespace inbox_net
             return this.auth_token;
         }
 
             return this.auth_token;
         }
 
+        private async Task<HttpResponseMessage> ValidateResponse(HttpResponseMessage response)
+        {
+            Dictionary<HttpStatusCode, string> status_code_to_exc = new Dictionary<HttpStatusCode, string>();
+            status_code_to_exc.Add(HttpStatusCode.BadRequest, "APIError");
+            status_code_to_exc.Add(HttpStatusCode.NotFound, "NotFoundError");
+            status_code_to_exc.Add(HttpStatusCode.Conflict, "ConflictError");
+            var request = response.RequestMessage;
+            string url = request.RequestUri.ToString();
+            var status_code = response.StatusCode;
+            string data = await response.Content.ReadAsStringAsync();
+            JObject obj = null;
+            try
+            {
+                obj = data != null ? JObject.Parse(data) : null;
+            }
+            catch (Exception)
+            {
+
+            }
+
+            if (status_code == HttpStatusCode.OK)
+            {
+                return response;
+            }
+            else if (status_code == HttpStatusCode.Unauthorized)
+            {
+                throw new Exception("Not Authorized");
+            }
+            else if (status_code == HttpStatusCode.BadRequest || status_code == HttpStatusCode.NotFound || status_code == HttpStatusCode.Conflict)
+            {
+                string errorMessage = status_code_to_exc[status_code];
+                try
+                {
+                    JObject responseJSON = JObject.Parse(data);
+                    if (responseJSON["message"] != null)
+                    {
+                        throw new InboxException(url, status_code, data, responseJSON["message"].ToString());
+                    }
+                    else
+                    {
+                        throw new InboxException(url, status_code, data, "N/A");
+                    }
+                }
+                catch (Exception)
+                {
+                    throw new InboxException(url, status_code, data, "Malformed");
+                }
+                throw new Exception("Error - Your fault...probably");
+            }
+            else if (status_code == HttpStatusCode.InternalServerError)
+            {
+                throw new InboxException(url, status_code, data, "ServerError");
+            }
+            else
+            {
+                throw new InboxException(url, status_code, data, "Unknown status code");
+            }
+        }
+
+        public async Task<IEnumerable<T>> GetResources<T>(string _namespace, RestfulModelCollection<T> cls, Dictionary<string, object> filters)
+        {
+            string prefix = string.Format("/n/{0}", _namespace != null ? _namespace : "");
+            string url = string.Format("{0}{1}/{2}", this.api_server, prefix, cls.CollectionName);
+            url = Utilities.Url_Concat(url, filters);
+
+            string json = await (await ValidateResponse(await client.GetAsync(url))).Content.ReadAsStringAsync();
+            return await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IEnumerable<T>>(json));
+        }
+
+        public async Task<string> GetRawResource(string _namespace, string objectType, string id, Dictionary<string, object> filters)
+        {
+            // Get an indivitual REST resource
+            string extra = null;
+            if (filters["extra"] != null)
+            {
+                extra = filters["extra"].ToString();
+                filters.Remove("extra");
+            }
+            string prefix = string.Format("/n/{0}", _namespace != null ? _namespace : "");
+            string postfix = string.Format("/{0}", extra != null ? extra : "");
+            string url = string.Format("{0}{1}/{2}/{3}{4}", this.api_server, prefix, objectType, id, postfix);
+            url = Utilities.Url_Concat(url, filters);
+            return await (await ValidateResponse(await client.GetAsync(url))).Content.ReadAsStringAsync();
+        }
+
+        public async Task<T> GetResource<T>(string _namespace, string objectType, string id, Dictionary<string, object> filters)
+        {
+
+
+            return default(T);
+        }
+
+
+
 
 
 
 
-        
+        internal T CreateResource<T>(Namespace p1, object p2, string p3)
+        {
+            throw new NotImplementedException();
+        }
+
+        internal T UpdateResource<T>(Namespace _namespace, object cls, string id, string json)
+        {
+            throw new NotImplementedException();
+        }
+
+
+
+        internal object UpdateResource(Namespace p1, Type type, string p2, string p3)
+        {
+            throw new NotImplementedException();
+        }
+
+        internal object CreateResource(Namespace p1, Type type, string p2)
+        {
+            throw new NotImplementedException();
+        }
     }
 }
     }
 }
diff --git a/inbox_net/DataModel/InboxAPIObject.cs b/inbox_net/DataModel/InboxAPIObject.cs
new file mode 100644 (file)
index 0000000..49b068a
--- /dev/null
@@ -0,0 +1,63 @@
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace inbox_net.DataModel
+{
+    public class InboxAPIObject
+    {
+        public string ID { get; set; }
+        public Type CLS { get; set; }
+        public Client API { get; set; }
+        public Namespace Namespace { get; set; }
+
+        private InboxAPIObject(Type cls, Client api, Namespace _namespace)
+        {
+            this.ID = null;
+            this.CLS = cls;
+            this.API = api;
+            this.Namespace = _namespace;
+        }
+
+        public InboxAPIObject Create(Type cls, Client api, Namespace _namespace)
+        {
+            var obj = Activator.CreateInstance(this.CLS, this.API, this.Namespace);
+            (obj as InboxAPIObject).CLS = cls;
+            return obj as InboxAPIObject;
+        }
+
+        public async Task<string> AsJson()
+        {
+            return await Task.Factory.StartNew(() => JsonConvert.SerializeObject(this));
+        }
+
+        public RestfulModelCollection<T> ChildCollection<T>(Dictionary<string, object> filters = null)
+        {
+            return new RestfulModelCollection<T>(this.API, this.Namespace, filters);
+        }
+
+        public async void Save()
+        {
+            var newObj = Activator.CreateInstance(this.CLS);
+            if (this.ID != null)
+            {
+                newObj = this.API.UpdateResource(this.Namespace, this.CLS, this.ID, await this.AsJson());
+            }
+            else
+            {
+                newObj = this.API.CreateResource(this.Namespace, this.CLS, await this.AsJson());
+            }
+            this.CLS = newObj.GetType();
+        }
+
+        public async void Update()
+        {
+            var newObj = Activator.CreateInstance(this.CLS);
+            newObj = this.API.UpdateResource(this.Namespace, this.CLS, this.ID, await this.AsJson());
+            this.CLS = newObj.GetType();
+        }
+    }
+}
diff --git a/inbox_net/DataModel/RestfulModelCollection.cs b/inbox_net/DataModel/RestfulModelCollection.cs
new file mode 100644 (file)
index 0000000..9892ee5
--- /dev/null
@@ -0,0 +1,47 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace inbox_net.DataModel
+{
+    public class RestfulModelCollection<T> : ObservableCollection<T>
+    {
+        const int CHUNK_SIZE = 50;
+        const int MAX_ITEMS = Convert.ToInt32(Math.Pow(2,64)) - 1;
+
+        private Namespace Namespace;
+        private Client api;
+        private Dictionary<string, object> filters;
+        private int offset;
+        private int limit;
+        public string CollectionName { get; set; }
+
+        public RestfulModelCollection(Client _api, Namespace _namespace, Dictionary<string, object> filter = null, int _offset = 0, int _limit = 0) : base()
+        {
+            if (filter == null)
+            {
+                this.filters = new Dictionary<string, object>();
+            }
+            else
+            {
+                this.filters = filter;
+            }
+            filters.Add("offset", 0);
+            filters.Add("limit", MAX_ITEMS);
+            this.Namespace = _namespace;
+            this.api = _api;
+            this.offset = _offset;
+            if (_limit == 0)
+            {
+                this.limit = MAX_ITEMS;
+            }
+            else
+            {
+                this.limit = _limit;
+            }
+        }
+    }
+}
diff --git a/inbox_net/InboxException.cs b/inbox_net/InboxException.cs
new file mode 100644 (file)
index 0000000..0a1b687
--- /dev/null
@@ -0,0 +1,30 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace inbox_net
+{
+    public class InboxException : Exception
+    {
+        public string Url { get; set; }
+        public HttpStatusCode StatusCode { get; set; }
+        public string Data { get; set; }
+        public string Message { get; set; }
+
+        public InboxException(string url, HttpStatusCode statusCode, string data, string message)
+        {
+            Url = url;
+            StatusCode = statusCode;
+            Data = data;
+            Message = message;
+        }
+
+        public InboxException()
+        {
+
+        }
+    }
+}
index f442ea847b8c37e54629fd183e5c9d0d80078eff..35205a88917bb315969badf9d4f8eadc0e07c712 100644 (file)
@@ -9,7 +9,7 @@ namespace inbox_net
 {
     public static class Utilities
     {
 {
     public static class Utilities
     {
-        public static string Url_Concat(string url, Dictionary<string, string> args, string fragments = null)
+        public static string Url_Concat(string url, Dictionary<string, object> args, string fragments = null)
         {
             if (args == null && fragments == null)
             {
         {
             if (args == null && fragments == null)
             {
@@ -35,7 +35,7 @@ namespace inbox_net
                     {
                         args_tail += url.Contains("?") ? "&" : "?";
                     }
                     {
                         args_tail += url.Contains("?") ? "&" : "?";
                     }
-                    args_tail += string.Format("{0}={1}", item.Key, WebUtility.UrlEncode(item.Value));
+                    args_tail += string.Format("{0}={1}", item.Key, WebUtility.UrlEncode(item.Value.ToString()));
                 }
             }
 
                 }
             }
 
index fc8a6180d6836f38e5498908c20fdce14ac051df..b213fec7b1d4db6e5ae0ab37b81bf70d5f727030 100644 (file)
     <Compile Include="DataModel\CanonicalTags.cs" />
     <Compile Include="DataModel\Draft.cs" />
     <Compile Include="DataModel\File.cs" />
     <Compile Include="DataModel\CanonicalTags.cs" />
     <Compile Include="DataModel\Draft.cs" />
     <Compile Include="DataModel\File.cs" />
+    <Compile Include="DataModel\InboxAPIObject.cs" />
     <Compile Include="DataModel\Message.cs" />
     <Compile Include="DataModel\MethodURIs.cs" />
     <Compile Include="DataModel\Namespace.cs" />
     <Compile Include="DataModel\Participant.cs" />
     <Compile Include="DataModel\Post.cs" />
     <Compile Include="DataModel\Message.cs" />
     <Compile Include="DataModel\MethodURIs.cs" />
     <Compile Include="DataModel\Namespace.cs" />
     <Compile Include="DataModel\Participant.cs" />
     <Compile Include="DataModel\Post.cs" />
+    <Compile Include="DataModel\RestfulModelCollection.cs" />
     <Compile Include="DataModel\Tag.cs" />
     <Compile Include="DataModel\Thread.cs" />
     <Compile Include="InboxClient.cs" />
     <Compile Include="DataModel\Tag.cs" />
     <Compile Include="DataModel\Thread.cs" />
     <Compile Include="InboxClient.cs" />
+    <Compile Include="InboxException.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="StringConstants.cs" />
     <Compile Include="Utilities.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="StringConstants.cs" />
     <Compile Include="Utilities.cs" />