Exemplo n.º 1
0
        /// <summary>
        /// Authenticates the user with Tableau Server.
        /// </summary>
        /// <returns>The auth token for the authenticated user's session.</returns>
        public string Authenticate()
        {
            var uri = Endpoints.GetSignInUri(baseUri);

            // Construct payload.
            tsRequest requestPayload = new tsRequest
            {
                Item = new tableauCredentialsType
                {
                    name     = userName,
                    password = password,
                    site     = new siteType
                    {
                        contentUrl = GetSiteAsContentUrl()
                    }
                }
            };

            // Issue request.
            var        errorMessage = String.Format("Failed to authenticate user '{0}'", userName);
            ApiRequest request      = new ApiRequest(uri, HttpMethod.Post, authToken: null, headers: null, body: requestPayload.SerializeBody());
            tsResponse response     = request.IssueRequest(errorMessage);

            // Extract authentication token.
            tableauCredentialsType credentials = response.GetTableauCredentials();

            return(credentials.token);
        }
Exemplo n.º 2
0
        public workbookType FinishUploadAndPublishWorkbook(PublishWorkbookRequest publishRequest, fileUploadType session)
        {
            var uri = Endpoints.GetFinishPublishWorkbookUri(baseUri, publishRequest.SiteId,
                                                            publishRequest.OverwriteExistingWorkbook, session.uploadSessionId,
                                                            Path.GetExtension(publishRequest.FilePath).Replace(".", ""));
            tsRequest requestPayload = new tsRequest
            {
                Item = new workbookType
                {
                    name = Path.GetFileNameWithoutExtension(publishRequest.FilePath),
                    //showTabs = publishRequest.ShowSheetsAsTabs,
                    //showTabsSpecified = publishRequest.ShowSheetsAsTabs,
                    project = new projectType
                    {
                        id = publishRequest.ProjectId
                    },
                }
            };

            var    boundaryString = Guid.NewGuid().ToString().Replace("-", "");
            string contentType    = String.Format("multipart/mixed; boundary={0}", boundaryString);

            byte[]     requestBody = PublishRequestBuilder.BuildFinishUploadBody(publishRequest.FilePath, requestPayload, boundaryString);
            ApiRequest apiRequest  = new ApiRequest(uri, HttpMethod.Post, GetAuthToken(), headers: null, contentType: contentType, body: requestBody, timeoutSeconds: publishRequest.PublishingTimeoutSeconds);

            // Issue request.
            var        errorMessage = String.Format("Failed to finish multipart publish workbook '{0}'", publishRequest.WorkbookName);
            tsResponse response     = apiRequest.IssueRequest(errorMessage);

            return(response.GetWorkbook());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Retrieves the project details for the given project name.
        /// </summary>
        /// <param name="projectName">The name of the project to query.</param>
        /// <returns>Project details associated with a given project name, or null if no match is found.</returns>
        public projectType GetProjectByName(string projectName)
        {
            int  currentPage      = 1;
            bool morePagesToCheck = true;

            while (morePagesToCheck)
            {
                // Construct URI specific to the current page of data to fetch.
                var uri = Endpoints.GetQueryProjectsUri(baseUri, GetSiteId(), currentPage);

                // Issue request.
                var        errorMessage = String.Format("Failed to retrieve project list for site '{0}'", siteName);
                ApiRequest request      = new ApiRequest(uri, HttpMethod.Get, GetAuthToken());
                tsResponse response     = request.IssueRequest(errorMessage);

                // Rip project names out of response and check for a match.
                projectListType projectList = response.GetProjectList();
                foreach (var project in projectList.project.Where(project => project.name == projectName))
                {
                    return(project);
                }

                // If we've read all the project names in and still haven't found a match, give up.  Otherwise check the next page.
                paginationType paginationData = response.GetPaginationType();
                if (currentPage * Constants.MaxResponsePageSize >= Convert.ToInt32(paginationData.totalAvailable))
                {
                    morePagesToCheck = false;
                }
                currentPage++;
            }

            // No match found.
            return(null);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a new project with the given name and description.
        /// </summary>
        /// <param name="projectName">The name of the project to create.</param>
        /// <param name="projectDescription">The description of the project to create.</param>
        /// <returns>The Project ID of the project that was created.</returns>
        public string CreateProject(string projectName, string projectDescription = Constants.DefaultCreatedProjectDescription)
        {
            // Get Site ID for the site we'll create a project in and use it to construct endpoint uri.
            var uri = Endpoints.GetCreateProjectUri(baseUri, GetSiteId());

            // Construct payload.
            tsRequest requestPayload = new tsRequest
            {
                Item = new projectType
                {
                    name        = projectName,
                    description = projectDescription
                }
            };

            // Issue request.
            var        errorMessage = String.Format("Failed to create project '{0}' on site '{1}'", projectName, siteName);
            ApiRequest request      = new ApiRequest(uri, HttpMethod.Post, GetAuthToken(), headers: null, body: requestPayload.SerializeBody());
            tsResponse response     = request.IssueRequest(errorMessage);

            // Return ID of created project.
            projectType createdProject = response.GetProject();

            return(createdProject.id);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Return a list of all projects present on the site associated with this RestApiRequestor.
        /// </summary>
        /// <returns>List of all projects present on the site.</returns>
        public IEnumerable <projectType> QueryProjects()
        {
            var projects = new List <projectType>();

            int  currentPage      = 1;
            bool morePagesToCheck = true;

            while (morePagesToCheck)
            {
                // Construct URI specific to the current page of data to fetch.
                var uri = Endpoints.GetQueryProjectsUri(baseUri, GetSiteId(), currentPage);

                // Issue request.
                var        errorMessage = String.Format("Failed to retrieve project list for site '{0}'", siteName);
                ApiRequest request      = new ApiRequest(uri, HttpMethod.Get, GetAuthToken());
                tsResponse response     = request.IssueRequest(errorMessage);

                // Add all projects in current page to our result set
                projectListType projectList = response.GetProjectList();
                projects.AddRange(projectList.project);

                // Evaluate whether we have more work to do
                paginationType paginationData = response.GetPaginationType();
                if (currentPage * Constants.MaxResponsePageSize >= Convert.ToInt32(paginationData.totalAvailable))
                {
                    morePagesToCheck = false;
                }
                currentPage++;
            }

            return(projects);
        }
Exemplo n.º 6
0
        public fileUploadType InitiateFileUpload(PublishWorkbookRequest publishRequest)
        {
            var        uri     = Endpoints.GetFileUploadUri(baseUri, publishRequest.SiteId);
            ApiRequest request = new ApiRequest(uri, HttpMethod.Post, GetAuthToken(), headers: null, contentType: null, body: null, timeoutSeconds: publishRequest.PublishingTimeoutSeconds);

            var        errorMessage = String.Format("Failed to retrieve session id for new upload to site '{0}'", siteName);
            tsResponse response     = request.IssueRequest(errorMessage);

            // Extract site ID.
            fileUploadType uploadSession = response.GetFileUpload();

            return(uploadSession);
        }
Exemplo n.º 7
0
        public fileUploadType AppendToFileUpload(PublishWorkbookRequest publishRequest, fileUploadType fileUploadSession, FileStream fileStream)
        {
            var    uri            = Endpoints.GetFileUploadUri(baseUri, publishRequest.SiteId, fileUploadSession.uploadSessionId);
            var    boundaryString = Guid.NewGuid().ToString().Replace("-", "");
            string contentType    = String.Format("multipart/mixed; boundary={0}", boundaryString);

            byte[] requestBody = PublishRequestBuilder.BuildMultiPartAppendBody(publishRequest.FilePath, boundaryString, fileStream);

            var        errorMessage = String.Format("Failed to append file part for upload to site '{0}' with upload session id '{1}'", siteName, fileUploadSession.uploadSessionId);
            ApiRequest request      = new ApiRequest(uri, HttpMethod.Put, GetAuthToken(), headers: null, contentType: contentType, body: requestBody, timeoutSeconds: publishRequest.PublishingTimeoutSeconds);
            tsResponse response     = request.IssueRequest(errorMessage);

            return(response.GetFileUpload());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Retrieves the project details for a given project id.
        /// </summary>
        /// <param name="projectId">The ID of the project to query.</param>
        /// <returns>Project details associated with a given project id, or null if no match is found.</returns>
        public projectType GetProjectById(string projectId)
        {
            Uri uri = Endpoints.GetUpdateProjectUri(baseUri, GetSiteId(), projectId);

            // Construct payload.
            tsRequest requestPayload = new tsRequest {
                Item = new projectType()
            };

            // Issue request.
            var        errorMessage = String.Format("Failed to retrieve project details for project '{0}' in site '{1}'", projectId, siteName);
            ApiRequest request      = new ApiRequest(uri, HttpMethod.Put, GetAuthToken(), headers: null, body: requestPayload.SerializeBody());
            tsResponse response     = request.IssueRequest(errorMessage);

            return(response.GetProject());
        }
Exemplo n.º 9
0
        /// <summary>
        /// Searches a tsResponse's Items array for an object matching the given type.
        /// </summary>
        /// <param name="response">This tsResponse object.</param>
        /// <param name="type">The type to search for.</param>
        /// <returns>A reference to item of the given type.</returns>
        private static object ExtractItemByType(this tsResponse response, Type type)
        {
            foreach (var item in response.Items)
            {
                if (item.GetType() == type)
                {
                    return(item);
                }

                if (item.GetType() == typeof(errorType))
                {
                    var error = item as errorType;
                    throw new HttpRequestException(error.summary);
                }
            }
            throw new ArgumentException(String.Format("No '{0}' item is present in response", type));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Retrieves the site ID for the given site.
        /// </summary>
        /// <returns>The Site ID for the inputted site name.</returns>
        public string GetSiteId()
        {
            if (String.IsNullOrWhiteSpace(siteId))
            {
                var uri = Endpoints.GetQuerySiteUri(baseUri, siteName);

                // Issue request.
                var        errorMessage = String.Format("Failed to retrieve site ID for site '{0}'", siteName);
                ApiRequest request      = new ApiRequest(uri, HttpMethod.Get, GetAuthToken());
                tsResponse response     = request.IssueRequest(errorMessage);

                // Extract site ID.
                siteType site = response.GetSite();
                siteId = site.id;
            }

            return(siteId);
        }
Exemplo n.º 11
0
        public workbookType PublishWorkbook(PublishWorkbookRequest publishRequest)
        {
            // Construct URI & compose request payload.
            var       uri            = Endpoints.GetPublishWorkbookUri(baseUri, publishRequest.SiteId, publishRequest.OverwriteExistingWorkbook);
            tsRequest requestPayload = new tsRequest
            {
                Item = new workbookType
                {
                    name              = Path.GetFileNameWithoutExtension(publishRequest.FilePath),
                    showTabs          = publishRequest.ShowSheetsAsTabs,
                    showTabsSpecified = publishRequest.ShowSheetsAsTabs,
                    project           = new projectType
                    {
                        id = publishRequest.ProjectId
                    },
                    connectionCredentials = new connectionCredentialsType
                    {
                        name           = publishRequest.DatasourceUserName,
                        password       = publishRequest.DatasourcePassword,
                        embed          = true,
                        embedSpecified = true
                    }
                }
            };

            // Construct multipart request body using a boundary string to delimit sections.
            var    boundaryString = Guid.NewGuid().ToString().Replace("-", "");
            string contentType    = String.Format("multipart/mixed; boundary={0}", boundaryString);

            byte[] requestBody = PublishRequestBuilder.BuildFileUploadBody(publishRequest.FilePath, requestPayload, boundaryString);

            // Issue request.
            var        errorMessage = String.Format("Failed to publish workbook '{0}'", publishRequest.WorkbookName);
            ApiRequest apiRequest   = new ApiRequest(uri, HttpMethod.Post, GetAuthToken(), headers: null, contentType: contentType, body: requestBody, timeoutSeconds: publishRequest.PublishingTimeoutSeconds);
            tsResponse response     = apiRequest.IssueRequest(errorMessage);

            return(response.GetWorkbook());
        }
Exemplo n.º 12
0
 public static fileUploadType GetFileUpload(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(fileUploadType)) as fileUploadType);
 }
Exemplo n.º 13
0
 public static favoriteListType GetFavoriteList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(favoriteListType)) as favoriteListType);
 }
Exemplo n.º 14
0
 public static errorType GetError(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(errorType)) as errorType);
 }
Exemplo n.º 15
0
 public static dataSourceListType GetDataSourceList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(dataSourceListType)) as dataSourceListType);
 }
Exemplo n.º 16
0
 public static connectionListType GetConnectionList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(connectionListType)) as connectionListType);
 }
Exemplo n.º 17
0
 public static tableauCredentialsType GetTableauCredentials(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(tableauCredentialsType)) as tableauCredentialsType);
 }
Exemplo n.º 18
0
 public static projectListType GetProjectList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(projectListType)) as projectListType);
 }
Exemplo n.º 19
0
 public static paginationType GetPaginationType(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(paginationType)) as paginationType);
 }
Exemplo n.º 20
0
 public static groupListType GetGroupList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(groupListType)) as groupListType);
 }
Exemplo n.º 21
0
 public static jobType GetJob(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(jobType)) as jobType);
 }
Exemplo n.º 22
0
 public static userListType GetUserList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(userListType)) as userListType);
 }
Exemplo n.º 23
0
 public static permissionsType GetPermissions(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(permissionsType)) as permissionsType);
 }
Exemplo n.º 24
0
 public static viewListType GetViews(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(viewListType)) as viewListType);
 }
Exemplo n.º 25
0
 public static siteListType GetSiteList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(siteListType)) as siteListType);
 }
Exemplo n.º 26
0
 public static workbookListType GetWorkbookList(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(workbookListType)) as workbookListType);
 }
Exemplo n.º 27
0
 public static tagListType GetTags(this tsResponse response)
 {
     return(ExtractItemByType(response, typeof(tagListType)) as tagListType);
 }
Exemplo n.º 28
0
        public PublishedWorkbookResult PublishWorkbookWithEmbeddedCredentials(PublishWorkbookRequest publishRequest)
        {
            PublishedWorkbookResult publishedWorkbookResult = new PublishedWorkbookResult(publishRequest);

            // Construct URI & compose request payload.
            var       uri            = Endpoints.GetPublishWorkbookUri(baseUri, publishRequest.SiteId, publishRequest.OverwriteExistingWorkbook);
            tsRequest requestPayload = new tsRequest
            {
                Item = new workbookType
                {
                    name              = Path.GetFileNameWithoutExtension(publishRequest.FilePath),
                    showTabs          = publishRequest.ShowSheetsAsTabs,
                    showTabsSpecified = publishRequest.ShowSheetsAsTabs,
                    project           = new projectType
                    {
                        id = publishRequest.ProjectId
                    },
                    connectionCredentials = new connectionCredentialsType
                    {
                        name           = publishRequest.DatasourceUserName,
                        password       = publishRequest.DatasourcePassword,
                        embed          = true,
                        embedSpecified = true
                    }
                }
            };

            // Construct multipart request body using a boundary string to delimit sections.
            var    boundaryString = Guid.NewGuid().ToString().Replace("-", "");
            string contentType    = String.Format("multipart/mixed; boundary={0}", boundaryString);

            byte[] requestBody = PublishRequestBuilder.BuildRequestBody(publishRequest.FilePath, requestPayload, boundaryString);

            // Issue request.
            var        errorMessage = String.Format("Failed to publish workbook '{0}'", publishRequest.WorkbookName);
            ApiRequest apiRequest   = new ApiRequest(uri, HttpMethod.Post, GetAuthToken(), headers: null, contentType: contentType, body: requestBody, timeoutSeconds: publishRequest.publishingTimeoutSeconds);

            try
            {
                tsResponse response = apiRequest.TryIssueRequest(errorMessage);

                publishedWorkbookResult.IsSuccessful = true;
                publishedWorkbookResult.WorkbookId   = response.GetWorkbook().id;
                publishedWorkbookResult.Uri          = GetWorkbookUrl(response.GetWorkbook().contentUrl);
            }
            catch (Exception ex)
            {
                publishedWorkbookResult.IsSuccessful = false;
                publishedWorkbookResult.ErrorMessage = ex.Message;
            }

            // Add any tags to the newly-published workbook.
            if (publishedWorkbookResult.IsSuccessful)
            {
                try
                {
                    AddTagsToWorkbook(publishedWorkbookResult.WorkbookId, publishRequest.Tags);
                }
                catch
                {
                    // We swallow any errors here.
                }
            }

            return(publishedWorkbookResult);
        }