Example #1
0
        public Application[] Get(string filter)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest("/rest/system/app", Method.GET);

            if (!filter.IsNullOrEmpty())
            {
                request.Parameters.Add(new Parameter()
                {
                    Name  = "filter",
                    Value = filter,
                    Type  = ParameterType.GetOrPost
                });
            }

            var response = Session.Client.Execute <ApplicationDescriptorList>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve Application descriptors: {0}", response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                var apps = new List <Application>();

                var data = response.Data;

                if (data != null)
                {
                    foreach (var app in data.record)
                    {
                        apps.Add(new Application(app));
                    }
                }

                return(apps.ToArray());

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #2
0
        public void Delete(string applicationID)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/system/app/{0}", applicationID), Method.DELETE);

            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                return;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #3
0
        public void DeleteContainer(string containerName)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/app/{0}/", containerName), Method.DELETE);

            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                return;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                var error = SimpleJson.DeserializeObject <ErrorDescriptorList>(response.Content);
                // TODO: make a library-specific Exception class
                throw new Exception(error.error[0].message);
            }
        }
Example #4
0
        internal Table(Session session, string tableName)
        {
            Session = session;
            m_uris  = new UriFactory(Session.ServerVersion);

            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("{0}/{1}", m_uris.SchemaRoot, tableName), Method.GET);

            var response = Session.Client.Execute <TableDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve the schema for table '{0}': {1}", tableName, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                var descriptor = response.Data;

                Name  = descriptor.name;
                Label = descriptor.label;

                var fieldList = new List <Field>();

                foreach (var f in descriptor.field)
                {
                    var fld = f.AsField();
                    fieldList.Add(fld);
                    if (f.is_primary_key.HasValue && f.is_primary_key.Value)
                    {
                        KeyField = fld;
                    }
                }

                Fields = fieldList.ToArray();
                break;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #5
0
        public int GetRecordCount(string filter)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), Method.GET);

            request.Parameters.Add(new Parameter()
            {
                Name = "limit", Value = 1, Type = ParameterType.GetOrPost
            });
            request.Parameters.Add(new Parameter()
            {
                Name = "include_count", Value = "true", Type = ParameterType.GetOrPost
            });

            if (!string.IsNullOrEmpty(filter))
            {
                request.Parameters.Add(new Parameter()
                {
                    Name = "filter", Value = filter, Type = ParameterType.GetOrPost
                });
            }

            var response = Session.Client.Execute <ResourceDescriptorList>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve a record count on table '{0}': {1}", Name, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                // TODO: this feels fragile - we should look at improving it
                return(Convert.ToInt32(((SimpleJson.DeserializeObject(response.Content) as JsonObject)[1] as JsonObject)[0]));

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #6
0
        public Container[] GetContainers()
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            // this is non-intuitive based on the published API.
            var request = Session.GetSessionRequest("/rest/app", Method.GET);

            var response = Session.Client.Execute <ContainerDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve Container descriptors: {0}", response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                var containers = new List <Container>();

                var container = response.Data;

                if (container != null)
                {
                    foreach (var app in container.folder)
                    {
                        containers.Add(new Container(app));
                    }
                }

                return(containers.ToArray());

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                var error = SimpleJson.DeserializeObject <ErrorDescriptorList>(response.Content);
                // TODO: make a library-specific Exception class
                throw new Exception(error.error[0].message);
            }
        }
Example #7
0
        public Container GetContainer(string containerName)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            // todo: add caching

            // The trailing slash here is *required*. Without it we'll get back a NotFound
            var request = Session.GetSessionRequest(string.Format("/rest/app/{0}/", containerName), Method.GET);

            var response = Session.Client.Execute <ContainerDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to container descriptor for '{0}': {1}", containerName, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case System.Net.HttpStatusCode.OK:
                var container = response.Data;

                if (container != null)
                {
                    return(new Container(container));
                }

                return(null);

            case System.Net.HttpStatusCode.NotFound:
                return(null);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                var error = SimpleJson.DeserializeObject <ErrorDescriptorList>(response.Content);
                // TODO: make a library-specific Exception class
                throw new Exception(error.error[0].message);
            }
        }
Example #8
0
        public Application Create(string name)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var descriptor = new ApplicationDescriptor()
            {
                name     = name,
                api_name = name
            };

            var request = Session.GetSessionRequest("/rest/system/app", Method.POST);

            request.JsonSerializer.ContentType = "application/json; charset=utf-8";
            request.JsonSerializer.Options     = new SerializerOptions()
            {
                SkipNullProperties = true
            };
            request.AddBody(descriptor);

            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                return(Find(name));

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #9
0
File: Session.cs Project: fkdl/orm
        private SystemConfigDescriptor GetSystemConfig()
        {
            var request  = GetSessionRequest("/rest/system/config", Method.GET, false);
            var response = Client.Execute <SystemConfigDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to deserialize the Session descriptor: {0}", response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                return(response.Data);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #10
0
        public void DeleteTable(string tableName)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("{0}/{1}", m_uris.SchemaRoot, tableName), Method.DELETE);

            // delete the table
            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                lock (m_tableCache)
                {
                    if (m_tableCache.ContainsKey(tableName))
                    {
                        m_tableCache.Remove(tableName);
                    }
                }
                break;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #11
0
        public void DeleteFilteredRecords(string filter)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), Method.DELETE);

            request.Parameters.Add(new Parameter()
            {
                Name  = "filter",
                Value = filter,
                Type  = ParameterType.GetOrPost
            });

            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                return;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #12
0
        public IEnumerable <object[]> GetRecords(int limit, int offset, string filter, string order)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), Method.GET);

            if (limit > 0)
            {
                request.Parameters.Add(new Parameter()
                {
                    Name = "limit", Value = limit, Type = ParameterType.GetOrPost
                });
            }
            if (offset > 0)
            {
                request.Parameters.Add(new Parameter()
                {
                    Name = "offset", Value = offset, Type = ParameterType.GetOrPost
                });
            }
            if (!filter.IsNullOrEmpty())
            {
                request.Parameters.Add(new Parameter()
                {
                    Name = "filter", Value = filter, Type = ParameterType.GetOrPost
                });
            }
            if (!order.IsNullOrEmpty())
            {
                request.Parameters.Add(new Parameter()
                {
                    Name = "order", Value = order, Type = ParameterType.GetOrPost
                });
            }

            var response = Session.Client.Execute <ResourceDescriptorList>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve a records from table '{0}': {1}", Name, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:

                JsonObject results = SimpleJson.DeserializeObject <JsonObject>(response.Content);

                var records = new List <object[]>();

                foreach (JsonObject item in results["record"] as JsonArray)
                {
                    var array = new object[Fields.Length];
                    var index = 0;

                    foreach (var field in Fields)
                    {
                        array[index++] = item[field.Name];
                    }

                    records.Add(array);
                }

                return(records);

            case HttpStatusCode.NotFound:
                // table doesn't exist, make sure it's not in the cache (e.g. remote delete)
                Session.Data.RemoveTableFromCache(this.Name);

                throw new TableNotFoundException(this.Name);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #13
0
        public Table GetTable(string tableName)
        {
            if (m_tableCache.ContainsKey(tableName))
            {
                return(m_tableCache[tableName]);
            }

            // TODO: enable caching of this info

            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

//            var request = Session.GetSessionRequest(string.Format("/rest/schema/{0}", tableName), Method.GET);
            var request = Session.GetSessionRequest(m_uris.GetTableSchema(tableName), Method.GET);

            var response = Session.Client.Execute <ResourceDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                // we've seen problems in Mono (3.2.3 on the windows desktop) with GZip decompression failure
                throw new DeserializationException(string.Format("Failed to deserialize schema response for table '{0}': {1}", tableName, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                var table = new Table(Session, response.Data);
                if (!m_tableCache.ContainsKey(tableName))
                {
                    m_tableCache.Add(tableName, table);
                }
                return(table);

            case HttpStatusCode.NotFound:
                return(null);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                // TODO: attempt to-reconnect?

                throw DreamFactoryException.Parse(response);

            default:
                var error = SimpleJson.DeserializeObject <ErrorDescriptorList>(response.Content);
                if (error.error.Count > 0)
                {
                    // As of 10/24/13 DreamFactory has a bug where it returns a 500 instead of a 404 for a not-found table
                    // Oddly, the error code inside the error returned is a 404, so they know it's not found.  This is the workaround.
                    if (error.error[0].code == 404)
                    {
                        return(null);
                    }

                    throw DreamFactoryException.Parse(response);
                }

                throw DreamFactoryException.Parse(response);
            }
        }
Example #14
0
        public Table CreateTable(string tableName, string label, IEnumerable <Field> fields)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var tableDescriptor = new TableDescriptor()
            {
                name   = tableName,
                label  = label,
                plural = tableName + "s"
            };

            var fieldDescriptors = new List <FieldDescriptor>();

            foreach (var f in fields)
            {
                fieldDescriptors.Add(f.AsFieldDescriptor());
            }

            tableDescriptor.field = fieldDescriptors;

            // build up a request to create the table
            var request = Session.GetSessionRequest(m_uris.SchemaRoot, Method.POST);

            request.JsonSerializer.ContentType = "application/json; charset=utf-8";
            request.JsonSerializer.Options     = new SerializerOptions()
            {
                SkipNullProperties = true
            };
            request.AddBody(tableDescriptor);

            // create the table
            var response = Session.Client.Execute(request);

            // check response
            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                // query the table schema back
                var actualTable = new Table(Session, tableName);

                lock (m_tableCache)
                {
                    m_tableCache.Add(actualTable.Name, actualTable);
                }

                // TODO: handle failure

                return(actualTable);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #15
0
        public Table UpdateTable(string tableName, IEnumerable <Field> updatedFieldList)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var tableDescriptor = new TableDescriptor();

            tableDescriptor.name  = tableName;
            tableDescriptor.field = new List <FieldDescriptor>();
            foreach (var f in updatedFieldList)
            {
                tableDescriptor.field.Add(f.AsFieldDescriptor());
            }

            var request = Session.GetSessionRequest(m_uris.GetTableSchema(tableName), Method.PATCH);

            request.JsonSerializer.ContentType = "application/json; charset=utf-8";
            request.JsonSerializer.Options     = new SerializerOptions()
            {
                SkipNullProperties = true
            };
            request.AddBody(tableDescriptor);

            // create the table
            var response = Session.Client.Execute(request);

            // check response
            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                // query the table schema back
                var actualTable = new Table(Session, tableName);

                lock (m_tableCache)
                {
                    if (!m_tableCache.ContainsKey(actualTable.Name))
                    {
                        m_tableCache.Add(actualTable.Name, actualTable);
                    }
                    else
                    {
                        m_tableCache[actualTable.Name] = actualTable;
                    }
                }

                // TODO: handle failure

                return(actualTable);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #16
0
        public Table[] GetTables(bool useCache)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest("/rest/db", Method.GET);

            var response = Session.Client.Execute <ResourceDescriptorList>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to deserialize the list of tables: {0}", response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                var list = new List <Table>();

                lock (m_tableCache)
                {
                    foreach (var resource in response.Data.resource)
                    {
                        Table t = null;

                        if (useCache)
                        {
                            if (m_tableCache.ContainsKey(resource.name))
                            {
                                t = m_tableCache[resource.name];
                                list.Add(t);
                            }
                        }

                        if (t == null)
                        {
                            try
                            {
                                t = new Table(Session, resource);

                                list.Add(t);

                                if (!m_tableCache.ContainsKey(t.Name))
                                {
                                    m_tableCache.Add(t.Name, t);
                                }
                                else
                                {
                                    m_tableCache[t.Name] = t;
                                }
                            }
                            catch (Exception ex)
                            {
                                // TODO: log this?
                                if (Debugger.IsAttached)
                                {
                                    Debugger.Break();
                                }
                                Debug.WriteLine(ex.Message);
                                throw;
                            }
                        }
                    }
                }

                return(list.ToArray());

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #17
0
        private object SendRecord(Dictionary <string, object> fields, bool isUpdate)
        {
            try
            {
                if (Session.Disconnected)
                {
                    Session.Reconnect();
                }

                var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), isUpdate ? Method.PUT : Method.POST);

                // "{\"record\":[{\"ID\":\"1\",\"Name\":\"Item #1\",\"UUID\":null,\"ITest\":23,\"Address\":\"Foo\",\"FTest\":\"2.4\",\"DBTest\":null,\"DETest\":null,\"TS\":0}]}"
                var o = SimpleJson.SerializeObject(fields);

                // we have to name the collection or the API will fail
                o = string.Format("{{ \"record\": [{0}] }}", o);

                // NOTE: We must use AddParameter here because we've already serialized the JSON.  AddBody attempts to serialize it again
                // At some point I want to fix RestSharp to not do this, as it's stupid behavior
                request.AddParameter("application/json", o, ParameterType.RequestBody);

                var response = Session.Client.Execute(request);

                switch (response.StatusCode)
                {
                case HttpStatusCode.Created:
                case HttpStatusCode.OK:
                    // the key for the inserted item gets returned (if there is one)
                    var pkJson = SimpleJson.DeserializeObject(response.Content) as JsonObject;
                    if (pkJson.Count == 0)
                    {
                        return(null);
                    }

                    var key = (pkJson[0] as JsonArray)[0] as JsonObject;
                    // no data sent back (i.e. there was no key field)
                    if (key == null)
                    {
                        return(null);
                    }

                    var name = key.Keys.First();
                    // no data sent back (i.e. there was no key field)
                    if (name.IsNullOrEmpty())
                    {
                        return(null);
                    }

                    var value = key[name];
                    return(value);

                case HttpStatusCode.InternalServerError:
                    var ex = DreamFactoryException.Parse(response);
                    if ((Session.ServerVersion == new Version("1.9.2")) && (ex.Message == "array (\n)"))
                    {
                        // this is an edge-case in DF 1.9.2 where a successful insert sometime will still return a 500 *even though* the record did insert.  WTF??
                        return(null);
                    }
                    throw ex;

                case HttpStatusCode.Forbidden:
                case HttpStatusCode.Unauthorized:
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }

                    Session.Disconnected = true;

                    throw DreamFactoryException.Parse(response);

                default:
                    throw DreamFactoryException.Parse(response);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #18
0
        public void DeleteRecords(params object[] resourceIDs)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), Method.DELETE);

            if ((resourceIDs != null) && (resourceIDs.Length > 0))
            {
                request.Parameters.Add(new Parameter()
                {
                    Name  = "ids",
                    Value = string.Join(",", resourceIDs.Select(i => i.ToString()).ToArray()),
                    Type  = ParameterType.GetOrPost
                });
            }
            else
            {
                // this is to delete all - we're setting up a "filter" that (hopefully) matches no record in the table
                if (KeyField != null)
                {
                    request.Parameters.Add(new Parameter()
                    {
                        Name  = "filter",
                        Value = string.Format("{0}!='fOObARbAZ'", KeyField.Name),
                        Type  = ParameterType.GetOrPost
                    });
                }
                else
                {
                    request.Parameters.Add(new Parameter()
                    {
                        Name  = "filter",
                        Value = string.Format("{0}!='fOObARbAZ'", Fields[0].Name),
                        Type  = ParameterType.GetOrPost
                    });
                }
            }

            var response = Session.Client.Execute(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                return;

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }
Example #19
0
File: Session.cs Project: fkdl/orm
        public void Initialize()
        {
//            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

            Client = new RestClient(DSPRootAddress);
            var request = new RestRequest("/rest/user/session", Method.POST);

            request.AddHeader("X-DreamFactory-Application-Name", ApplicationName);
            request.RequestFormat = DataFormat.Json;
            var creds = new CredentialDescriptor
            {
                email    = Username,
                password = Password
            };

            request.AddBody(creds);

            if (EnableCompressedResponseData)
            {
                request.AcceptDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;
            }
            else
            {
                request.AcceptDecompression = DecompressionMethods.None;
            }

            var response = Client.Execute <SessionDescriptor>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to deserialize the Session descriptor: {0}", check.Message), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.Created:
            case HttpStatusCode.OK:
                // successful session opened
                Disconnected = false;
                break;

            default:
                throw DreamFactoryException.Parse(response);
            }

            SessionDescriptor = response.Data;

            // TODO: set some properties that might be of interest

            // get the server version
            ConfigDescriptor = GetSystemConfig();
            ServerVersion    = new Version(ConfigDescriptor.dsp_version);

            if (Data == null)
            {
                Data = new Data(this);
            }
            if (Applications == null)
            {
                Applications = new Applications(this);
            }
        }
Example #20
0
        public IEnumerable <object[]> GetRecords(string filterStatement, params object[] resourceIDs)
        {
            if (Session.Disconnected)
            {
                Session.Reconnect();
            }

            var request = Session.GetSessionRequest(string.Format("/rest/db/{0}", Name), Method.GET);

            if ((resourceIDs != null) && (resourceIDs.Length > 0))
            {
                request.Parameters.Add(new Parameter()
                {
                    Name  = "ids",
                    Value = string.Join(",", resourceIDs.Select(i => i.ToString()).ToArray()),
                    Type  = ParameterType.GetOrPost
                });
            }
            if (!filterStatement.IsNullOrEmpty())
            {
                request.Parameters.Add(new Parameter()
                {
                    Name  = "filter",
                    Value = filterStatement,
                    Type  = ParameterType.GetOrPost
                });
            }

            var response = Session.Client.Execute <ResourceDescriptorList>(request);

            var check = DreamFactoryException.ValidateIRestResponse(response);

            if (check != null)
            {
                throw new DeserializationException(string.Format("Failed to retrieve a records from table '{0}': {1}", Name, response.ErrorMessage), check);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:

                JsonObject results = SimpleJson.DeserializeObject <JsonObject>(response.Content);

                var records = new List <object[]>();

                if (results.Count != 0)
                {
                    // {"record":["Could not find record for id = '9'"]}
                    var jarray = results["record"] as JsonArray;

                    if (jarray.Count > 0)
                    {
                        if (jarray[0] as JsonObject == null)
                        {
                            Debug.WriteLine("No results");
                            return(records);
                        }

                        foreach (JsonObject item in jarray)
                        {
                            var array = new object[Fields.Length];
                            var index = 0;

                            foreach (var field in Fields)
                            {
                                array[index++] = item[field.Name];
                            }

                            records.Add(array);
                        }
                    }
                }
                return(records);

            case HttpStatusCode.Forbidden:
            case HttpStatusCode.Unauthorized:
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Session.Disconnected = true;

                throw DreamFactoryException.Parse(response);

            default:
                throw DreamFactoryException.Parse(response);
            }
        }