Beispiel #1
0
        static void Main(string[] args)
        {
            var shared        = new SharedData();
            var cancel_source = new CancellationTokenSource();

            var output_handler = new OutputHandler()
            {
                Data = shared
            };
            var output_thread = output_handler.RunOnNewThread(cancel_source.Token);

            while (true)
            {
                var key = Console.ReadKey();

                if (key.KeyChar == 'q')
                {
                    break;
                }
                else
                {
                    shared.LastChar = key.KeyChar;
                }
            }
            cancel_source.Cancel();
            output_thread.Join();
        }
Beispiel #2
0
 public static Exception Log(Exception error, ExceptionType type, OutputHandler OutputCallback)
 {
     lock (Lock)
     {
         OutputHandler callback = new OutputHandler(delegate(Exception e, ExceptionType t) { });
         Errors.Add(new ExceptionItem(error, type));
         if (Output != null)
         {
             callback = Output;
         }
         if (OutputCallback != null)
         {
             callback = OutputCallback;
         }
         if (callback != null)
         {
             callback(error, type);
         }
         Logger.Log(">> Exception Detected >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
         //System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
         //for (int i = 0; i < st.FrameCount; i++)
         //{
         //    System.Diagnostics.StackFrame sf = st.GetFrame(i);
         //    Logger.Log(String.Format(">> File name:{0}\tLine:{1}\tColumn:{2}\tMethodName:{3} ", sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber(), sf.GetMethod().Name));
         //}
         Logger.Log(error.ToString());
     }
     return(error);
 }
Beispiel #3
0
        private void ChannelPacketReceived(byte arg1, byte arg2, byte[] arg3)
        {
            if (arg1 == 129)
            {
                // for now, skip
                return;
            }
            if (arg1 == TestController.TestChannel)
            {
                switch (arg2)
                {
                case (byte)TestChannelCommandEnum.TestCompleted:
                    KernelTestCompleted();
                    break;

                case (byte)TestChannelCommandEnum.TestFailed:
                    KernelTestFailed();
                    break;

                case (byte)TestChannelCommandEnum.AssertionSucceeded:
                    KernelAssertionSucceeded();
                    break;
                }
            }
            else
            {
                OutputHandler.LogMessage($"ChannelPacketReceived, Channel = {arg1}, Command = {arg2}, Args = {BitConverter.ToString(arg3)}");
            }
        }
Beispiel #4
0
    private static void WriteGenerateStatisticsLogInfo(string statisticsName, string filter1Name, string filter2Name)
    {
        string filter1 = "";
        string filter2 = "";

        if (!string.IsNullOrEmpty(filter1Name))
        {
            filter1 = string.Format("Filter 1 \"{0}\" applied", filter1Name);
        }

        if (!string.IsNullOrEmpty(filter2Name))
        {
            filter2 = string.Format("Filter 2 \"{0}\" applied", filter2Name);
        }

        string filters = "";

        if (filter1 != "" && filter2 == "")
        {
            filters = string.Format(" ({0})", filter1);
        }
        else if (filter2 != "" && filter1 == "")
        {
            filters = string.Format(" ({0})", filter2);
        }
        if (filter1 != "" && filter2 != "")
        {
            filters = string.Format(" ({0}, {1})", filter1, filter2);
        }

        OutputHandler.WriteToLog(string.Format("Generating statistics using \"{0}\"{1}", statisticsName, filters));
    }
Beispiel #5
0
        private void ChannelPacketReceived(byte arg1, byte arg2, byte[] arg3)
        {
            OutputHandler.LogMessage(String.Format("ChannelPacketReceived, Channel = {0}, Command = {1}", arg1, arg2));
            if (arg1 == 129)
            {
                // for now, skip
                return;
            }
            if (arg1 == TestController.TestChannel)
            {
                switch (arg2)
                {
                case (byte)TestChannelCommandEnum.TestCompleted:
                    KernelTestCompleted();
                    break;

                case (byte)TestChannelCommandEnum.TestFailed:
                    KernelTestFailed();
                    break;

                case (byte)TestChannelCommandEnum.AssertionSucceeded:
                    KernelAssertionSucceeded();
                    break;
                }
            }
        }
    private bool VerifyFields()
    {
        if (serverNameComboBox.Text.Trim() == "")
        {
            string text = "Please enter server name.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("servernameMissing");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            serverNameComboBox.Focus();
            return(false);
        }

        if (authenticationComboBox.SelectedIndex == 1)
        {
            if (userNameTextBox.Text.Trim() == "")
            {
                string text = "Please enter user name.";

                if (ConfigHandler.UseTranslation)
                {
                    text = Translator.GetText("usernameMissing");
                }

                OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                userNameTextBox.Focus();
                return(false);
            }
        }

        return(true);
    }
Beispiel #7
0
 private void KernelTestCompleted()
 {
     OutputHandler.SetKernelTestResult(true, "Test completed");
     mKernelResultSet = true;
     mKernelResult    = true;
     mKernelRunning   = false;
 }
    private void DeleteLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string text = "Delete the saved password?";

        if (ConfigHandler.UseTranslation)
        {
            text = Translator.GetText("DeleteSavedValue");
        }

        DialogResult result = OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Information);

        if (result == DialogResult.Yes)
        {
            if (ConfigHandler.RegistryModifyAccess)
            {
                RegistryHandler.Delete("Password_ConnectionString");
                passwordTextBox.Text = "";
            }
            else
            {
                if (ConfigHandler.UseTranslation)
                {
                    MessageBox.Show(Translator.GetText("DeletePasswordNoAccess"));
                }
                else
                {
                    MessageBox.Show("Logged in user does not have necessary rights to delete the saved password.\r\n\r\nUser needs modify access to HKLM in RegEdit.", GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
Beispiel #9
0
//public bool IsCancellationRequested => TokenSource.IsCancellationRequested;

        #endregion

        #region public methods

        public Task Start(CancellationToken token)
        {
            if (!Enabled)
            {
                OutputHandler.OnCompleted();
                CompletedHandler.OnNext((this, DateTime.Now));
                return(Task.CompletedTask);
            }


            var task = Task.Run(async() =>
            {
                StartHandler.OnNext((this, DateTime.Now));
                try
                {
                    token.ThrowIfCancellationRequested();
                    await InternalStart(token);
                }
                catch (OperationCanceledException) { }
                catch (Exception e)
                {
                    ErrorHandler.OnNext(new ConnectorException($"An error occurs while processing {this.GetType().Name}. See Inner Exception", e));
                }
            }, token)
                       .ContinueWith(t => {
                CompletedHandler.OnNext((this, DateTime.Now));
            });

            return(task);
        }
Beispiel #10
0
    public bool DeleteCheckedTraceFiles()
    {
        bool success = true;

        OutputHandler.WriteToLog(string.Format("Deleting Trace Files after import. Number of Trace Files to delete: {0}", traceFileListView.CheckedItems.Count));

        for (int i = 0; i < traceFileListView.CheckedItems.Count; i++)
        {
            string fileName = string.Format(@"{0}\{1}", _traceFileDir, traceFileListView.CheckedItems[i].SubItems[2].Text);

            try
            {
                GenericHelper.DeleteFile(fileName);
            }
            catch (Exception ex)
            {
                success = false;

                string text = "Error deleting Trace File.\r\n\r\n{0}";

                if (ConfigHandler.UseTranslation)
                {
                    text = Translator.GetText("errorDeletingTrace");
                }

                OutputHandler.Show(string.Format(text, ex.Message), GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        return(success);
    }
    private void OkButton_Click(object sender, EventArgs e)
    {
        if (enableCheckBox.Checked && updateServerTextBox.Text.Trim().Length == 0)
        {
            string caption = "Online Settings";

            if (ConfigHandler.UseTranslation)
            {
                caption = Translator.GetText("OnlineSettingsTitle");
            }

            string text = "Update server is missing.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("MissingUpdateServer");
            }

            OutputHandler.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
            updateServerTextBox.Focus();
            return;
        }
        else
        {
            if (enableCheckBox.Checked != _initialAutomaticUpdateEnabled || updateServerTextBox.Text != _initialUpdateServer)
            {
                SaveOptions();
                ChangesMade = true;
            }
        }

        Close();
    }
    private int SearchRegEx(string checkSearchItem, string checkSearchTerm)
    {
        string pattern = checkSearchTerm;

        if (matchWholeWordCheckBox.Checked)
        {
            pattern = string.Format(@"\b({0})\b", checkSearchTerm);
        }

        Match match;

        try
        {
            match = Regex.Match(checkSearchItem, pattern);
        }
        catch (Exception ex)
        {
            OutputHandler.Show(ex.Message, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return(-2);
        }

        if (match.Success)
        {
            return(match.Index);
        }
        else
        {
            return(-1);
        }
    }
Beispiel #13
0
    private static int HandleUnattended(int numberOfImportFiles, string lastImportFile, string importNewerThanSessionId, string sessionId, string postScriptFileName, string postScript, int compressTraceFilesAfterImport, bool deleteTraceFilesAfterImport, string importPath, string columnsXmlFileName, string connectionStringFromCmdLine, bool saveOutputToLogFile, bool forceDelete, string sqlEventAnalyzerDatabaseName, List <string> generateStatisticsNames, List <string> generateStatisticsFilter1Names, List <string> generateStatisticsFilter2Names, string generateStatisticsSavePath, List <string> generateStatisticsSaveWebService)
    {
        if (saveOutputToLogFile)
        {
            StartInteractiveRunLog();
        }

        if (postScriptFileName == null || File.Exists(postScriptFileName))
        {
            return(StartUnattended(postScriptFileName, postScript, numberOfImportFiles, lastImportFile, importNewerThanSessionId, sessionId, compressTraceFilesAfterImport, deleteTraceFilesAfterImport, importPath, columnsXmlFileName, connectionStringFromCmdLine, forceDelete, sqlEventAnalyzerDatabaseName, generateStatisticsNames, generateStatisticsFilter1Names, generateStatisticsFilter2Names, generateStatisticsSavePath, generateStatisticsSaveWebService));
        }
        else
        {
            ConfigHandler.LoadConfig();
            Translator.GenerateDictionary();

            string text = "Post Script File not found.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("postScriptFileNotFound");
            }

            ConfigHandler.SaveOutputToLogFile = saveOutputToLogFile;

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return(1);
        }
    }
Beispiel #14
0
    private void HelpToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        const string helpFile = "SQLEventAnalyzer.pdf";

        if (File.Exists(helpFile))
        {
            try
            {
                Process.Start(helpFile);
            }
            catch (Exception ex)
            {
                OutputHandler.Show(ex.Message, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
        {
            string text = "Help file not found.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("helpFileNotFound");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
Beispiel #15
0
    private static int HandleUseSessionMode(string useSessionId, string columnsXmlFileName, bool verboseMode, string connectionStringFromCmdLine, bool saveOutputToLogFile, bool forceDelete, string applicationName, string sqlEventAnalyzerDatabaseName)
    {
        OutputHandler.WriteToLog("\"-u\" not available when running in a service context.");

        if (!GenericHelper.IsUserInteractive())
        {
            return(1);
        }

        if (saveOutputToLogFile)
        {
            StartInteractiveRunLog();
        }

        MainForm form = new MainForm(useSessionId, columnsXmlFileName, verboseMode, connectionStringFromCmdLine, forceDelete, applicationName, sqlEventAnalyzerDatabaseName);

        int returnCode = form.GetUnattendedExitCode();

        if (returnCode == 0)
        {
            Application.Run(form);
            return(form.GetUnattendedExitCode());
        }
        else
        {
            return(returnCode);
        }
    }
    private static void ShowErrorForm(object arg)
    {
        ErrorFormParams errorFormParams = (ErrorFormParams)arg;
        ErrorForm       form            = new ErrorForm();

        string message = errorFormParams.Message;

        if (ConfigHandler.ActiveCustomColumn != "")
        {
            string text = "Error in Custom Column";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("errorInCustomColumn");
            }

            message = string.Format("{2}: {1}\r\n{0}", message, ConfigHandler.ActiveCustomColumn, text);
        }

        form.SetValues(errorFormParams.OkButtonText, message, errorFormParams.Sql, GenericHelper.InfoText);

        if (GenericHelper.IsUserInteractive())
        {
            form.ShowDialog();
        }

        OutputHandler.WriteToLog(string.Format("{0}\r\n{1}", message, errorFormParams.Sql));

        Application.DoEvents();
    }
Beispiel #17
0
        private void RunIsoInBochs(string iso, string harddisk)
        {
            if (!File.Exists(harddisk))
            {
                throw new FileNotFoundException("Harddisk file not found!", harddisk);
            }

            var xBochsConfig = Path.Combine(mBaseWorkingDirectory, "Kernel.bochsrc");
            var xParams      = new NameValueCollection();

            xParams.Add("ISOFile", iso);
            xParams.Add(BuildPropertyNames.VisualStudioDebugPortString, "Pipe: Cosmos\\Serial");
            xParams.Add(BuildPropertyNames.EnableBochsDebugString, RunWithGDB.ToString());
            xParams.Add(BuildPropertyNames.StartBochsDebugGui, StartBochsDebugGui.ToString());
            var xDebugConnector = new DebugConnectorPipeServer(DebugConnectorPipeServer.DefaultCosmosPipeName);

            InitializeDebugConnector(xDebugConnector);

            var xBochs = new Bochs(xParams, RunWithGDB, new FileInfo(xBochsConfig), harddisk);

            xBochs.OnShutDown = (a, b) =>
            {
            };

            xBochs.RedirectOutput = false;
            xBochs.LogError       = s => OutputHandler.LogDebugMessage(s);
            xBochs.LogOutput      = s => OutputHandler.LogDebugMessage(s);

            HandleRunning(xDebugConnector, xBochs);
        }
Beispiel #18
0
        private void RunIsoInQemu(string iso, string harddisk, string workingDir)
        {
            if (!File.Exists(harddisk))
            {
                throw new FileNotFoundException("Harddisk file not found!", harddisk);
            }

            var xParams = new Dictionary <string, string>
            {
                { BuildPropertyNames.IsoFileString, iso }
            };

            var xDebugConnector = new DebugConnectorPipeClient("Cosmos\\Serial");

            InitializeDebugConnector(xDebugConnector);

            var xQemu = new Qemu(xParams, RunWithGDB, harddisk)
            {
                OnShutDown     = (a, b) => { mKernelRunning = false; },
                RedirectOutput = false,
                LogError       = s => OutputHandler.LogDebugMessage(s),
                LogOutput      = s => OutputHandler.LogDebugMessage(s)
            };

            HandleRunning(xDebugConnector, xQemu);
        }
Beispiel #19
0
    private void RenameToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (traceFileListView.SelectedItems.Count == 0)
        {
            return;
        }

        string initialName = traceFileListView.SelectedItems[0].SubItems[2].Text;
        string newName     = GetName(initialName, initialName);

        if (newName != initialName && newName != null)
        {
            string source = string.Format(@"{0}\{1}", _traceFileDir, initialName);
            string dest   = string.Format(@"{0}\{1}", _traceFileDir, newName);

            try
            {
                File.Move(source, dest);
            }
            catch (Exception ex)
            {
                OutputHandler.Show(ex.Message, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            PopulateTraceFileListView(false);
        }
    }
Beispiel #20
0
    private void TraceRecordingForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_checkingAccessRights)
        {
            e.Cancel = true;
            return;
        }

        if (_traceRunning)
        {
            string text = "Recording in progress.\r\n\r\nAbort operation?";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("abortRecording");
            }

            DialogResult result = OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (result.ToString() == "Yes")
            {
                _databaseOperation.StopDeleteTrace();
                TraceFileHandler.DeleteTraceFile(true, _databaseOperation);
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
Beispiel #21
0
    public static bool FillMissingParameters()
    {
        bool success = true;

        foreach (Parameter parameter in ColumnHelper.ColumnCollection.Parameters)
        {
            if (parameter.Value == "")
            {
                OutputHandler.WriteToLog("Mandatory Parameters not filled.");

                if (!GenericHelper.IsUserInteractive())
                {
                    success = false;
                    break;
                }

                FillParameterForm form = new FillParameterForm();
                form.SetNameValue(parameter.Name);


                DialogResult result = form.ShowDialog();

                if (result == DialogResult.Cancel)
                {
                    success = false;
                    break;
                }
            }
        }

        return(success);
    }
Beispiel #22
0
		public static Exception Log(Exception error, ExceptionType type, OutputHandler OutputCallback)
		{
			lock (Lock)
			{
				OutputHandler callback = new OutputHandler(delegate(Exception e, ExceptionType t) { });
				Errors.Add(new ExceptionItem(error, type));
				if (Output != null)
				{
					callback = Output;
				}
				if (OutputCallback != null)
				{
					callback = OutputCallback;
				}
				if (callback != null)
				{
					callback(error, type);
				}
				Logger.Log(">> Exception Detected >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
				//System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
				//for (int i = 0; i < st.FrameCount; i++)
				//{
				//    System.Diagnostics.StackFrame sf = st.GetFrame(i);
				//    Logger.Log(String.Format(">> File name:{0}\tLine:{1}\tColumn:{2}\tMethodName:{3} ", sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber(), sf.GetMethod().Name));
				//}
				Logger.Log(error.ToString());
			}
			return error;
		}
Beispiel #23
0
    private void OkButton_Click(object sender, EventArgs e)
    {
        if (valueTextBox.Text.Trim().Length == 0)
        {
            string text = "Please enter a value.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("ValueMissing");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            valueTextBox.Focus();

            _allowClose = false;
        }
        else
        {
            foreach (Parameter parameter in ColumnHelper.ColumnCollection.Parameters)
            {
                if (parameter.Name == nameTextBox.Text)
                {
                    parameter.Value = valueTextBox.Text;
                }
            }

            _allowClose = true;
        }
    }
Beispiel #24
0
    public static bool CheckForUniqueParameterNames()
    {
        bool stop = false;

        for (int i = 0; i < ColumnHelper.ColumnCollection.Parameters.Count; i++)
        {
            for (int j = 0; j < ColumnHelper.ColumnCollection.Parameters.Count; j++)
            {
                if (ColumnHelper.ColumnCollection.Parameters[i].Name == ColumnHelper.ColumnCollection.Parameters[j].Name && j != i)
                {
                    string text = "Can't continue while parameter names are not unique.";

                    if (ConfigHandler.UseTranslation)
                    {
                        text = Translator.GetText("ParameterNamesNotUnique");
                    }

                    OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    stop = true;
                    break;
                }
            }

            if (stop)
            {
                return(false);
            }
        }

        return(true);
    }
Beispiel #25
0
    private void HandleColumnForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        _inputSearchForm.Hide();
        _outputSearchForm.Hide();

        if (_textChanged)
        {
            string text = "Save changes?";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("saveChanges");
            }

            DialogResult result = OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);

            if (result.ToString() == "Yes")
            {
                bool closeWindow = Save();

                if (!closeWindow)
                {
                    e.Cancel = true;
                }
            }
            else if (result.ToString() == "Cancel")
            {
                e.Cancel = true;
            }
        }
    }
Beispiel #26
0
        private void PerformJoin()
        {
            if (!_dataCompleted || !_lookupCompleted)
            {
                return;
            }
            try
            {
#pragma warning disable CS8524 // L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive).
                var joinedRows = _join switch
#pragma warning restore CS8524 // L'expression switch ne prend pas en charge toutes les valeurs possibles de son type d'entrée (elle n'est pas exhaustive).
                {
                    TMapJoin.LeftOuter => _dataRows.LeftOuterJoin(_lookupRows, GetLeftKey, GetRightKey, (r, l) => (r, l)).ToList(),
                    TMapJoin.Inner => _dataRows.InnerJoin(_lookupRows, GetLeftKey, GetRightKey, (r, l) => (r, l)).ToList(),
                };
                foreach (var item in joinedRows)
                {
                    OutputHandler.OnNext(Mapper.Map <TOutputSchema>(item.l, item.r));
                }
                OutputHandler.OnCompleted();
            }

            catch (Exception e)
            {
                ErrorHandler.OnNext(new ConnectorException("An error occure while Performing Mapping", e));
            }
        }
Beispiel #27
0
    private bool ValidName(string keyName)
    {
        if (keyName == "")
        {
            string text = "\"Name\" can't be empty.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("emptyName");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            nameTextBox.Focus();
            return(false);
        }

        if (keyName == "id" || keyName == "filename" || keyName == "type" || keyName == "textdata" || keyName == "spid" || keyName == "duration" || keyName == "starttime" || keyName == "reads" || keyName == "writes" || keyName == "cpu" || keyName == "rows" || IsNameStatisticsName(keyName))
        {
            string text = "Invalid \"Name\".";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("invalidName");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            nameTextBox.Focus();
            return(false);
        }

        return(true);
    }
Beispiel #28
0
    private bool ValidOutput(string output)
    {
        if (output == "" && ((ComboBoxItem)outputTypeComboBox.SelectedItem).ColumnType != Column.ColumnType.StoredProcedureName && ((ComboBoxItem)outputTypeComboBox.SelectedItem).ColumnType != Column.ColumnType.Constant)
        {
            string text = "Output can't be empty.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("emptyOutput");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            outputTextEditorControl.Focus();
            return(false);
        }

        if (output.Length > 4000)
        {
            string text = "Output length exceeds 4000 characters.\r\nMaximum length allowed is 4000 characters.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("outputLength");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            outputTextEditorControl.Focus();
            return(false);
        }

        return(true);
    }
    private void DatabaseOperation_ExportSessionToSessionReadyEvent(bool success)
    {
        _databaseOperation.ExportSessionToSessionReadyEvent -= DatabaseOperation_ExportSessionToSessionReadyEvent;

        if (success)
        {
            string text = "Export successful.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("ExportSuccessful");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            string text = "Export failed.";

            if (ConfigHandler.UseTranslation)
            {
                text = Translator.GetText("ExportFailed");
            }

            OutputHandler.Show(text, GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        Close();
    }
Beispiel #30
0
 private void KernelTestFailed()
 {
     OutputHandler.SetKernelTestResult(false, "Test failed");
     mKernelResultSet = true;
     mKernelResult    = false;
     mKernelRunning   = false;
 }
Beispiel #31
0
    public void DeleteSelectedTraceFiles()
    {
        for (int i = 0; i < traceFileListView.SelectedItems.Count; i++)
        {
            string fileName = string.Format(@"{0}\{1}", _traceFileDir, traceFileListView.SelectedItems[i].SubItems[2].Text);

            try
            {
                GenericHelper.DeleteFile(fileName);
            }
            catch (Exception ex)
            {
                string text = "Error deleting Trace File.\r\n\r\n{0}";

                if (ConfigHandler.UseTranslation)
                {
                    text = Translator.GetText("errorDeletingTrace");
                }

                OutputHandler.Show(string.Format(text, ex.Message), GenericHelper.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        RefreshTraceFileListView();
    }
Beispiel #32
0
        internal BfdDisassembler(Process process, bool is_x86_64)
        {
            this.process = process;

            read_handler = new ReadMemoryHandler (read_memory_func);
            output_handler = new OutputHandler (output_func);
            print_handler = new PrintAddressHandler (print_address_func);

            handle = bfd_glue_create_disassembler (
                is_x86_64, read_handler, output_handler, print_handler);
        }
Beispiel #33
0
 static extern IntPtr bfd_glue_create_disassembler(bool is_x86_64, ReadMemoryHandler read_memory_cb, OutputHandler output_cb, PrintAddressHandler print_address_cb);
        /// <summary>
        /// Resizes the specified texture and/or generates mipmaps.
        /// </summary>
        /// <param name="texture">The texture.</param>
        /// <param name="width">The desired width.</param>
        /// <param name="height">The desired height.</param>
        /// <param name="inputGamma">The input gamma.</param>
        /// <param name="outputGamma">The output gamma.</param>
        /// <param name="generateMipmaps">
        /// <see langword="true"/> to generate all mipmap levels; otherwise <see langword="false"/>.
        /// </param>
        /// <param name="hasAlpha">
        /// <see langword="true"/> if <paramref name="texture"/> requires an alpha channel; otherwise,
        /// <see langword="false"/> if <paramref name="texture"/> is opaque.
        /// </param>
        /// <param name="hasFractionalAlpha">
        /// <see langword="true"/> if <paramref name="texture"/> contains fractional alpha values;
        /// otherwise, <see langword="false"/> if <paramref name="texture"/> is opaque or contains only
        /// binary alpha.
        /// </param>
        /// <param name="premultipliedAlpha">
        /// <see langword="true"/> when <paramref name="texture"/> is using premultiplied alpha.;
        /// otherwise, <see langword="false"/>.</param>
        /// <returns>The resized texture.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="texture"/> is <see langword="null"/>.
        /// </exception>
        public static Texture ResizeAndGenerateMipmaps(Texture texture, int width, int height, float inputGamma, float outputGamma, bool generateMipmaps, bool hasAlpha, bool hasFractionalAlpha, bool premultipliedAlpha)
        {
            if (texture == null)
            throw new ArgumentNullException("texture");

              // NVIDIA Texture Tools expect BGRA 8:8:8:8.
              if (texture.Description.Format != TextureFormat.B8G8R8A8_UNorm)
            throw new ArgumentException("Texture format needs to be B8G8R8A8_UNORM.", "texture");

              if (texture.Description.Dimension != TextureDimension.TextureCube && texture.Description.ArraySize > 1)
            throw new NotSupportedException("Resizing and mipmap generation for texture arrays is not supported.");
              if (texture.Description.Dimension == TextureDimension.Texture3D)
            throw new NotSupportedException("Resizing and mipmap generation for volume textures is not supported.");

              // ----- InputOptions
              var inputOptions = new InputOptions();
              inputOptions.SetAlphaMode(hasAlpha ? (premultipliedAlpha ? AlphaMode.Premultiplied : AlphaMode.Transparency)
                                         : AlphaMode.None);
              inputOptions.SetFormat(InputFormat.BGRA_8UB);
              inputOptions.SetGamma(inputGamma, outputGamma);
              inputOptions.SetMipmapFilter(MipmapFilter.Box);
              inputOptions.SetMipmapGeneration(generateMipmaps);
              bool roundToPowerOfTwo = (width != texture.Description.Width || height != texture.Description.Height);
              inputOptions.SetRoundMode(roundToPowerOfTwo ? RoundMode.ToNextPowerOfTwo : RoundMode.None);
              inputOptions.SetWrapMode(WrapMode.Mirror);

              var description = texture.Description;
              bool isCube = description.Dimension == TextureDimension.TextureCube;
              var textureType = isCube ? TextureType.TextureCube : TextureType.Texture2D;
              inputOptions.SetTextureLayout(textureType, description.Width, description.Height, 1);

              for (int arrayIndex = 0; arrayIndex < description.ArraySize; arrayIndex++)
              {
            for (int mipIndex = 0; mipIndex < description.MipLevels; mipIndex++)
            {
              int index = texture.GetImageIndex(mipIndex, arrayIndex, 0);
              var image = texture.Images[index];
              var handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
              inputOptions.SetMipmapData(handle.AddrOfPinnedObject(), image.Width, image.Height, 1, arrayIndex, mipIndex);
              handle.Free();
            }
              }

              // ----- OutputOptions
              var outputOptions = new OutputOptions();
              outputOptions.SetOutputHeader(false);
              outputOptions.Error += OnError;

              description.Format = TextureFormat.R8G8B8A8_UNorm;
              description.Width = width;
              description.Height = height;
              description.MipLevels = generateMipmaps ? CalculateMipLevels(width, height) : 1;
              var resizedTexture = new Texture(description);
              var outputHandler = new OutputHandler(resizedTexture);
              outputOptions.SetOutputHandler(outputHandler.BeginImage, outputHandler.WriteData);

              // ----- CompressionOptions
              var compressionOptions = new CompressionOptions();
              compressionOptions.SetFormat(Format.RGBA);
              compressionOptions.SetPixelFormat(32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000);
              compressionOptions.SetQuality(Quality.Normal);

              // ----- Run NVTT
              try
              {
            var compressor = new Compressor();
            compressor.Compress(inputOptions, compressionOptions, outputOptions);
              }
              catch (NullReferenceException)
              {
            // Resizing and mipmap generation without compression sometimes causes a
            // NullReferenceException in nvttCompress().
            throw new Exception("NullReferenceException in NVIDIA texture tools. Please try again.");
              }

              return resizedTexture;
        }
        /// <summary>
        /// Compresses the specified texture using a Block Compression format (BC<i>n</i>).
        /// </summary>
        /// <param name="texture">The uncompressed texture.</param>
        /// <param name="inputGamma">The input gamma.</param>
        /// <param name="outputGamma">The output gamma.</param>
        /// <param name="generateMipmaps">
        /// <see langword="true"/> to generate all mipmap levels; otherwise <see langword="false"/>.
        /// </param>
        /// <param name="hasAlpha">
        /// <see langword="true"/> if <paramref name="texture"/> requires an alpha channel; otherwise,
        /// <see langword="false"/> if <paramref name="texture"/> is opaque.
        /// </param>
        /// <param name="hasFractionalAlpha">
        /// <see langword="true"/> if <paramref name="texture"/> contains fractional alpha values;
        /// otherwise, <see langword="false"/> if <paramref name="texture"/> is opaque or contains only
        /// binary alpha.
        /// </param>
        /// <param name="premultipliedAlpha">
        /// <see langword="true"/> when <paramref name="texture"/> is using premultiplied alpha.;
        /// otherwise, <see langword="false"/>.</param>
        /// <param name="sharpAlpha">
        /// <see langword="true"/> when the texture contains a sharp alpha mask; otherwise
        /// <see langword="false"/>.
        /// </param>
        /// <returns>The compressed texture.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="texture"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Texture width and height need to be equal (square texture) and  a power of two (POT
        /// texture).
        /// </exception>
        internal static Texture CompressBCn(Texture texture, float inputGamma, float outputGamma, bool generateMipmaps, bool hasAlpha, bool hasFractionalAlpha, bool premultipliedAlpha, bool sharpAlpha = false)
        {
            if (texture == null)
            throw new ArgumentNullException("texture");
              if (texture.Description.Dimension == TextureDimension.Texture3D)
            throw new NotSupportedException("Texture compression for volume textures is not supported.");

              // NVIDIA Texture Tools expect BGRA 8:8:8:8.
              texture = texture.ConvertTo(TextureFormat.B8G8R8A8_UNorm);

              // ----- InputOptions
              var inputOptions = new InputOptions();
              inputOptions.SetAlphaMode(hasAlpha ? (premultipliedAlpha ? AlphaMode.Premultiplied : AlphaMode.Transparency)
                                         : AlphaMode.None);
              inputOptions.SetFormat(InputFormat.BGRA_8UB);
              inputOptions.SetGamma(inputGamma, outputGamma);
              inputOptions.SetMipmapFilter(MipmapFilter.Box);
              inputOptions.SetMipmapGeneration(generateMipmaps);
              inputOptions.SetRoundMode(RoundMode.None);  // Size is set explicitly.
              inputOptions.SetWrapMode(WrapMode.Mirror);

              var description = texture.Description;
              bool isCube = description.Dimension == TextureDimension.TextureCube;
              var textureType = isCube ? TextureType.TextureCube : TextureType.Texture2D;
              inputOptions.SetTextureLayout(textureType, description.Width, description.Height, 1);

              for (int arrayIndex = 0; arrayIndex < description.ArraySize; arrayIndex++)
              {
            for (int mipIndex = 0; mipIndex < description.MipLevels; mipIndex++)
            {
              int index = texture.GetImageIndex(mipIndex, arrayIndex, 0);
              var image = texture.Images[index];
              var handle = GCHandle.Alloc(image.Data, GCHandleType.Pinned);
              inputOptions.SetMipmapData(handle.AddrOfPinnedObject(), image.Width, image.Height, 1, arrayIndex, mipIndex);
              handle.Free();
            }
              }

              // ----- OutputOptions
              var outputOptions = new OutputOptions();
              outputOptions.SetOutputHeader(false);
              outputOptions.Error += OnError;

              Format compressedFormat;
              if (hasAlpha)
              {
            if (sharpAlpha)
            {
              compressedFormat = Format.BC2;
              description.Format = TextureFormat.BC2_UNorm;
            }
            else
            {
              compressedFormat = Format.BC3;
              description.Format = TextureFormat.BC3_UNorm;
            }
              }
              else
              {
            compressedFormat = Format.BC1;
            description.Format = TextureFormat.BC1_UNorm;
              }
              var compressedTexture = new Texture(description);
              var outputHandler = new OutputHandler(compressedTexture);
              outputOptions.SetOutputHandler(outputHandler.BeginImage, outputHandler.WriteData);

              // ----- CompressionOptions
              var compressionOptions = new CompressionOptions();
              compressionOptions.SetFormat(compressedFormat);
              compressionOptions.SetQuality(Quality.Normal);

              // ----- Run NVTT
              try
              {
            var compressor = new Compressor();
            compressor.Compress(inputOptions, compressionOptions, outputOptions);
              }
              catch (NullReferenceException)
              {
            throw new Exception("NullReferenceException in NVIDIA texture tools. Please try again.");
              }

              return compressedTexture;
        }
Beispiel #36
0
        /// <summary>
        /// 运行程序
        /// </summary>
        /// <param name="appName">程序名</param>
        /// <param name="workDir">工作目录</param>
        /// <param name="handler">回调事件</param>
        /// <param name="exitProcessHandler">退出关闭事件</param>
        public static Process RunFile(string appName, string workDir, OutputHandler handler, EventHandler exitProcessHandler)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = appName;
            proc.StartInfo.Arguments = "";
            proc.StartInfo.WorkingDirectory = workDir;

            proc.StartInfo.UseShellExecute = false;
            //重定向标准输入
            proc.StartInfo.RedirectStandardInput = true;
            //重定向标准输出
            proc.StartInfo.RedirectStandardOutput = true;
            //增加接收数据委托事件
            proc.OutputDataReceived += new DataReceivedEventHandler(handler);// (PreProcess_OutputHandler);
            //重定向错误输出
            proc.StartInfo.RedirectStandardError = true;
            //设置不显示窗口
            proc.StartInfo.CreateNoWindow = true;

            //增加退出事件
            if (exitProcessHandler != null)
            {
                proc.EnableRaisingEvents = true;    //一定要有这个才能触发Exited 事件
                proc.Exited += new EventHandler(exitProcessHandler);
            }

            try
            {
                proc.Start();
                proc.BeginOutputReadLine();//开启异步读取输出流
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }

            return proc;
        }