private void parseRepositoryDirectory(JSONResponse jresponse, ref RRepositoryDirectoryDetails directoryDetails)
        {
            Boolean systemDirectory      = default(Boolean);
            List <RRepositoryFile> files = new List <RRepositoryFile>();

            JObject jdir = jresponse.JSONMarkup;

            if (!(jdir == null))
            {
                String name = JSONUtilities.trimXtraQuotes(jdir["directory"].ToString());
                if ((name == Constants.SYSTEM_SHARED) || (name == Constants.SYSTEM_RESTRICTED) || (name == Constants.SYSTEM_PUBLIC))
                {
                    systemDirectory = true;
                }
                else
                {
                    systemDirectory = false;
                }

                if (!(jdir["files"] == null))
                {
                    JArray jvalues = jdir["files"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            RRepositoryFile file = new RRepositoryFile(new JSONResponse(j.Value <JObject>(), true, "", 0), m_client);
                            files.Add(file);
                        }
                    }
                }

                directoryDetails = new RRepositoryDirectoryDetails(name, systemDirectory, files);
            }
        }
        static public List <RData> getObject(RProjectDetails details, List <String> objectNames, Boolean encodeDataFramePrimitiveAsVector, RClient client, String uri)
        {
            StringBuilder data = new StringBuilder();

            //create the input String
            data.Append(Constants.FORMAT_JSON);
            data.Append("&project=" + HttpUtility.UrlEncode(details.id));
            if (!(objectNames == null))
            {
                if (objectNames.Count > 0)
                {
                    data.Append("&name=");
                    foreach (var s in objectNames)
                    {
                        data.Append(HttpUtility.UrlEncode(s) + ",");
                    }
                    data.Remove(data.Length - 1, 1);
                }
            }
            data.Append("&encodeDataFramePrimitiveAsVector=" + encodeDataFramePrimitiveAsVector.ToString());

            //call the server
            JSONResponse jresponse = HTTPUtilities.callRESTGet(uri, data.ToString(), ref client);

            List <RData> returnValue = new List <RData>();

            returnValue = JSONUtilities.parseRObjects(jresponse.JSONMarkup);

            return(returnValue);
        }
Exemple #3
0
 static public void parseConsole(JSONResponse jresponse, ref String console)
 {
     if (!(jresponse.JSONMarkup["execution"] == null))
     {
         JObject jscriptexec = jresponse.JSONMarkup["execution"].Value <JObject>();
         console = JSONUtilities.trimXtraQuotes(jscriptexec["console"].Value <string>());
     }
 }
        private void parseRepositoryScript(JSONResponse jresponse, ref RRepositoryScriptDetails scriptDetails)
        {
            List <Dictionary <String, String> > inputs  = new List <Dictionary <String, String> >();
            List <Dictionary <String, String> > outputs = new List <Dictionary <String, String> >();
            Dictionary <String, String>         dic     = new Dictionary <String, String>();

            JObject jscript = jresponse.JSONMarkup;

            if (!(jscript == null))
            {
                String name  = JSONUtilities.trimXtraQuotes(jscript["name"].Value <string>());
                String descr = JSONUtilities.trimXtraQuotes(jscript["descr"].Value <string>());

                if (!(jscript["inputs"] == null))
                {
                    JArray jvalues = jscript["inputs"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            dic = new Dictionary <String, String>();
                            dic.Add("name", JSONUtilities.trimXtraQuotes(j["name"].Value <String>()));
                            dic.Add("rclass", JSONUtilities.trimXtraQuotes(j["rclass"].Value <String>()));
                            dic.Add("descr", JSONUtilities.trimXtraQuotes(j["descr"].Value <String>()));
                            dic.Add("type", JSONUtilities.trimXtraQuotes(j["type"].Value <String>()));
                            inputs.Add(dic);
                        }
                    }
                }

                if (!(jscript["outputs"] == null))
                {
                    JArray jvalues = jscript["outputs"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            dic = new Dictionary <String, String>();
                            dic.Add("name", JSONUtilities.trimXtraQuotes(j["name"].Value <String>()));
                            dic.Add("rclass", JSONUtilities.trimXtraQuotes(j["rclass"].Value <String>()));
                            dic.Add("descr", JSONUtilities.trimXtraQuotes(j["descr"].Value <String>()));
                            dic.Add("type", JSONUtilities.trimXtraQuotes(j["type"].Value <String>()));
                            outputs.Add(dic);
                        }
                    }
                }

                scriptDetails = new RRepositoryScriptDetails(descr, inputs, name, outputs);
            }
        }
        private void parseProjectResult(JSONResponse jresponse, ref RProjectResultDetails resultDetails)
        {
            JObject jresult = jresponse.JSONMarkup;

            if (!(jresult == null))
            {
                String execution = JSONUtilities.trimXtraQuotes(jresult["execution"].Value <string>());
                String name      = JSONUtilities.trimXtraQuotes(jresult["filename"].Value <string>());
                int    size      = jresult["length"].Value <int>();
                String type      = JSONUtilities.trimXtraQuotes(jresult["type"].Value <string>());
                String url       = JSONUtilities.trimXtraQuotes(jresult["url"].Value <string>());

                resultDetails = new RProjectResultDetails(execution, name, size, type, url);
            }
        }
        private void parseProjectPackage(JSONResponse jresponse, ref RProjectPackageDetails packageDetails)
        {
            JObject jprojectfile = jresponse.JSONMarkup;

            if (!(jprojectfile == null))
            {
                String  descr    = JSONUtilities.trimXtraQuotes(jprojectfile["descr"].Value <String>());
                String  name     = JSONUtilities.trimXtraQuotes(jprojectfile["name"].Value <String>());
                String  repo     = JSONUtilities.trimXtraQuotes(jprojectfile["repo"].Value <String>());
                String  status   = JSONUtilities.trimXtraQuotes(jprojectfile["status"].Value <String>());
                String  version  = JSONUtilities.trimXtraQuotes(jprojectfile["version"].Value <String>());
                Boolean attached = jprojectfile["attached"].Value <Boolean>();

                packageDetails = new RProjectPackageDetails(descr, name, repo, status, version, attached);
            }
        }
Exemple #7
0
        private void parseProjectFile(JSONResponse jresponse, ref RProjectFileDetails fileDetails)
        {
            JObject jprojectfile = jresponse.JSONMarkup;

            if (!(jprojectfile == null))
            {
                String descr    = JSONUtilities.trimXtraQuotes(jprojectfile["descr"].Value <String>());
                String name     = JSONUtilities.trimXtraQuotes(jprojectfile["filename"].Value <String>());
                int    size     = jprojectfile["length"].Value <int>();
                String type     = JSONUtilities.trimXtraQuotes(jprojectfile["type"].Value <String>());
                String url      = JSONUtilities.trimXtraQuotes(jprojectfile["url"].Value <String>());
                String category = JSONUtilities.trimXtraQuotes(jprojectfile["category"].Value <String>());

                fileDetails = new RProjectFileDetails(descr, name, size, type, url, category);
            }
        }
Exemple #8
0
        private void parseJob(JSONResponse jresponse, ref RJobDetails jobDetails)
        {
            String  descr         = "";
            String  id            = "";
            String  name          = "";
            int     onrepeat      = 0;
            String  project       = "";
            long    schedinterval = 0;
            int     schedrepeat   = 0;
            long    schedstart    = 0;
            String  status        = "";
            String  statusMsg     = "";
            long    timeStart     = 0;
            long    timeCode      = 0;
            long    timeTotal     = 0;
            String  tag           = "";
            JObject jjob          = default(JObject);

            if (jresponse.JSONMarkup["job"].Type == JTokenType.Object)
            {
                jjob = jresponse.JSONMarkup["job"].Value <JObject>();
            }
            else
            {
                jjob = jresponse.JSONMarkup;
            }
            if (!(jjob == null))
            {
                descr         = JSONUtilities.trimXtraQuotes(jjob["descr"].Value <String>());
                id            = JSONUtilities.trimXtraQuotes(jjob["job"].Value <String>());
                name          = JSONUtilities.trimXtraQuotes(jjob["name"].Value <String>());
                onrepeat      = Convert.ToInt32(jjob["onrepeat"].Value <String>());
                project       = JSONUtilities.trimXtraQuotes(jjob["project"].Value <String>());
                schedinterval = Convert.ToInt64(jjob["schedinterval"].Value <String>());
                schedrepeat   = Convert.ToInt32(jjob["schedrepeat"].Value <String>());
                schedstart    = Convert.ToInt64(jjob["schedstart"].Value <String>());
                status        = JSONUtilities.trimXtraQuotes(jjob["status"].Value <String>());
                statusMsg     = JSONUtilities.trimXtraQuotes(jjob["statusMsg"].Value <String>());
                timeStart     = Convert.ToInt64(jjob["timeStart"].Value <String>());
                timeCode      = Convert.ToInt64(jjob["timeCode"].Value <String>());
                timeTotal     = Convert.ToInt64(jjob["timeTotal"].Value <String>());
                tag           = JSONUtilities.trimXtraQuotes(jjob["tag"].Value <String>());

                jobDetails = new RJobDetails(descr, id, name, onrepeat, project, schedinterval, schedrepeat, schedstart, status, statusMsg, timeStart, timeCode, timeTotal, tag);
            }
        }
        private void parseUser(JSONResponse jresponse, ref RUserDetails userDetails)
        {
            RUserLimitDetails limitDetails = null;

            if (!(jresponse.JSONMarkup["user"] == null))
            {
                JObject juser = jresponse.JSONMarkup["user"].Value <JObject>();

                String  username    = JSONUtilities.trimXtraQuotes(juser["username"].Value <String>());
                String  displayname = JSONUtilities.trimXtraQuotes(juser["displayname"].Value <String>());
                String  cookie      = JSONUtilities.trimXtraQuotes(juser["cookie"].Value <String>());
                JObject jlimits     = jresponse.JSONMarkup["limits"].Value <JObject>();
                parseLimits(jlimits, ref limitDetails);

                userDetails = new RUserDetails(username, displayname, cookie, limitDetails);
            }
        }
        /// <summary>
        /// Create an RData object from a json.net JObject referenceing some JSON markup
        /// </summary>
        /// <param name="jobject">JObject containing JSON markup</param>
        /// <param name="jparent">Parent object (JProperty, JObject, JArray)</param>
        /// <returns>RData object</returns>
        /// <remarks></remarks>
        public static RData parseRObject(JToken jobject, JToken jparent)
        {
            String type   = JSONUtilities.trimXtraQuotes(jparent["type"].Value <string>());
            String rclass = JSONUtilities.trimXtraQuotes(jparent["rclass"].Value <string>());
            String name   = System.Convert.ToString(jobject.Value <JObject>().Property("Key"));

            RData data = checkEmptyValue(jparent, type, rclass, name);

            if (data == null)
            {
                if (type == Constants.TYPE_MATRIX)
                {
                    data = parseMatrix(name, jobject);
                }
                else if (type == Constants.TYPE_VECTOR)
                {
                    data = parseVector(name, jobject, rclass);
                }
                else if (type == Constants.TYPE_PRIMITIVE)
                {
                    data = parsePrimitive(name, jobject);
                }
                else if (type == Constants.TYPE_DATE)
                {
                    data = parseDate(name, jobject);
                }
                else if (type == Constants.TYPE_FACTOR)
                {
                    data = parseFactor(name, jobject);
                }
                else if (type == Constants.TYPE_DATAFRAME)
                {
                    data = parseDataFrame(name, jobject);
                }
                else if (type == Constants.TYPE_LIST)
                {
                    data = parseRList(name, jobject);
                }
            }

            return(data);
        }
Exemple #11
0
        static public void parseProject(JSONResponse jresponse, ref RProjectDetails projectDetails)
        {
            List <String> authors  = new List <String>();
            JObject       jproject = default(JObject);

            if (jresponse.JSONMarkup["project"].Type == JTokenType.Object)
            {
                jproject = jresponse.JSONMarkup["project"].Value <JObject>();
            }
            else
            {
                jproject = jresponse.JSONMarkup;
            }
            if (!(jproject == null))
            {
                String  cookie      = JSONUtilities.trimXtraQuotes(jproject["cookie"].Value <string>());
                String  descr       = JSONUtilities.trimXtraQuotes(jproject["descr"].Value <string>());
                String  id          = JSONUtilities.trimXtraQuotes(jproject["project"].Value <string>());
                Boolean live        = jproject["live"].Value <bool>();
                Boolean sharedUsers = jproject["shared"].Value <bool>();
                String  longdescr   = JSONUtilities.trimXtraQuotes(jproject["longdescr"].Value <string>());
                String  modified    = JSONUtilities.trimXtraQuotes(jproject["lastmodified"].Value <string>());
                String  name        = JSONUtilities.trimXtraQuotes(jproject["name"].Value <string>());
                String  origin      = JSONUtilities.trimXtraQuotes(jproject["origin"].Value <string>());

                if (!(jproject["authors"] == null))
                {
                    JArray jvalues = jproject["authors"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            authors.Add(j.Value <String>());
                        }
                    }
                }

                projectDetails = new RProjectDetails(cookie, descr, id, live, longdescr, modified, name, origin, sharedUsers, authors);
            }
        }
        static public List <RData> listObjects(RProjectDetails details, ProjectWorkspaceOptions options, RClient client, String uri)
        {
            StringBuilder data = new StringBuilder();

            //create the input String
            data.Append(Constants.FORMAT_JSON);
            data.Append("&project=" + HttpUtility.UrlEncode(details.id));
            if (!(options == null))
            {
                data.Append("&root=" + HttpUtility.UrlEncode(options.alternateRoot));
                data.Append("&filter=" + HttpUtility.UrlEncode(options.startsWithFilter));
                data.Append("&clazz=" + HttpUtility.UrlEncode(options.classFilter));
                data.Append("&pagesize=" + options.pagesize.ToString());
                data.Append("&pageoffset=" + options.pageoffset.ToString());
            }

            //call the server
            JSONResponse jresponse = HTTPUtilities.callRESTGet(uri, data.ToString(), ref client);

            List <RData> returnValue = JSONUtilities.parseRObjects(jresponse.JSONMarkup);


            return(returnValue);
        }
Exemple #13
0
        /// <summary>
        /// Make an HTTP GET request on one of the DeployR APIs
        /// </summary>
        /// <param name="uri">Base URL of the DeployR server</param>
        /// <param name="data">The data to send on the HTTP GET call</param>
        /// <param name="client">reference to the RClient calling this function</param>
        /// <returns>JSONResponse object</returns>
        /// <remarks></remarks>
        public static JSONResponse callRESTGet(String uri, String data, ref RClient client)
        {
            HttpWebResponse response     = null;
            StreamReader    reader       = default(StreamReader);
            String          responseText = "";
            String          address      = client.URL + uri;

            //setup callback for SSL/HTTPS validation
            //setup callback for SSL/HTTPS validation
            if (client.allowSelfSignedSSLCert == true)
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            }

            // Create the web request
            String         url     = address + "?" + data;
            HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(url));

            request.Timeout = HTTP_TIMEOUT;

            // Set the cookie
            CookieContainer cookieJar = new CookieContainer();

            if (!(client.Cookie == null))
            {
                cookieJar.Add(client.Cookie);
            }

            // Set type to POST
            request.Method          = "GET";
            request.ContentType     = "application/x-www-form-urlencoded";
            request.CookieContainer = cookieJar;

            if (HTTPUtilities.DEBUGMODE == true)
            {
                Console.WriteLine("\r\n" + request.Method + "  " + request.Address.AbsoluteUri);
                if (!(client.Cookie == null))
                {
                    Console.WriteLine(client.Cookie.Name + "=" + client.Cookie.Value);
                }
                Console.WriteLine(data);
            }

            try
            {
                // Get response
                response = (HttpWebResponse)(request.GetResponse());
                // Save the cookie (if there is one)
                if (response.Cookies.Count > 0)
                {
                    client.Cookie = response.Cookies[0];
                }

                // Get the response stream into a reader
                reader = new StreamReader(response.GetResponseStream());

                responseText = reader.ReadToEnd();

                if (HTTPUtilities.DEBUGMODE == true)
                {
                    Console.WriteLine(responseText);
                }
            }
            finally
            {
                if (!(response == null))
                {
                    response.Close();
                }
            }

            //return a JSON response
            JSONResponse returnValue = JSONUtilities.checkForSuccess(responseText);

            //throw an exception if the call failed
            if (returnValue.Success == false)
            {
                HTTPRestException e = new HTTPRestException(returnValue.ErrorMsg, returnValue.Console, returnValue.ErrorCode);
                throw (e);
            }

            return(returnValue);
        }
        private void parseRepositoryFile(JSONResponse jresponse, ref RRepositoryFileDetails fileDetails)
        {
            List <String> authors = new List <String>();

            JObject jfile = jresponse.JSONMarkup;

            if (!(jfile == null))
            {
                String  category     = JSONUtilities.trimXtraQuotes(jfile["category"].Value <string>());
                String  filename     = JSONUtilities.trimXtraQuotes(jfile["filename"].Value <string>());
                String  author       = JSONUtilities.trimXtraQuotes(jfile["author"].Value <string>());
                int     length       = jfile["length"].Value <int>();
                String  type         = JSONUtilities.trimXtraQuotes(jfile["type"].Value <string>());
                String  url          = JSONUtilities.trimXtraQuotes(jfile["url"].Value <string>());
                String  latestby     = JSONUtilities.trimXtraQuotes(jfile["latestby"].Value <string>());
                String  lastModified = JSONUtilities.trimXtraQuotes(jfile["lastModified"].Value <string>());
                Boolean sharedUsers  = jfile["shared"].Value <Boolean>();
                Boolean published    = jfile["published"].Value <Boolean>();
                String  restricted   = JSONUtilities.trimXtraQuotes(jfile["restricted"].Value <string>());
                String  access       = JSONUtilities.trimXtraQuotes(jfile["access"].Value <string>());
                String  directory    = JSONUtilities.trimXtraQuotes(jfile["directory"].Value <string>());
                String  inputs       = "";
                if (!(jfile["inputs"] == null))
                {
                    inputs = JSONUtilities.trimXtraQuotes(jfile["inputs"].Value <string>());
                }
                String outputs = "";
                if (!(jfile["outputs"] == null))
                {
                    outputs = JSONUtilities.trimXtraQuotes(jfile["outputs"].Value <string>());
                }
                String version = JSONUtilities.trimXtraQuotes(jfile["version"].Value <string>());
                if (version == "null")
                {
                    version = "";
                }

                if (!(jfile["authors"] == null))
                {
                    JArray jvalues = jfile["authors"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            authors.Add(j.Value <string>());
                        }
                    }
                }

                fileDetails = new RRepositoryFileDetails(category,
                                                         filename,
                                                         author,
                                                         version,
                                                         latestby,
                                                         lastModified,
                                                         length,
                                                         type,
                                                         url,
                                                         sharedUsers,
                                                         published,
                                                         restricted,
                                                         access,
                                                         authors,
                                                         inputs,
                                                         outputs,
                                                         directory);
            }
        }
Exemple #15
0
        /// <summary>
        /// Make an HTTP POST request on one of the DeployR APIs
        /// </summary>
        /// <param name="uri">Base URL of the DeployR server</param>
        /// <param name="data">The data to send on the HTTP POST call</param>
        /// <param name="client">reference to the RClient calling this function</param>
        /// <returns>JSONResponse object</returns>
        /// <remarks></remarks>
        public static JSONResponse callRESTPost(String uri, String data, ref RClient client)
        {
            HttpWebResponse response     = null;
            Stream          postStream   = null;
            String          responseText = "";
            String          address      = client.URL + uri;

            //setup callback for SSL/HTTPS validation
            if (client.allowSelfSignedSSLCert == true)
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            }

            // Create the web request
            HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(address));

            request.Timeout = HTTP_TIMEOUT;

            // Set the cookie
            CookieContainer cookieJar = new CookieContainer();

            if (!(client.Cookie == null))
            {
                cookieJar.Add(client.Cookie);
            }

            // Set the X-XSRF-TOKEN header
            if (!(client.XSRFHeader == null))
            {
                request.Headers.Add("X-XSRF-TOKEN", client.XSRFHeader);
            }

            // Set type to POST
            request.Method          = "POST";
            request.ContentType     = "application/x-www-form-urlencoded";
            request.CookieContainer = cookieJar;

            // Create a byte array of the data we want to send
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            // Set the content length in the request headers
            request.ContentLength = byteData.Length;

            if (HTTPUtilities.DEBUGMODE == true)
            {
                Console.WriteLine("\r\n" + request.Method + "  " + request.Address.AbsoluteUri);
                if (!(client.Cookie == null))
                {
                    Console.WriteLine(client.Cookie.Name + "=" + client.Cookie.Value);
                }
                Console.WriteLine(data);
            }

            // Write data
            try
            {
                postStream = request.GetRequestStream();
                postStream.Write(byteData, 0, byteData.Length);
            }
            finally
            {
                if (!(postStream == null))
                {
                    postStream.Close();
                }
            }
            try
            {
                // Get response
                response = (HttpWebResponse)(request.GetResponse());
                // Save the cookie (if there is one)
                if (response.Cookies.Count > 0)
                {
                    client.Cookie = response.Cookies[0];
                }

                // Save the X-XSRF-TOKEN header (if there is one)
                if (response.Headers.Count > 0)
                {
                    client.XSRFHeader = response.Headers.Get("X-XSRF-TOKEN");
                }

                // Get the response stream into a reader
                StreamReader reader = new StreamReader(response.GetResponseStream());

                responseText = reader.ReadToEnd();

                if (HTTPUtilities.DEBUGMODE == true)
                {
                    Console.WriteLine(responseText);
                }
            }
            finally
            {
                if (!(response == null))
                {
                    response.Close();
                }
            }

            //return a JSON response
            JSONResponse returnValue = JSONUtilities.checkForSuccess(responseText);

            //throw an exception if the call failed
            if (returnValue.Success == false)
            {
                HTTPRestException e = new HTTPRestException(returnValue.ErrorMsg, returnValue.Console, returnValue.ErrorCode);
                throw (e);
            }

            return(returnValue);
        }
Exemple #16
0
        /// <summary>
        /// A function to handle a mulitp-part HTTP POST that includes a file upload
        /// </summary>
        /// <param name="uri">Base URL of the DeployR server</param>
        /// <param name="parameters">Dictionary of form parameters to send with the POST</param>
        /// <param name="path">Fully qualified path to file to upload</param>
        /// <param name="client">reference to the RClient calling this function</param>
        /// <returns>JSONResponse object</returns>
        /// <remarks></remarks>
        public static JSONResponse callRESTFileUploadPost(String uri, Dictionary <String, String> parameters, String path, ref RClient client)
        {
            HttpWebResponse response     = null;
            Stream          postStream   = null;
            String          responseText = "";
            String          address      = client.URL + uri;

            //setup callback for SSL/HTTPS validation
            if (client.allowSelfSignedSSLCert == true)
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            }

            // Create the web request
            HttpWebRequest request = (HttpWebRequest)(WebRequest.Create(address));

            request.Timeout = HTTP_TIMEOUT;

            // Set the cookie
            CookieContainer cookieJar = new CookieContainer();

            if (!(client.Cookie == null))
            {
                cookieJar.Add(client.Cookie);
            }

            // Set the X-XSRF-TOKEN header
            if (!(client.XSRFHeader == null))
            {
                request.Headers.Add("X-XSRF-TOKEN", client.XSRFHeader);
            }

            // Set type to POST
            request.Method = "POST";
            //this is a multipart request, so we need a boundary and need to setup the proper ContentType
            String boundary = System.Guid.NewGuid().ToString();

            request.ContentType     = String.Format("multipart/form-data;boundary={0}", boundary);
            request.CookieContainer = cookieJar;

            //header and footer to be used for the boundary
            String header = String.Format("--{0}", boundary);
            String footer = header + "--";

            StringBuilder contents = new StringBuilder();

            //loop through the parameters in this POST call
            foreach (var param in parameters)
            {
                contents.Append(header);
                contents.Append("\r\n");
                contents.Append("Content-Disposition: form-data;name=\"" + param.Key + "\"" + "\r\n");
                contents.Append("\r\n");
                contents.Append(param.Value);
                contents.Append("\r\n");
            }

            //ok, here we do something special for the file we are going to upload
            contents.Append(header);
            contents.Append("\r\n");
            contents.Append("Content-Disposition:form-data;name=\"file\";filename=\"" + path + "\"" + "\r\n");
            contents.Append("Content-Type: application/octet-stream" + "\r\n");
            contents.Append("\r\n");

            //get all the various byte streams we need
            byte[] bodyBytes   = Encoding.UTF8.GetBytes(contents.ToString());
            byte[] fileData    = System.IO.File.ReadAllBytes(path);
            byte[] footerBytes = Encoding.UTF8.GetBytes("\r\n" + footer + "\r\n");

            // Set the content length in the request headers
            request.ContentLength = bodyBytes.Length + fileData.Length + footerBytes.Length;

            if (HTTPUtilities.DEBUGMODE == true)
            {
                Console.WriteLine("\r\n" + request.Method + "  " + request.Address.AbsoluteUri);
                if (!(client.Cookie == null))
                {
                    Console.WriteLine(client.Cookie.Name + "=" + client.Cookie.Value);
                }
                Console.Write(contents.ToString());
            }

            // Write data
            try
            {
                postStream = request.GetRequestStream();
                postStream.Write(bodyBytes, 0, bodyBytes.Length);
                postStream.Write(fileData, 0, fileData.Length);
                postStream.Write(footerBytes, 0, footerBytes.Length);
            }
            finally
            {
                if (!(postStream == null))
                {
                    postStream.Close();
                }
            }

            try
            {
                // Get response
                response = (HttpWebResponse)(request.GetResponse());
                // Save the cookie (if there is one)
                if (response.Cookies.Count > 0)
                {
                    client.Cookie = response.Cookies[0];
                }

                // Save the X-XSRF-TOKEN header (if there is one)
                if (response.Headers.Count > 0)
                {
                    client.XSRFHeader = response.Headers.Get("X-XSRF-TOKEN");
                }

                // Get the response stream into a reader
                StreamReader reader = new StreamReader(response.GetResponseStream());

                responseText = reader.ReadToEnd();

                if (HTTPUtilities.DEBUGMODE == true)
                {
                    Console.WriteLine(responseText);
                }
            }
            finally
            {
                if (!(response == null))
                {
                    response.Close();
                }
            }

            //return a JSON response
            JSONResponse returnValue = JSONUtilities.checkForSuccess(responseText);

            //throw an exception if the call failed
            if (returnValue.Success == false)
            {
                HTTPRestException e = new HTTPRestException(returnValue.ErrorMsg, returnValue.Console, returnValue.ErrorCode);
                throw (e);
            }

            return(returnValue);
        }
Exemple #17
0
        static public void parseProjectExecution(JSONResponse jresponse, ref RProjectExecutionDetails executionDetails, ref RProjectDetails projectDetails, RClient client)
        {
            List <RProjectFile>    projectfiles     = new List <RProjectFile>();
            List <RRepositoryFile> repositoryFiles  = new List <RRepositoryFile>();
            List <RProjectResult>  results          = new List <RProjectResult>();
            List <String>          warnings         = new List <String>();
            List <RData>           workspaceObjects = new List <RData>();
            JArray  jvalues;
            JObject jrepo;

            if (!(jresponse.JSONMarkup["execution"] == null))
            {
                JObject jscriptexec = jresponse.JSONMarkup["execution"].Value <JObject>();

                String  code        = JSONUtilities.trimXtraQuotes(jscriptexec["code"].Value <string>());
                long    timeStart   = jscriptexec["timeStart"].Value <long>();
                long    timeCode    = jscriptexec["timeCode"].Value <long>();
                long    timeTotal   = jscriptexec["timeTotal"].Value <long>();
                String  tag         = JSONUtilities.trimXtraQuotes(jscriptexec["tag"].Value <string>());
                String  console     = JSONUtilities.trimXtraQuotes(jscriptexec["console"].Value <string>());
                String  errorDescr  = jresponse.ErrorMsg;
                int     errorCode   = jresponse.ErrorCode;
                String  id          = JSONUtilities.trimXtraQuotes(jscriptexec["execution"].Value <string>());
                Boolean interrupted = Convert.ToBoolean(jscriptexec["interrupted"].Value <string>());

                if (!(jscriptexec["results"] == null))
                {
                    jvalues = jscriptexec["results"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            results.Add(new RProjectResult(new JSONResponse(j.Value <JObject>(), true, "", 0), client));
                        }
                    }
                }

                if (!(jscriptexec["artifacts"] == null))
                {
                    jvalues = jscriptexec["artifacts"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            projectfiles.Add(new RProjectFile(new JSONResponse(j.Value <JObject>(), true, "", 0), client, id));
                        }
                    }
                }

                if (!(jscriptexec["warnings"] == null))
                {
                    jvalues = jscriptexec["warnings"].Value <JArray>();
                    foreach (var j in jvalues)
                    {
                        if (j.Type != JTokenType.Null)
                        {
                            warnings.Add(j.Value <string>());
                        }
                    }
                }

                if (!(jscriptexec["repository"] == null))
                {
                    jrepo = jscriptexec["repository"].Value <JObject>();

                    if (!(jrepo["files"] == null))
                    {
                        jvalues = jrepo["files"].Value <JArray>();
                        foreach (var j in jvalues)
                        {
                            if (j.Type != JTokenType.Null)
                            {
                                repositoryFiles.Add(new RRepositoryFile(new JSONResponse(j.Value <JObject>(), true, "", 0), client));
                            }
                        }
                    }
                }

                workspaceObjects = JSONUtilities.parseRObjects(jresponse.JSONMarkup);
                parseProject(jresponse, ref projectDetails);

                executionDetails = new RProjectExecutionDetails(projectfiles, code, timeStart, timeCode, timeTotal, tag, console, errorDescr, errorCode, id, interrupted, null, results, warnings, workspaceObjects);
            }
        }