public AssetFile Download(ILeanKitAccountAuth accountAuth, string resource)
        {
            var request = WebRequest.Create(accountAuth.GetAccountUrl() + resource) as HttpWebRequest;

            if (request == null)
            {
                throw new Exception("Error downloading file. Could not create HttpWebRequest");
            }
            request.UserAgent = _leanKitUserAgent;
            AddAuth(request, accountAuth);

            var response = request.GetResponse() as HttpWebResponse;

            byte[] fileBytes;
            using (var responseStream = response.GetResponseStream())
            {
                var buffer = new byte[4096];
                using (var ms = new MemoryStream())
                {
                    int read;
                    while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    fileBytes = ms.ToArray();
                }
            }
            return(new AssetFile
            {
                FileBytes = fileBytes,
                ContentType = response.ContentType,
                ContentLength = response.ContentLength
            });
        }
        private static void ValidateResponse(IRestResponse <AsyncResponse> response,
                                             ILeanKitAccountAuth leanKitAccountAuth,
                                             IRestRequest request)
        {
            var requestedResource = GetRequestUri(leanKitAccountAuth.GetAccountUrl());

            var logAuthString = FormatApiRequestInfo(leanKitAccountAuth, request, true);

            if (response == null)
            {
                throw new LeanKitAPIException("A failure occurred retrieving the response from the API.");
            }

            if (response.ResponseUri != null && response.ResponseUri.Host != requestedResource.Host)
            {
                throw new InvalidAPIResourceException();
            }

            if (response.ResponseStatus == ResponseStatus.Error)
            {
                throw new LeanKitAPIException(response.ErrorException);
            }

            switch (response.StatusCode)
            {
            case HttpStatusCode.Unauthorized:
                throw new UnauthorizedAccessException(response.StatusDescription + ": " + logAuthString);
            }

            AsyncResponse responseData = response.Data;

            if (responseData == null)
            {
                throw new LeanKitAPIException("Unable to process the response from the API.");
            }

            switch ((ResponseCode)responseData.ReplyCode)
            {
            case ResponseCode.UnauthorizedAccess:
                throw new UnauthorizedAccessException(responseData.ReplyText + ": " + logAuthString);

            case ResponseCode.NoData:
                throw new NoDataException(responseData.ReplyText);

            case ResponseCode.FatalException:
            case ResponseCode.MinorException:
            case ResponseCode.UserException:
                throw new LeanKitAPIException(responseData.ReplyText, (ResponseCode)responseData.ReplyCode);
            }

            //check to make sure there is data
            if (string.IsNullOrEmpty(responseData.ReplyData))
            {
                throw new LeanKitAPIException(responseData.ReplyText + ": " + logAuthString, (ResponseCode)responseData.ReplyCode);
            }
        }
        private T Process <T>(ILeanKitAccountAuth accountAuth, IRestRequest request) where T : new()
        {
            var errorMessages = _validationService.ValidateRequest((RestRequest)request);

            if (errorMessages.Count > 0)
            {
                var ex = new ValidationException("Provided request parameters are invalid.");
                ex.Data["ErrorMessages"] = errorMessages;
                throw ex;
            }
            var client = new RestClient
            {
                BaseUrl       = new Uri(accountAuth.GetAccountUrl()),
                Authenticator = GetAuthenticator(accountAuth),
                UserAgent     = LeanKitUserAgent
            };

            var response = RetryRequest(request, accountAuth, client);

            var asyncResponse = response.Data;

            if (string.IsNullOrEmpty(asyncResponse.ReplyData))
            {
                return(new T());
            }
            var rawJson = asyncResponse.ReplyData;

            var authUserDateFormat = _settings.DateFormat;

            var isoDateTimeConverter = new IsoDateTimeConverter {
                DateTimeFormat = authUserDateFormat
            };

            rawJson = rawJson.Substring(1, rawJson.Length - 2);

            var retVal = JsonConvert.DeserializeObject <T>(rawJson, new JsonSerializerSettings
            {
                Error      = HandleError,
                Converters = { isoDateTimeConverter }
            });

            return(retVal);
        }
        public T PostFile <T>(ILeanKitAccountAuth accountAuth, string resource, Dictionary <string, object> parameters, string fileName, string mimeType, byte[] fileBytes) where T : new()
        {
            var boundary    = string.Format("----------{0:N}", Guid.NewGuid());
            var contentType = "multipart/form-data; boundary=" + boundary;
            var formBytes   = GetMultipartFormData(parameters, boundary, fileName, mimeType, fileBytes);

            var request = WebRequest.Create(accountAuth.GetAccountUrl() + resource) as HttpWebRequest;

            if (request == null)
            {
                throw new Exception("Error posting file. Could not create HttpWebRequest");
            }

            request.Method        = "POST";
            request.ContentType   = contentType;
            request.ContentLength = formBytes.Length;
            request.UserAgent     = _leanKitUserAgent;
            AddAuth(request, accountAuth);

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(formBytes, 0, formBytes.Length);
                requestStream.Close();
            }

            var response       = request.GetResponse() as HttpWebResponse;
            var responseStream = new StreamReader(response.GetResponseStream());
            var result         = responseStream.ReadToEnd();

            response.Close();

            //var task = PostFileAsync(accountAuth, resource, parameters, fileName, fileBytes);
            //var result = task.Result;

            if (string.IsNullOrEmpty(result))
            {
                return(new T());
            }
            var asyncResponse = JsonConvert.DeserializeObject <AsyncResponse2>(result);

            if (asyncResponse == null || asyncResponse.ReplyData == null || asyncResponse.ReplyData.Length == 0)
            {
                return(new T());
            }

            var rawJson = asyncResponse.ReplyData[0].ToString();

            if (string.IsNullOrEmpty(rawJson))
            {
                return(new T());
            }

            var authUserDateFormat = _settings.DateFormat + " hh:mm:ss t";

            var retVal = JsonConvert.DeserializeObject <T>(rawJson, new JsonSerializerSettings
            {
                Error            = HandleError,
                DateFormatString = authUserDateFormat
            });

            return(retVal);
        }