public void SetError(string errorMessage, object responseModel = null)
 {
     Status   = StatusLog.Error;
     Date     = DateHelper.Now;
     Message  = errorMessage;
     Response = responseModel;
 }
    /// <summary>
    /// Attempts to upload a single file a Tableau Server, and then make it a published workbook
    /// </summary>
    /// <param name="localFilePath"></param>
    /// <returns></returns>
    private bool AttemptUploadSingleFile_Inner(
        string localFilePath,
        string projectId,
        CredentialManager.Credential dbCredentials,
        WorkbookPublishSettings publishSettings)
    {
        string uploadSessionId;

        try
        {
            var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds);
            uploadSessionId = fileUploader.ExecuteRequest();
        }
        catch (Exception exFileUpload)
        {
            this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message);
            throw exFileUpload;
        }

        SiteWorkbook workbook;

        this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10);
        try
        {
            string fileName   = Path.GetFileNameWithoutExtension(localFilePath);
            string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower());
            workbook = FinalizePublish(
                uploadSessionId,
                FileIOHelper.Undo_GenerateWindowsSafeFilename(fileName), //[2016-05-06] If the name has escapted characters, unescape them
                uploadType,
                projectId,
                dbCredentials,
                publishSettings);
            StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10);
            StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath));
        }
        catch (Exception exPublishFinalize)
        {
            this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message);
            LogManualAction_UploadWorkbook(localFilePath);
            throw exPublishFinalize;
        }

        //See if we want to reassign ownership of the workbook
        if (_attemptOwnershipAssignment)
        {
            try
            {
                AttemptOwnerReassignment(workbook, publishSettings, _siteUsers);
            }
            catch (Exception exOwnershipAssignment)
            {
                this.StatusLog.AddError("Unexpected error reassigning ownership of published workbook " + workbook.Name + ", " + exOwnershipAssignment.Message);
                LogManualAction_ReassignOwnership(workbook.Name);
                throw exOwnershipAssignment;
            }
        }

        return(true);     //Success
    }
示例#3
0
        public async Task <IActionResult> SendStatusAsync([FromBody] StatusLog sl)
        {
            _storeService.AddStatusLog(sl);
            await _storeService.SaveChangesAsync();

            return(Ok());
        }
示例#4
0
        public async Task AddStatusLog_Work()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "AddItemsToDb")
                          .Options;
            var newEntry = new StatusLog()
            {
                ServiceName = "Service1",
                Status      = HttpStatusCode.OK,
                Date        = DateTimeOffset.Now
            };

            // Act
            using (var context = new ApplicationDbContext(options))
            {
                var sut = new StatusLogStore(context);


                sut.AddStatusLog(newEntry);
                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(options))
            {
                Assert.AreEqual(1, context.StatusLogs.Count());
                Assert.AreEqual(newEntry.ServiceName, context.StatusLogs.First().ServiceName);
            }
        }
示例#5
0
        protected override ExitCode ExecuteFileTask()
        {
            string target     = Arguments.GetOption <string>("target", "t");
            int    redirector = Array.IndexOf(Arguments.Targets, ">");

            if (target == null && redirector == -1)
            {
                ResultLog.WriteLine(string.Join(" ", Arguments.Targets));
                return(ExitCode.Success);
            }

            if (target == null)
            {
                if (redirector == Arguments.Targets.Length - 1)
                {
                    StatusLog.WriteLine(WriteStyle.Error, XFileStrings.ErrorNoTargetSpecified);
                    return(ExitCode.InvalidArgument);
                }

                target = Arguments.Targets[redirector + 1];
            }

            target = GetFullPath(target);
            FileService.WriteAllText(target, string.Join(" ", redirector == -1 ? Arguments.Targets : Arguments.Targets.Take(redirector)));

            return(ExitCode.Success);
        }
示例#6
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="serverName"></param>
    public void ExecuteRequest()
    {
        //Sanity check
        if (string.IsNullOrWhiteSpace(_userId))
        {
            _onlineSession.StatusLog.AddError("User ID required to query workbooks");
        }

        var onlineWorkbooks = new List <SiteWorkbook>();
        int numberPages     = 1; //Start with 1 page (we will get an updated value from server)

        //Get subsequent pages
        for (int thisPage = 1; thisPage <= numberPages; thisPage++)
        {
            try
            {
                ExecuteRequest_ForPage(onlineWorkbooks, thisPage, out numberPages);
            }
            catch (Exception exPageRequest)
            {
                StatusLog.AddError("Workbooks error during page request: " + exPageRequest.Message);
            }
        }

        _workbooks = onlineWorkbooks;
    }
        /// <summary>
        /// Installs the wing progress.
        /// </summary>
        /// <param name="progressResult">The progress result.</param>
        public void InstallWingProgress(OpenSourceInstallResult progressResult)
        {
            switch (progressResult.Status)
            {
            case OpenSourceInstallFlags.AlreadyExists:
                StatusLog.Add(progressResult.Message);

                if (progressResult.Target != null && WingItems != null && !WingItems.Any(item => item != null && !string.IsNullOrEmpty(item.Name) && item.Name.EqualsIgnoreCase(progressResult.Target.Name)))
                {
                    WingItems.Add(progressResult.Target);
                }
                break;

            case OpenSourceInstallFlags.StatusUpdate:
                StatusLog.Add(progressResult.Message);
                break;

            case OpenSourceInstallFlags.Success:
                StatusLog.Add(progressResult.Message);

                if (progressResult.Target != null && !WingItems.Any(wi => wi.Name.EqualsIgnoreCase(progressResult.Target.Name)))
                {
                    WingItems.Add(progressResult.Target);
                }

                break;
            }
        }
示例#8
0
        public static void Main(string[] args)
        {
            if (Utils.IsInstanceRunning())
            {
                StatusLog.Log("A running instance is already present! [ABORTING]");
                Environment.Exit(2);
            }
            if (Utils.DetectSandboxie())
            {
                StatusLog.Log("Sandboxie detected! [ABORTING]");
                Environment.Exit(2);
            }

            Startup.Init();
            StatusLog.Log("Started...");
            Utils.PreventSleep();

            _activeWindowTextManager = new ActiveWindowTextManager();
            _activeWindowTextManager.Run();

            _hookptr = SetHook(_proc);
            SetConsoleWindow(Constants.ConsoleWindowState.SW_HIDE);

            Application.Run();
            NativeMethods.UnhookWindowsHookEx(_hookptr);
        }
示例#9
0
    /// <summary>
    /// Sanity testing on whether the file being uploaded is worth uploading
    /// </summary>
    /// <param name="localFilePath"></param>
    /// <returns></returns>
    bool IsValidUploadFile(string localFilePath)
    {
        //If the file is a custom settings file for the workbook, then ignore it
        if (DatasourcePublishSettings.IsSettingsFile(localFilePath))
        {
            return(false); //Nothing to do, it's just a settings file
        }

        //Ignore temp files, since we know we don't want to upload them
        var fileExtension = Path.GetExtension(localFilePath).ToLower();

        if ((fileExtension == ".tmp") || (fileExtension == ".temp"))
        {
            StatusLog.AddStatus("Ignoring temp file, " + localFilePath, -10);
            return(false);
        }

        //These are the only kinds of data sources we know about...
        if ((fileExtension != ".tds") && (fileExtension != ".tdsx"))
        {
            StatusLog.AddError("File is not a data source: " + localFilePath);
            return(false);
        }

        return(true);
    }
示例#10
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("ServiceChecker tracking {count} services at: {time}",
                                       _businessServices.Count(), DateTimeOffset.Now);

                var listOfTasks = new List <(Task <HttpResponseMessage> Task, string Name)>();

                foreach (var businessService in _businessServices)
                {
                    listOfTasks.Add((businessService.GetStatusAsync(), businessService.ServiceName));
                }

                //await Task.WhenAll(listOfTasks);

                foreach (var task in listOfTasks)
                {
                    var result = await task.Task;
                    var log    = new StatusLog()
                    {
                        ServiceName = task.Name,
                        Status      = result.StatusCode,
                        Date        = result.Headers.Date ?? DateTimeOffset.Now
                    };
                    _storeService.AddStatusLog(log);
                }
                await _storeService.SaveChangesAsync();

                await Task.Delay(_delay, stoppingToken);
            }
        }
示例#11
0
    /// <summary>
    /// Attempts to upload a single file a Tableau Server, and then make it a published workbook
    /// </summary>
    /// <param name="localFilePath"></param>
    /// <returns></returns>
    private bool AttemptUploadSingleFile_Inner(
        string localFilePath,
        string projectId,
        CredentialManager.Credential dbCredentials)
    {
        string uploadSessionId;

        try
        {
            var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds);
            uploadSessionId = fileUploader.ExecuteRequest();
        }
        catch (Exception exFileUpload)
        {
            this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message);
            throw exFileUpload;
        }

        this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10);
        try
        {
            string fileName   = Path.GetFileNameWithoutExtension(localFilePath);
            string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower());
            var    workbook   = FinalizePublish(uploadSessionId, fileName, uploadType, projectId, dbCredentials);
            StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10);
            StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath));
        }
        catch (Exception exPublishFinalize)
        {
            this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message);
            LogManualAction_UploadWorkbook(localFilePath);
            throw exPublishFinalize;
        }
        return(true);     //Success
    }
示例#12
0
        /// <summary>
        ///     This is called after the class is constructed and before the page is displayed.
        ///     We use it as a trigger to populate the page elements.
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            // Write our status messages to a list on the page.
            var statusBuilder = new StringBuilder();

            if (StatusLog.Count > 0)
            {
                statusBuilder.AppendLine("<ul>");
                foreach (var status in StatusLog)
                {
                    statusBuilder.AppendFormat("<li>{0}</li>\n", status.Contains("\n") ? FormatForPage(status) : status);
                }
                statusBuilder.AppendLine("</ul>");
                statusPlaceholder.Text = statusBuilder.ToString();

                // We've written the messages out, so remove them from the list.
                StatusLog.Clear();
            }

            // Write information about the system to the page.
            WriteSystemVariables();

            // Build our list of images from DynamoDB and S3
            BuildImageList();

            // Display the image list in a table on the page.
            var imageListBuilder = new StringBuilder();

            foreach (var imageRow in ImageListRows)
            {
                imageListBuilder.AppendLine(imageRow);
            }
            imageListPlaceholder.Text = imageListBuilder.ToString();
        }
示例#13
0
    /// <summary>
    /// After a file has been uploaded in chunks, we need to make a call to COMMIT the file to server as a published Data Source
    /// </summary>
    /// <param name="uploadSessionId"></param>
    /// <param name="publishedContentName"></param>
    private SiteDatasource FinalizePublish(
        string uploadSessionId,
        string publishedContentName,
        string publishedContentType,
        string projectId,
        CredentialManager.Credential dbCredentials)
    {
        //See definition: http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Publish_Datasource%3FTocPath%3DAPI%2520Reference%7C_____29
        var sb        = new StringBuilder();
        var xmlWriter = XmlWriter.Create(sb, XmlHelper.XmlSettingsForWebRequests);

        xmlWriter.WriteStartElement("tsRequest");
        xmlWriter.WriteStartElement("datasource");
        xmlWriter.WriteAttributeString("name", publishedContentName);

        //If we have an associated database credential, write it out
        if (dbCredentials != null)
        {
            CredentialXmlHelper.WriteCredential(
                xmlWriter,
                dbCredentials);
        }

        xmlWriter.WriteStartElement("project"); //<project>
        xmlWriter.WriteAttributeString("id", projectId);
        xmlWriter.WriteEndElement();            //</project>
        xmlWriter.WriteEndElement();            // </datasource>
        //Currently not supporting <connectionCredentials>
        xmlWriter.WriteEndElement();            // </tsRequest>
        xmlWriter.Close();

        var xmlText = sb.ToString(); //Get the XML text out

        //Generate the MIME message
        var mimeGenerator = new MimeWriterXml(xmlText);

        //Create a web request to push the
        var urlFinalizeUpload = _onlineUrls.Url_FinalizeDataSourcePublish(_onlineSession, uploadSessionId, publishedContentType);

        //NOTE: The publish finalization step can take several minutes, because server needs to unpack the uploaded ZIP and file it away.
        //      For this reason, we pass in a long timeout
        var webRequest = this.CreateAndSendMimeLoggedInRequest(urlFinalizeUpload, "POST", mimeGenerator, TableauServerWebClient.DefaultLongRequestTimeOutMs);
        var xmlDoc     = GetWebReponseLogErrors_AsXmlDoc(webRequest, "finalize datasource publish");

        //Get all the datasource node from the response
        var nsManager     = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
        var dataSourceXml = xmlDoc.SelectSingleNode("//iwsOnline:datasource", nsManager);

        try
        {
            return(new SiteDatasource(dataSourceXml));
        }
        catch (Exception parseXml)
        {
            StatusLog.AddError("Data source upload, error parsing XML response " + parseXml.Message + "\r\n" + dataSourceXml.InnerXml);
            return(null);
        }
    }
示例#14
0
    /// <summary>
    /// Called to perform Uploads of the workbooks
    /// </summary>
    /// <param name="onlineLogin"></param>
    /// <param name="localBasePath"></param>
    /// <param name="remapWorkbookReferences">TRUE is we want to transform workbooks to remap any published datasources to the new server/site we are uploading to</param>
    /// <param name="credentialManager">Database credentials to associate with content we are uploading</param>
    private void Execute_UploadWorkbooks(
        TableauServerSignIn onlineLogin,
        string localBasePath,
        bool remapWorkbookReferences,
        CredentialManager credentialManager)
    {
        StatusLog.AddStatusHeader("Upload workbooks");

        if (string.IsNullOrWhiteSpace(localBasePath))
        {
            _statusLog.AddError("Abort uploads. Local path is not specified");
            return;
        }

        string pathWorkbooks = Path.Combine(localBasePath, "workbooks");

        if (!Directory.Exists(pathWorkbooks))
        {
            _statusLog.AddStatus("Skipping workbooks upload. Local workbooks path does not exist: \"" + pathWorkbooks + "\"");
            return;
        }

        //Do we have a directory to perform remapping
        string pathRemappingTempspace = Path.Combine(localBasePath, "_remapTempspace");

        if (!Directory.Exists(pathRemappingTempspace))
        {
            Directory.CreateDirectory(pathRemappingTempspace);
        }


        //Upload all the files
        var uploadProjectBehavior = new UploadBehaviorProjects(
            _taskOptions.IsOptionSet(TaskMasterOptions.Option_UploadCreateNeededProjects),
            true);

        var dsUploader = new UploadWorkbooks(
            _onlineUrls,
            onlineLogin,
            credentialManager,
            pathWorkbooks,
            remapWorkbookReferences,
            pathRemappingTempspace,
            uploadProjectBehavior,
            _manualActions,
            this.UploadChunksSizeBytes,
            this.UploadChunksDelaySeconds);

        try
        {
            dsUploader.ExecuteRequest();
        }
        catch (Exception exUploader)
        {
            StatusLog.AddError("Aborted upload workbooks. Unexpected error + " + exUploader.Message);
        }
    }
示例#15
0
 internal void WriteStatusLog(string status)
 {
     using (var db = new TwitterBotContext())
     {
         var log = new StatusLog();
         log.Message = status;
         db.StatusLogs.Add(log);
         db.SaveChanges();
     }
 }
示例#16
0
        protected override ExitCode CheckPrerequisites()
        {
            if (String.IsNullOrWhiteSpace(this.Arguments.Target))
            {
                StatusLog.WriteLine(WriteStyle.Error, XFileStrings.ErrorRequiresTarget);
                return(ExitCode.InvalidArgument);
            }

            return(ExitCode.Success);
        }
 /// <summary>
 /// Fakes the status.
 /// </summary>
 private void FakeStatus()
 {
     for (int i = 0; i < 50; i++)
     {
         StatusLog.Add(i + " aasdfasdfasdfasdfasdfasdfasdfasdfasd fasdfasdfasdfasdfasdfsadfasd dfasdfasd fasdfasdfasdfasdfasdfsadfasd");
         Task.Delay(100);
         StatusLog.Add(i + " zxcvzxcvzxcv zxcv zxcvz zxcv zxcv zxcvxz xzcv zxcv zxcv zxcv zxcv xcz");
         Task.Delay(100);
         StatusLog.Add(i + " qwerqwerwerq qwer qwer qwerwerwqerqwerq  qwer qwerqwerwerqwreqw ");
     }
 }
示例#18
0
 public void AppendLog(string status)
 {
     if (StatusLog.InvokeRequired)
     {
         StatusLog.Invoke(new SafeStatusDelegate(AppendLog), new object[] { status });
     }
     else
     {
         StatusLog.AppendText(status + "\n");
     }
 }
示例#19
0
        public void AddStatusLog(StatusLog sl)
        {
            var sle = new StatusLogEntity()
            {
                ServiceName = sl.ServiceName,
                Status      = sl.Status,
                Date        = sl.Date
            };

            _context.StatusLogs.Add(sle);
        }
        /// <summary>
        /// Called when [uninstall wing].
        /// </summary>
        /// <param name="dynamicTarget">The dynamic target.</param>
        private async void OnUninstallWing(Target dynamicTarget)
        {
            if (dynamicTarget == null)
            {
                return;
            }



            var uninstallConfirmation = MessageBox.Show(@"Are you sure you want to uninstall '" + dynamicTarget.DisplayName + "'?"
                                                        + Environment.NewLine + "The Website(s) using this Wing will be deleted."
                                                        , @"Uninstall Confirmation", MessageBoxButton.YesNo);

            if (uninstallConfirmation == MessageBoxResult.No)
            {
                return;
            }
            UninstallInProgress = true;
            StatusLog.Clear();
            ProgressPopupVisibility = true;

            await Task.Delay(500);

            UnistallWingName = dynamicTarget.DisplayName;
            var cancellationToken = new CancellationTokenSource();
            var uninstallResult   = await DynamicTargetService.Uninstall(dynamicTarget, cancellationToken.Token, result =>
            {
                if (result.Status == OpenSourceUnInstallFlags.StatusUpdate)
                {
                    StatusLog.Add(result.Message);
                }
                if (result.Status == OpenSourceUnInstallFlags.Success)
                {
                    StatusLog.Add(string.Format("Uninstallation of wing \"{0}\" completed successfully.", dynamicTarget.Name));

                    if (WingItems.Contains(dynamicTarget))
                    {
                        WingItems.Remove(dynamicTarget);
                    }
                }
            },
                                                                         exceptionResult =>
            {
                var statusMessage = string.Format("Uninstallation of wing \"{0}\" was unsuccessful. Please try again. If for any reason the" +
                                                  "the error still remains after trying to uninstall again. Please contact Monahrq technical assistance.",
                                                  dynamicTarget.Name);
                StatusLog.Add(statusMessage);
                Logger.Write(exceptionResult.Exception);
            });


            UninstallInProgress = false;
        }
示例#21
0
        /// <summary>
        /// Update a user on server
        /// </summary>

        public void ExecuteRequest()
        {
            try
            {
                _UpdateUser(_userId, _fullName, _email, _password);
                StatusLog.AddStatus("User updated. " + _userId);
            }
            catch (Exception exUser)
            {
                StatusLog.AddError("Error attempting to update user '" + _userId + "'," + exUser.Message);
            }
        }
 /// <summary>
 /// Create a project on server
 /// </summary>
 public void ExecuteRequest()
 {
     try
     {
         _UpdateUser(_userID, _siteRole);
         StatusLog.AddStatus("User updated. " + _userID);
     }
     catch (Exception exUser)
     {
         StatusLog.AddError("Error attempting to update user '" + _userID + "', " + exUser.Message);
     }
 }
        /// <summary>
        /// Called when [install flutter].
        /// </summary>
        private async void OnInstallFlutter()
        {
            FlutterInstalled = false;

            var uiContext = SynchronizationContext.Current;

            StatusLog.Clear();
            ApplicableReports.Clear();

            if (string.IsNullOrEmpty(SelectedFlutterFile))
            {
                return;
            }


            OSFlutterInstallResult installResult = null;

            var cTokenSource = new CancellationTokenSource();
            var taskResult   = await DynamicTargetService.InstallFlutterFiles(SelectedFlutterFile, cTokenSource.Token,
                                                                              result =>
            {
                installResult = result;
                if (result.Status == OSFlutterInstallFlags.StatusUpdate || result.Status == OSFlutterInstallFlags.UploadFileComplete)
                {
                    uiContext.Send(x => StatusLog.Add(result.Message), null);
                }

                if (result.Status == OSFlutterInstallFlags.Success)
                {
                    uiContext.Send(x => StatusLog.Add(result.Message), null);
                }
            },
                                                                              exceptionResult =>
            {
                if (exceptionResult.Status == OSFlutterInstallFlags.Error)
                {
                    uiContext.Send(x => StatusLog.Add(exceptionResult.Message), null);
                    Logger.Warning(installResult.ToString());

                    installResult = exceptionResult;
                }
            });

            if (installResult.Status == OSFlutterInstallFlags.Success && installResult.Flutter != null)
            {
                if (FlutterItems.All(f => !f.Name.EqualsIgnoreCase(installResult.Flutter.Name)))
                {
                    FlutterItems.Add(installResult.Flutter);
                }
            }
            FlutterInstalled = true;
        }
示例#24
0
 /// <summary>
 /// Delete the tag from the workbook.
 /// </summary>
 public void ExecuteRequest()
 {
     try
     {
         //Attempt the delete
         _DeleteTagFromContent(_contentId, _tagText);
         StatusLog.AddStatus("Tag deleted from workbook " + _contentId + "/" + _tagText);
     }
     catch (Exception exProject)
     {
         StatusLog.AddError("Error attempting to delete content tag " + _contentId + "/" + _tagText + "', " + exProject.Message);
     }
 }
        private SiteProject _CreateProject(string projectName, string projectDescription)
        {
            //ref: http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Create_Project%3FTocPath%3DAPI%2520Reference%7C_____12
            var sb          = new StringBuilder();
            var xmlSettings = new XmlWriterSettings();

            xmlSettings.OmitXmlDeclaration = true;
            var xmlWriter = XmlWriter.Create(sb, xmlSettings);

            xmlWriter.WriteStartElement("tsRequest");
            xmlWriter.WriteStartElement("project");
            xmlWriter.WriteAttributeString("name", projectName);
            xmlWriter.WriteAttributeString("description", projectDescription);
            xmlWriter.WriteEndElement(); //</project>
            xmlWriter.WriteEndElement(); // </tsRequest>
            xmlWriter.Close();

            var xmlText = sb.ToString(); //Get the XML text out

            //Generate the MIME message
            //var mimeGenerator = new OnlineMimeXmlPayload(xmlText);

            //Create a web request
            var urlCreateProject = _onlineUrls.Url_CreateProject(OnlineSession);
            var webRequest       = CreateLoggedInWebRequest(urlCreateProject, "POST");

            SendRequestContents(webRequest, xmlText);

            //Get the response
            var response = GetWebResponseLogErrors(webRequest, "create project");

            using (response)
            {
                var xmlDoc = GetWebResponseAsXml(response);


                //Get all the workbook nodes
                var nsManager    = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
                var xNodeProject = xmlDoc.SelectSingleNode("//iwsOnline:project", nsManager);

                try
                {
                    return(new SiteProject(xNodeProject));
                }
                catch (Exception parseXml)
                {
                    StatusLog.AddError("Data source upload, error parsing XML resposne " + parseXml.Message + "\r\n" + xNodeProject.InnerXml);
                    return(null);
                }
            }
        }
示例#26
0
    private SiteUser UpdateUser(string userId, string newRole, SiteUserAuth newAuthentication)
    {
        AppDiagnostics.Assert(!string.IsNullOrWhiteSpace(userId), "missing user id");
        AppDiagnostics.Assert(!string.IsNullOrWhiteSpace(newRole), "missing role");

        string newAuthenticationText = SendCreateUser.SiteUserAuthToAttributeText(newAuthentication);

        //ref: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#update_user
        var sb        = new StringBuilder();
        var xmlWriter = XmlWriter.Create(sb, XmlHelper.XmlSettingsForWebRequests);

        xmlWriter.WriteStartElement("tsRequest");
        xmlWriter.WriteStartElement("user");
        xmlWriter.WriteAttributeString("siteRole", newRole);
        xmlWriter.WriteAttributeString("authSetting", newAuthenticationText);
        xmlWriter.WriteEndElement(); //</user>
        xmlWriter.WriteEndElement(); // </tsRequest>
        xmlWriter.Close();

        var xmlText = sb.ToString(); //Get the XML text out

        //Create a web request
        var urlUpdateUser = _onlineUrls.Url_UpdateSiteUser(_onlineSession, userId);
        var webRequest    = this.CreateLoggedInWebRequest(urlUpdateUser, "PUT");

        TableauServerRequestBase.SendPutContents(webRequest, xmlText);

        //Get the response
        var response = GetWebReponseLogErrors(webRequest, "update yser (change auth or role)");

        using (response)
        {
            var xmlDoc = GetWebResponseAsXml(response);


            //Get all the user nodes
            var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
            var xNodeUser = xmlDoc.SelectSingleNode("//iwsOnline:user", nsManager);

            try
            {
                return(SiteUser.FromUserXMLWithoutUserId(xNodeUser, userId));
            }
            catch (Exception parseXml)
            {
                StatusLog.AddError("Update user, error parsing XML response " + parseXml.Message + "\r\n" + xNodeUser.InnerXml);
                return(null);
            }
        }
    }
 /// <summary>
 /// Create a project on server
 /// </summary>
 public SiteProject ExecuteRequest()
 {
     try
     {
         var newProj = _CreateProject(_projectName, _projectDesciption);
         StatusLog.AddStatus("Project created. " + newProj);
         return(newProj);
     }
     catch (Exception exProject)
     {
         StatusLog.AddError("Error attempting to create project '" + _projectName + "', " + exProject.Message);
         return(null);
     }
 }
示例#28
0
 /// <summary>
 /// Create a user on server
 /// </summary>
 public string ExecuteRequest()
 {
     try
     {
         var newUser = _CreateUser(_name, _fullName, _siteRole, _authSetting);
         StatusLog.AddStatus("User created. " + newUser);
         return(newUser);
     }
     catch (Exception exProject)
     {
         StatusLog.AddError("Error attempting to create user '" + _name + "', " + exProject.Message);
         return(null);
     }
 }
示例#29
0
    /// <summary>
    /// Create the user on the server
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="userRole"></param>
    /// <param name="userAuthentication"></param>
    /// <returns></returns>
    private SiteUser CreateUser(string userName, string userRole, SiteUserAuth userAuthentication)
    {
        string authSettingText = SiteUserAuthToAttributeText(userAuthentication);

        //ref: https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref.htm#add_user_to_site
        var sb        = new StringBuilder();
        var xmlWriter = XmlWriter.Create(sb, XmlHelper.XmlSettingsForWebRequests);

        xmlWriter.WriteStartElement("tsRequest");
        xmlWriter.WriteStartElement("user");
        xmlWriter.WriteAttributeString("name", userName);
        xmlWriter.WriteAttributeString("siteRole", userRole);
        xmlWriter.WriteAttributeString("authSetting", authSettingText);
        xmlWriter.WriteEndElement(); //</user>
        xmlWriter.WriteEndElement(); //</tsRequest>
        xmlWriter.Close();

        var xmlText = sb.ToString(); //Get the XML text out

        //Generate the MIME message

        //Create a web request
        var urlCreateUser = _onlineUrls.Url_CreateSiteUser(_onlineSession);
        var webRequest    = this.CreateLoggedInWebRequest(urlCreateUser, "POST");

        TableauServerRequestBase.SendPostContents(webRequest, xmlText);

        //Get the response
        var response = GetWebReponseLogErrors(webRequest, "create user");

        using (response)
        {
            var xmlDoc = GetWebResponseAsXml(response);

            //Get all the workbook nodes
            var nsManager    = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
            var xNodeProject = xmlDoc.SelectSingleNode("//iwsOnline:user", nsManager);

            try
            {
                return(new SiteUser(xNodeProject));
            }
            catch (Exception parseXml)
            {
                StatusLog.AddError("Create user, error parsing XML response " + parseXml.Message + "\r\n" + xNodeProject.InnerXml);
                return(null);
            }
        }
    }
示例#30
0
    private SiteFlow ChangeContentOwner(string flowId, string newOwnerId)
    {
        AppDiagnostics.Assert(!string.IsNullOrWhiteSpace(flowId), "missing flow id");
        AppDiagnostics.Assert(!string.IsNullOrWhiteSpace(newOwnerId), "missing owner id");

        //ref: https://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Update_Flow%3FTocPath%3DAPI%2520Reference%7C_____76
        var sb        = new StringBuilder();
        var xmlWriter = XmlWriter.Create(sb, XmlHelper.XmlSettingsForWebRequests);

        xmlWriter.WriteStartElement("tsRequest");
        xmlWriter.WriteStartElement("flow");
        xmlWriter.WriteStartElement("owner");
        xmlWriter.WriteAttributeString("id", newOwnerId);
        xmlWriter.WriteEndElement(); //</owner>
        xmlWriter.WriteEndElement(); //</flow>
        xmlWriter.WriteEndElement(); // </tsRequest>
        xmlWriter.Close();

        var xmlText = sb.ToString(); //Get the XML text out

        //Create a web request
        var urlUpdateFlow = _onlineUrls.Url_UpdateFlow(_onlineSession, flowId);
        var webRequest    = this.CreateLoggedInWebRequest(urlUpdateFlow, "PUT");

        TableauServerRequestBase.SendPutContents(webRequest, xmlText);

        //Get the response
        var response = GetWebReponseLogErrors(webRequest, "update flow (change owner)");

        using (response)
        {
            var xmlDoc = GetWebResponseAsXml(response);


            //Get all the flow nodes
            var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline");
            var xNodeDs   = xmlDoc.SelectSingleNode("//iwsOnline:flow", nsManager);

            try
            {
                return(new SiteFlow(xNodeDs));
            }
            catch (Exception parseXml)
            {
                StatusLog.AddError("Change flow owner, error parsing XML response " + parseXml.Message + "\r\n" + xNodeDs.InnerXml);
                return(null);
            }
        }
    }
示例#31
0
        private StatusLog VerificaStatus(IEnumerable<LogEvent> events, StatusLog statusPai)
        {
            if (events != null)
            {
                foreach (var logEvent in events)
                {
                    statusPai = VerificaStatus(logEvent.Events, logEvent._status);
                }
            }
            if (statusPai == StatusLog.Error)
                _status = StatusLog.Error;
            else if (statusPai == StatusLog.Warning && _status == StatusLog.Success)
                _status = StatusLog.Warning;

            return _status;
        }