private string SetupJson(EngineDoc doc, string docName)
        {
            var item = new Itemobject();

            item.name                     = docName;
            item.resourceId               = doc.Attributes.AppId;
            item.resourceType             = doc.Attributes.Resourcetype;
            item.description              = doc.Attributes.Description;
            item.resourceCustomAttributes = new Resourcecustomattributes();
            item.resourceCreatedAt        = doc.Attributes.CreatedDate;
            item.resourceCreatedBySubject = doc.Attributes.Owner;
            item.resourceAttributes       = new Resourceattributes
            {
                id               = doc.Attributes.AppId,
                description      = doc.Attributes.Description,
                thumbnail        = doc.Attributes.Thumbnail,
                lastReloadTime   = doc.Attributes.LastReloadTime,
                createdDate      = doc.Attributes.CreatedDate,
                modifiedDate     = doc.Attributes.ModifiedDate,
                owner            = doc.Attributes.Owner,
                ownerId          = doc.Attributes.OwnerId,
                dynamicColor     = doc.Attributes.DynamicColor,
                published        = doc.Attributes.Published,
                publishTime      = doc.Attributes.PublishTime,
                hasSectionAccess = doc.Attributes.HasSectionAccess,
                encrypted        = doc.Attributes.Encrypted,
                originAppId      = doc.Attributes.OriginAppId,
                _resourcetype    = doc.Attributes.Resourcetype
            };
            var json = JsonConvert.SerializeObject(item, IgnoreNullSetting());

            return(json);
        }
        private async Task <CollectionEntity> CreateEngineItem(EngineDoc doc, string jwtToken, string multiCloudMachineName, string docName)
        {
            CollectionEntity result = null;

            try
            {
                result = await GetItem(jwtToken, multiCloudMachineName, doc.Attributes.AppId, "qvapp");

                if (result != null && result.Id != null)
                {
                    return(result);
                }

                string additionalUri = "items";
                string jsonRequest   = SetupJson(doc, docName);
                using (HttpResponseMessage createItemResponse = await SetupAndSendRequest(HttpMethod.Post, multiCloudMachineName + additionalUri, jsonRequest, jwtToken))
                {
                    if (createItemResponse != null && createItemResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        PrintMessage("Failure - Document could not be created. StatusCode= " + createItemResponse.StatusCode + ", reason= " + createItemResponse.ReasonPhrase, false);
                    }
                    var responseContent = await createItemResponse.Content.ReadAsStringAsync() ?? "{}";

                    result = JsonConvert.DeserializeObject <CollectionEntity>(responseContent);
                }
            }
            catch (Exception e)
            {
                PrintMessage("Failure - Could not create item for doc upload. Exception= " + e.Message, false);
            }
            return(result);
        }
        public async Task <string> DistributeDocumentsOrFiles(string fileNameAndPath, string cloudDeploymentResourceUrl, string sourceDocumentId, string jwtToken, string mode, string proxyName, string proxyPort, string appId = null)
        {
            PrintMessage("Deployment Name: " + cloudDeploymentResourceUrl, false);
            string multiCloudMachineName = cloudDeploymentResourceUrl.TrimEnd('/') + "/api/v1/";
            string responseContent;

            try
            {
                Assembly assembly  = Assembly.GetExecutingAssembly();
                string   version   = assembly.GetName().Version.ToString();
                var      tusClient = new TusClient(version);
                tusClient.AdditionalHeaders.Add("Authorization", "Bearer " + jwtToken);

                string url;
                using (var l_FileStream = new FileStream(fileNameAndPath, FileMode.Open, FileAccess.Read))
                {
                    url = await tusClient.CreateAsync(multiCloudMachineName + "temp-contents/files", l_FileStream.Length, this, proxyName, proxyPort);

                    int cloudChunkSize = 300;
                    PrintMessage("Upload file to Cloud - Chunk size set to " + cloudChunkSize, false);
                    await tusClient.UploadAsync(url, l_FileStream, cloudChunkSize, this, proxyName, proxyPort);
                }
                responseContent = await ImportApp(jwtToken, multiCloudMachineName, sourceDocumentId, fileNameAndPath, url, mode, appId, version);

                if (string.IsNullOrEmpty(responseContent))
                {
                    return(string.Empty);
                }

                EngineDoc result = JsonConvert.DeserializeObject <EngineDoc>(responseContent);

                CollectionEntity engineItem = await CreateEngineItem(result, jwtToken, multiCloudMachineName, Path.GetFileNameWithoutExtension(fileNameAndPath), version);

                if (engineItem == null)
                {
                    return(string.Empty);
                }
            }
            catch (HttpAppSizeException)
            {
                throw;
            }
            catch (WorkflowException)
            {
                throw;
            }
            catch (TaskCanceledException e)
            {
                PrintMessage("Failure - Could not upload document to engine, Connection timeout. Message =" + e.Message, false);
                throw new AppUploadTimeoutException("Client connection timeout.");
            }
            catch (Exception)
            {
                throw;
            }
            return(responseContent);
        }
Esempio n. 4
0
 public ItemRequestBody(EngineDoc doc)
 {
     Name                     = doc.Attributes.Name;
     Description              = "";
     ResourceId               = doc.Attributes.AppId;
     ResourceType             = ResourceType.Qlikview;
     ResourceCreatedBySubject = "";
     ResourceCreatedAt        = DateTime.Now;//In lack of real creation date
     ResourceUpdatedAt        = DateTime.Now;
     ResourceLink             = "";
     ResourceAttributes       = new Dictionary <string, object>();
     ResourceCustomAttributes = new Dictionary <string, object>();
     ThumbNail                = new Dictionary <string, object>();
     ThumbnailId              = "";
     ResourceUpdatedBySubject = "";
     SpaceId                  = "";
     AddThumbNail();
 }
        private async Task <HttpResponseMessage> CreateItem(EngineDoc doc, string jwtToken, string multiCloudMachineName, string docName)
        {
            string jsonRequest = SetupJson(doc, docName);

            using (HttpClient cloudClient = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, multiCloudMachineName + "items")
                {
                    Content = new StringContent(jsonRequest, Encoding.UTF8, "application/json")
                };

                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
                HttpResponseMessage createItemResponse = await cloudClient.SendAsync(request);

                var responseContent = await createItemResponse.Content.ReadAsStringAsync() ?? "{}";

                return(createItemResponse);
            }
        }
        private async Task <EngineDoc> ImportApp(string jwtToken, string multiCloudMachineName, string sourceDocumentId, string fileName, string url, string version)
        {
            string fileId        = url.Substring(url.LastIndexOf('/') + 1);
            string additionalUri = "apps/import?fileId=" + fileId + "&mode=autoreplace" + "&appId=" + CalculateDocumentOrTagId(sourceDocumentId, fileName);

            using (HttpResponseMessage response = await SetupAndSendRequest(HttpMethod.Post, multiCloudMachineName + additionalUri, "", jwtToken, "UserAgent", "QDS/" + version))
            {
                try
                {
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.RequestEntityTooLarge:
                        PrintMessage("Failure - Could not upload document to engine, since engine reported that the app exceeds the maximum size. statusCode= " + response.StatusCode + ", reason= " + response.ReasonPhrase, false);
                        throw new HttpAppSizeException("App size exceeds max size");

                    case HttpStatusCode.GatewayTimeout:
                        PrintMessage("Failure - Could not upload document in engine, API gateway in QSEfe/Multicloud reported that it timed out when waiting for a response. statusCode= " + response.StatusCode + ", reason= " + response.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(response);
                        break;
                    }
                    if (!response.IsSuccessStatusCode)
                    {
                        PrintMessage("Failure - Could not upload document to engine. statusCode= " + response.StatusCode + ", reason= " + response.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(response);
                    }
                    else
                    {
                        PrintMessage("Success - Upload document " + fileName + " to engine", false);
                    }

                    var responseContent = await response.Content.ReadAsStringAsync() ?? "{}";

                    EngineDoc result = JsonConvert.DeserializeObject <EngineDoc>(responseContent);
                    return(result);
                }
                catch (Exception e)
                {
                    PrintMessage("Failed to import app " + fileName + " to engine. Exception: " + e.Message, false);
                    return(null);
                }
            }
        }
        public async Task <HttpResponseMessage> DistributeDocument(string fileNameAndPath, string cloudDeploymentResourceUrl, string sourceDocumentId, string jwtToken)
        {
            string multiCloudMachineName = cloudDeploymentResourceUrl.TrimEnd('/') + "/api/v1/";
            string qvDocName             = Path.GetFileNameWithoutExtension(fileNameAndPath);
            var    l_FileStream          = new FileStream(fileNameAndPath, FileMode.Open, FileAccess.Read);
            var    stream  = new BufferedStream(l_FileStream, 8192);
            var    content = new StreamContent(stream, 65536);

            try
            {
                content.Headers.Add("Content-Type", "binary/octet-stream");
                using (HttpClient cloudClient = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, multiCloudMachineName + "apps/import?mode=autoreplace&appId=" + sourceDocumentId + "&fallbackName=" + qvDocName)
                    {
                        Content = content
                    };
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
                    HttpResponseMessage autoReplaceDocResponse = await cloudClient.SendAsync(request);

                    switch (autoReplaceDocResponse.StatusCode)
                    {
                    case HttpStatusCode.RequestEntityTooLarge:
                        PrintMessage("Failure - Could not upload document to engine, since engine reported that the app exceeds the maximum size. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        throw new HttpAppSizeException("App size exceeds max size");

                    case HttpStatusCode.GatewayTimeout:
                        PrintMessage("Failure - Could not upload document in engine, API gateway in QSEfe/Multicloud reported that it timed out when waiting for a response. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(autoReplaceDocResponse);
                        break;
                    }
                    if (!autoReplaceDocResponse.IsSuccessStatusCode)
                    {
                        PrintMessage("Failure - Could not upload document " + qvDocName + "to engine. statusCode= " + autoReplaceDocResponse.StatusCode + ", reason= " + autoReplaceDocResponse.ReasonPhrase, false);
                        WorkflowExceptionStrategy.ThrowException(autoReplaceDocResponse);
                    }

                    else
                    {
                        Console.WriteLine("Success - Document  " + qvDocName + " uploaded to engine");
                    }

                    var responseContent = await autoReplaceDocResponse.Content.ReadAsStringAsync() ?? "{}";

                    EngineDoc result = JsonConvert.DeserializeObject <EngineDoc>(responseContent);

                    HttpResponseMessage createItemResponse = await CreateItem(result, jwtToken, multiCloudMachineName, qvDocName);

                    return(createItemResponse);
                }
            }
            catch (HttpAppSizeException)
            {
                PrintMessage("App " + qvDocName + " exceeds max size", false);
            }
            catch (WorkflowException e)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, workflowException. Message =" + e.Message, false);
            }
            catch (TaskCanceledException e)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, Connection timeout. Message =" + e.Message, false);
            }
            catch (Exception ex)
            {
                PrintMessage("Failure - Could not upload document " + qvDocName + " to engine, Other exception of unknown cause. Message =" + ex.Message, false);
            }
            finally
            {
                content.Dispose();
                stream.Dispose();
                l_FileStream.Dispose();
            }
            return(null);
        }