// ************************************************************************************* //
        //This function is used by all the API Functions to call the API
        // ************************************************************************************* //

        public async Task <MakeRequestResponse> MakeRequest(String method, string serviceCall, ApiRequest ApiRequest, bool isDownload = false, string downloadFolderPath = "")
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    //Authentication & Authorization
                    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", this.ApiSettings.ApiKey);
                    // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.Token);

                    HttpResponseMessage result = new HttpResponseMessage();

                    //Making the request depending on which type of request( multipart/form-data or application/json )
                    //Only UploadFile uses multipart/form-data

                    if (serviceCall == "UploadFile")
                    {
                        //Turn the ApiRequest into an UploadApiRequest
                        string           tempString = JsonConvert.SerializeObject(ApiRequest);
                        UploadApiRequest apiReq     = JsonConvert.DeserializeObject <UploadApiRequest>(tempString);
                        //The API main link ( ex: http://localhost:5001/REALvision/ )
                        client.BaseAddress = new Uri(this.ApiSettings.ApiUrl);
                        //Initializing the multipart Http request entity
                        MultipartFormDataContent multipartRequest = new MultipartFormDataContent();

                        //Adding details to the request like the filename and the file itself
                        HttpContent FileNameContent = new StringContent(apiReq.FileName);
                        HttpContent stlFileContent  = new ByteArrayContent(apiReq.File);

                        multipartRequest.Add(FileNameContent, "FileName");
                        multipartRequest.Add(stlFileContent, "file", apiReq.FileName);

                        try
                        {
                            result = client.PostAsync("UploadFile", multipartRequest).Result;
                        }
                        catch (HttpRequestException e)
                        {
                            Console.WriteLine("Error while uploading file  ... ");
                            throw e;
                        }

                        Console.WriteLine("*************************************************************************");

                        //Logging the results of the request
                        this.logResponse(result, serviceCall, false);

                        if (result.IsSuccessStatusCode)
                        {
                            string uploadFileResponseString = await result.Content.ReadAsStringAsync();

                            FileIdResponse uploadFileResponse = JsonConvert.DeserializeObject <FileIdResponse>(uploadFileResponseString);
                            return(new MakeRequestResponse(result.StatusCode, uploadFileResponse.Result.FileId));
                        }
                        else
                        {
                            string errorResponseString = await result.Content.ReadAsStringAsync();

                            //ApiErrorResponse errorResponse = JsonConvert.DeserializeObject<ApiErrorResponse>(errorResponseString);

                            return(new MakeRequestResponse(result.StatusCode, errorResponseString));
                        }
                    }
                    else
                    {
                        string downloadFileName = "";
                        //Turn the ApiRequest into an UploadApiRequest
                        string tempString = JsonConvert.SerializeObject(ApiRequest);
                        //We use the string for the HTTP request
                        if (method == "GET")
                        {
                            result = client.GetAsync(this.ApiSettings.ApiUrl + serviceCall).Result;
                        }
                        else
                        {
                            result = client.PostAsync(this.ApiSettings.ApiUrl + serviceCall, new StringContent(tempString, Encoding.UTF8, "application/json")).Result;
                        }

                        if (result.IsSuccessStatusCode)
                        {
                            //Reading the response as a string
                            var response = await result.Content.ReadAsStringAsync();

                            if (!isDownload)
                            {
                                this.logResponse(result, serviceCall, false);

                                switch (serviceCall)
                                {
                                case "GetActivationStatus":
                                    ActivationStatusResponse resp = JsonConvert.DeserializeObject <ActivationStatusResponse>(response);
                                    return(new MakeRequestResponse(result.StatusCode, resp.Result.Activated));

                                case "StartSlicingTask":
                                    TaskIdResponse startSlicingTaskResponse = JsonConvert.DeserializeObject <TaskIdResponse>(response);
                                    return(new MakeRequestResponse(result.StatusCode, startSlicingTaskResponse.Result.TaskId));

                                case "GetProgress":
                                    ProgressResponse responseObject = JsonConvert.DeserializeObject <ProgressResponse>(response);
                                    return(new MakeRequestResponse(result.StatusCode, responseObject.Result.Progress));

                                case "GetPrintingInformation":
                                    PrintingInformationResponse printingInformationResponse = JsonConvert.DeserializeObject <PrintingInformationResponse>(response);
                                    return(new MakeRequestResponse(result.StatusCode, JsonConvert.SerializeObject(printingInformationResponse.Result)));

                                default:
                                    return(new MakeRequestResponse(result.StatusCode, "Service call could not be found."));
                                }
                            }
                            else
                            {
                                this.logResponse(result, serviceCall, isDownload, downloadFolderPath + downloadFileName);

                                downloadFileName = result.Content.Headers.ContentDisposition.FileName;
                                SaveFile(response, Path.GetFileNameWithoutExtension(downloadFileName), Path.GetExtension(downloadFileName), downloadFolderPath);

                                return(new MakeRequestResponse(result.StatusCode, response));
                            }
                        }
                        else
                        {
                            string errorResponseString = await result.Content.ReadAsStringAsync();

                            ApiErrorResponse errorResponse = JsonConvert.DeserializeObject <ApiErrorResponse>(errorResponseString);

                            throw new Exception(errorResponse.Error.ErrorMessage);
                        }
                    }
                }
                catch (WebException e)
                {
                    throw e;
                }
            }
        }
Exemplo n.º 2
0
        // ************************************************************************************* //
        //This function is used by all the API Functions to call the API
        // ************************************************************************************* //

        public async Task <String> MakeRequest(HttpMethod method, String serviceCall, ApiRequest ApiRequest, bool isDownload = false)
        {
            using (HttpClient client = new HttpClient())
            {
                String FinalResponse = "";

                string json = JsonConvert.SerializeObject(ApiRequest, Formatting.Indented);

                //Preparing request
                HttpRequestMessage req = new HttpRequestMessage();
                req.RequestUri = new Uri(this.ApiSettings.ApiUrl + serviceCall);
                req.Method     = method;
                req.Content    = new StringContent(json, Encoding.UTF8, "application/json");
                //Authentication & Authorization
                req.Headers.Add("Ocp-Apim-Subscription-Key", this.ApiSettings.ApiKey);

                //Making the request
                var result = await client.SendAsync(req);

                //Reading the response as a string
                var response = await result.Content.ReadAsStringAsync();

                if (!result.IsSuccessStatusCode)
                {
                    logResponse(result, serviceCall, false);
                    throw new Exception("Request unsuccessful.");
                }

                //Serializing the response depeding on which endpoint was called
                if (!isDownload)
                {
                    if (serviceCall == "ProvideFile")
                    {
                        TaskIdResponse responseObject = JsonConvert.DeserializeObject <TaskIdResponse>(response);
                        FinalResponse = responseObject.Result.TaskId;
                    }
                    else if (serviceCall == "GetProgress")
                    {
                        ProgressResponse responseObject = JsonConvert.DeserializeObject <ProgressResponse>(response);
                        FinalResponse = "" + responseObject.Result.Progress;
                    }
                    else if (serviceCall == "GetPrintingInformation")
                    {
                        PrintingInformationResponse responseObject = JsonConvert.DeserializeObject <PrintingInformationResponse>(response);
                        FinalResponse = JsonConvert.SerializeObject(responseObject.Result);
                    }
                    else
                    {
                        TaskIdResponse responseObject = JsonConvert.DeserializeObject <TaskIdResponse>(response);
                        FinalResponse = responseObject.Result.TaskId;
                    }
                }
                else
                {
                    string fullFilename          = result.Content.Headers.ContentDisposition.FileName;
                    string extentionlessFilename = Path.GetFileNameWithoutExtension(fullFilename);
                    string extention             = Path.GetExtension(fullFilename);

                    SaveFile(response, extentionlessFilename, extention);
                    FinalResponse = response;
                }

                //Logging the results of the request
                this.logResponse(result, serviceCall, isDownload);

                return(FinalResponse);
            }
        }