Exemplo n.º 1
0
        private void DoFilterDataTable()
        {
            if (String.IsNullOrEmpty(txtFilterDt.Text))
            {
                ClearFilter();
                return;
            }

            Cursor currentCursor = Cursor.Current;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                ShowStatusProgress("Filtering data...");
                if (ddlFilterType.Text == "Custom")
                {
                    CustomFilterDataTable(txtFilterDt.Text);
                }
                else if (ddlFilterType.Text == "Like")
                {
                    LikeSearchDataTable(txtFilterDt.Text);
                }
            }
            catch (Exception ex)
            {
                GenericErrorDialog.ShowError("Filter Error", "Invalid filter expression", ex.Message);
            }
            finally
            {
                Cursor.Current = currentCursor;
                HideStatusProgress();
            }
        }
Exemplo n.º 2
0
        internal static bool Load()
        {
            bool result = false;

            try
            {
                frmSplashScreen.PrintStatus("Loading AddIns...");

                // Searches for ".addin" files in the application directory.
                string addInDir = Path.Combine(FileUtility.ApplicationRootPath, "AddIns");
                if (!Directory.Exists(addInDir))
                {
                    Directory.CreateDirectory(addInDir);
                }

                ICSharpCoreWrapper.Core.AddAddInsFromDirectory(addInDir);

                // Searches for a "AddIns.xml" in the user profile that specifies the names of the
                // add-ins that were deactivated by the user, and adds "external" AddIns.
                ICSharpCoreWrapper.Core.ConfigureExternalAddIns(Path.Combine(PropertyService.ConfigDirectory, "AddIns.xml"));

                // Searches for add-ins installed by the user into his profile directory. This also
                // performs the job of installing, uninstalling or upgrading add-ins if the user
                // requested it the last time this application was running.
                ICSharpCoreWrapper.Core.ConfigureUserAddIns(Path.Combine(PropertyService.ConfigDirectory, "AddInInstallTemp"),
                                                            Path.Combine(PropertyService.ConfigDirectory, "AddIns"));

                LoggingService.Info("Loading AddInTree...");
                // Now finally initialize the application. This parses the ".addin" files and
                // creates the AddIn tree. It also automatically runs the commands in
                // "/Workspace/Autostart"
                ICSharpCoreWrapper.Core.RunInitialization();

                if (ICSharpCoreWrapper.Core.AddInLoadErrors.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string err in ICSharpCoreWrapper.Core.AddInLoadErrors)
                    {
                        LoggingService.Error(err);
                        sb.AppendLine(err);
                    }

                    GenericErrorDialog.ShowError("Error", "Can not load listed AddIns.", sb.ToString());
                }

                LoggingService.Info("AddIns loaded sucessfully.");
                result = true;
            }
            catch (Exception ex)
            {
                frmSplashScreen.HideSplash();
                frmException.ShowAppError("Fatal Error : AddIns can not be loaded", ex);
            }

            return(result);
        }
Exemplo n.º 3
0
        private void AddNodesToSelectedObjectGroup()
        {
            TreeNode selNode = og.SelectedNode;

            if (selNode == null)
            {
                ShowError("Please select an object grouping folder!");
                return;
            }

            ObjectGroupingItemData selData = ObjectGroupingItemDataFactory.GetNodeData(selNode);

            if (selData.Type != DBObjectType.GroupingFolderY)
            {
                ShowError("Please select an object grouping folder!");
                return;
            }

            StringBuilder sb = new StringBuilder();

            foreach (TreeNode node in _nodes)
            {
                try
                {
                    if (_isImport)
                    {
                        og.ImportObject(node, selNode, true);
                    }
                    else
                    {
                        og.AddObjectFromObjectExplorer(node, selNode, true);
                    }
                }
                catch (Exception ex)
                {
                    sb.AppendLine("-> " + ex.Message);
                }
            }

            if (sb.Length > 0)
            {
                GenericErrorDialog.ShowError("Object Grouping Error", "Some objects can not be added to selected group folder.", sb.ToString());
            }
            this.DialogResult = DialogResult.OK;
        }
Exemplo n.º 4
0
        private void PostAction(DbObjectScripterResult result, bool isCancelled)
        {
            string errors = String.Empty;

            if (result.errors != null && result.errors.Count > 0)
            {
                if (!isCancelled)
                {
                    lblStatus.Text = "Completed with errors!";
                }

                foreach (Exception ex in result.errors)
                {
                    errors += "- " + ex.Message.Replace("\n", " ").Replace("\r", " ") + "\r\n";
                }
            }
            else
            {
                if (!isCancelled)
                {
                    lblStatus.Text = "Completed. Press \"Start\" to script objects.";
                }
            }

            switch (_destination)
            {
            case ScriptDestination.Window:
                string          caption = "Database Objects [" + _connParams.Server + " {" + _connParams.Database + "} ]";
                frmScriptEditor frm     = ScriptEditorFactory.Create(caption, result.script, _connParams);
                ScriptEditorFactory.ShowScriptEditor(frm);
                break;

            case ScriptDestination.File:
                File.AppendAllText(_destPath, result.script);
                break;

            case ScriptDestination.Folder:
                break;
            }

            if (!String.IsNullOrEmpty(errors))
            {
                GenericErrorDialog.ShowError("Error", "Scripting completed with errors! See details below.", errors);
            }
        }
Exemplo n.º 5
0
        private void BackgroundWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                DisposeScripter();
                _isInProgress = false;

                btnStart.Enabled  = true;
                btnClose.Enabled  = true;
                btnStop.Enabled   = false;
                groupBox1.Enabled = true;
                groupBox2.Enabled = true;
                groupBox3.Enabled = true;

                bool isCancelled = false;

                if (e.Cancelled)
                {
                    lblStatus.Text = "Scripting cancelled!";
                    isCancelled    = true;
                    return;
                }

                if (e.Error != null)
                {
                    lblStatus.Text = "Worker thread error occured!";
                    GenericErrorDialog.ShowError("Error", "Worker thread error occured.See details below.", e.Error.Message);
                    return;
                }

                DbObjectScripterResult result = e.Result as DbObjectScripterResult;
                if (result == null)
                {
                    lblStatus.Text = "Nothing was scripted!";
                    return;
                }

                PostAction(result, isCancelled);
            }
            finally
            {
                System.Media.SystemSounds.Exclamation.Play();
                this.BringToFront();
            }
        }
Exemplo n.º 6
0
        private void RegisterRenderers()
        {
            try
            {
                Type t = typeof(VirtualResultRendererFactory);
                IResultRendererFactory factory = Activator.CreateInstance(t) as IResultRendererFactory;

                ResultRendererSpec spec = new ResultRendererSpec();
                spec.Name         = factory.FactoryName;
                spec.Description  = factory.FactoryDescription;
                spec.FullName     = String.Format("{0}, {1}", t.FullName, t.Assembly.FullName);
                spec.RendererType = t;

                HostServicesSingleton.HostServices.ResultRendererService.Register(spec);

                t       = typeof(VirtualResultRendererFactory_AllInOne);
                factory = Activator.CreateInstance(t) as IResultRendererFactory;

                spec              = new ResultRendererSpec();
                spec.Name         = factory.FactoryName;
                spec.Description  = factory.FactoryDescription;
                spec.FullName     = String.Format("{0}, {1}", t.FullName, t.Assembly.FullName);
                spec.RendererType = t;
                HostServicesSingleton.HostServices.ResultRendererService.Register(spec);



                t       = typeof(PaletteCompatibleRendererFactory);
                factory = Activator.CreateInstance(t) as IResultRendererFactory;

                spec              = new ResultRendererSpec();
                spec.Name         = factory.FactoryName;
                spec.Description  = factory.FactoryDescription;
                spec.FullName     = String.Format("{0}, {1}", t.FullName, t.Assembly.FullName);
                spec.RendererType = t;

                HostServicesSingleton.HostServices.ResultRendererService.Register(spec);
            }
            catch (Exception ex)
            {
                GenericErrorDialog.ShowError("PragmaSQL.VirtualResultRenderers Error", "Can not register result renderers.", ex);
            }
        }
Exemplo n.º 7
0
		private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
      if (TaskbarManager.IsPlatformSupported)
      {
        TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.NoProgress,this.Handle);
        TaskbarManager.Instance.SetProgressValue(0,100,this.Handle);
      }

      timer1.Enabled = false;
			lblTimer.Text = "Elapsed: 00:00:00";

			lblRowPrg.Text = String.Empty;
			pbRow.Value = 0;
			_copying = false;
			_cancelled = false;

			wizardControl1.NextButtonEnabled = true;
			wizardControl1.BackButtonEnabled = true;

			if (e.Cancelled)
			{
				lblOverallPrg.Text = "Cancelled by the user";
				lblTotal.Text = String.Empty;
				return;
			}
			else if (e.Error == null)
			{
				lblOverallPrg.Text = "Completed";
			}

			if (e.Error != null)
			{
				lblOverallPrg.Text = "Terminated with errors";
				lblTotal.Text = String.Empty;
				GenericErrorDialog.ShowError("Bulk Copy Error", "Bulk copy terminated because the following error occured.", e.Error);
				return;
			}

			BulkCopyResult result = e.Result as BulkCopyResult;
			DisplayErrors(result.Errors);
		}
Exemplo n.º 8
0
        private void DumpObjectInfos()
        {
            if (HostServicesSingleton.HostServices == null || HostServicesSingleton.HostServices.ObjectExplorerService == null)
            {
                throw new InvalidOperationException("ObjectExplorer is not active or visible!");
            }

            IList <ObjectExplorerNode> selNodes = HostServicesSingleton.HostServices.ObjectExplorerService.SelNodes;

            IDictionary <string, StringBuilder> dumpJobs = new Dictionary <string, StringBuilder>();
            StringBuilder sb = null;

            string template = "{0}=[{1}].[{2}]";
            string objType  = String.Empty;
            string dbInfo   = String.Empty;

            foreach (ObjectExplorerNode node in selNodes)
            {
                if (!DBObjectType.CanTypeBeDumpedForScriptingWizardUsage(node.Type))
                {
                    continue;
                }
                if (node.ConnParams == null)
                {
                    continue;
                }

                dbInfo = node.DatabaseName + " on " + node.ConnParams.Server;
                if (dumpJobs.ContainsKey(dbInfo))
                {
                    sb = dumpJobs[dbInfo];
                }
                else
                {
                    sb = new StringBuilder();
                    dumpJobs.Add(dbInfo, sb);
                }

                objType = DbObjectListUtils.EncodeObjectExplorerNodeType(node.Type);
                sb.AppendLine(String.Format(template, objType, node.Owner, node.Name));
            }

            string editorCaption = String.Empty;
            string errors        = String.Empty;

            foreach (string info in dumpJobs.Keys)
            {
                sb = dumpJobs[info];
                try
                {
                    editorCaption = "Objects [" + info + "]";
                    HostServicesSingleton.HostServices.EditorServices.CreateTextEditor(editorCaption, sb.ToString());
                }
                catch (Exception ex)
                {
                    errors += "Error Type: " + ex.GetType().Name + ", Message: " + ex.Message + "\r\n";
                }
            }

            if (!String.IsNullOrEmpty(errors))
            {
                GenericErrorDialog.ShowError("Dump Error", "Some errors occured during object dump.", errors);
            }
        }
Exemplo n.º 9
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            try
            {
                ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(int.MaxValue));

                _taskbarIcon = (TaskbarIcon)FindResource("TaskbarIcon");
                _taskbarIcon.DoubleClickCommand = ApplicationManager.Instance.OpenConfigurationCommand;

                Settings settings = null;
                try { settings = JsonConvert.DeserializeObject <Settings>(File.ReadAllText(PATH_SETTINGS), new ColorSerializer()); }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    /* File doesn't exist or is corrupt - just create a new one. */
                }

                AppSettings appsettings = null;
                try { appsettings = JsonConvert.DeserializeObject <AppSettings>(File.ReadAllText(PATH_APPSETTINGS), new ColorSerializer()); }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    /* File doesn't exist or is corrupt - just create a new one. */
                }

                if (settings == null)
                {
                    settings = new Settings {
                        Version = Settings.CURRENT_VERSION
                    };
                    _taskbarIcon.ShowBalloonTip("JackNet RGB Sync is starting in the tray!", "Click on the icon to open the configuration.", BalloonIcon.Info);
                }

                else if (settings.Version != Settings.CURRENT_VERSION)
                {
                    ConfigurationUpdates.PerformOn(settings);
                }

                if (appsettings == null)
                {
                    appsettings = new AppSettings {
                        Version = AppSettings.CURRENT_VERSION
                    };
                }


                ApplicationManager.Instance.Settings    = settings;
                ApplicationManager.Instance.AppSettings = appsettings;
                ApplicationManager.Instance.Initialize();
                if (!appsettings.MinimizeToTray) //HACK Fanman03 05.12.2019: Workaround to create the window
                {
                    ApplicationManager.Instance.OpenConfigurationCommand.Execute(null);
                    ApplicationManager.Instance.HideConfigurationCommand.Execute(null);
                }
            }
            catch (Exception ex)
            {
                File.WriteAllText("error.log", $"[{DateTime.Now:G}] Exception!\r\n\r\nMessage:\r\n{ex.GetFullMessage()}\r\n\r\nStackTrace:\r\n{ex.StackTrace}\r\n\r\n");
                GenericErrorDialog dialog = new GenericErrorDialog("An error occured while starting JackNet RGB Sync.\r\nMore information can be found in the error.log file in the application directory.", "Can't start JackNet RGB Sync.", $"[{DateTime.Now:G}] Exception!\r\n\r\nMessage:\r\n{ex.GetFullMessage()}\r\n\r\nStackTrace:\r\n{ex.StackTrace}\r\n\r\n");
                dialog.Show();

                try { ApplicationManager.Instance.ExitCommand.Execute(null); }
                catch { Environment.Exit(0); }
            }
        }
Exemplo n.º 10
0
        private void PerformRestore()
        {
            ConnectionParams        cp            = null;
            IList <frmTextEditor>   textEditors   = new List <frmTextEditor>();
            IList <frmScriptEditor> scriptEditors = new List <frmScriptEditor>();
            StringBuilder           sbErrors      = new StringBuilder();
            bool   showTextEditorInfoHeader       = false;
            bool   failedConnections = false;
            string scriptWarningText = String.Empty;

            InitializeProgress(lv.CheckedItems.Count);
            try
            {
                foreach (ListViewItem lvItem in lv.Items)
                {
                    cp = null;
                    scriptWarningText = String.Empty;
                    RecoverContent item = lvItem.Tag as RecoverContent;
                    if (!lvItem.Checked || item == null)
                    {
                        continue;
                    }

                    string itemCaption = item.Title;
                    failedConnections        = false;
                    showTextEditorInfoHeader = false;
                    frmTextEditor   txtEditor    = null;
                    frmScriptEditor scriptEditor = null;

                    try
                    {
                        if (item.ItemType == RecoverContentType.Script || item.ItemType == RecoverContentType.ScriptFile)
                        {
                            if (item.HasConnectionInfo)
                            {
                                cp = PrepareWorkspaceItemConnection(item, out failedConnections);

                                if (cp == null && !failedConnections)
                                {
                                    Utils.ShowWarning(String.Format(Properties.Resources.RecoverScriptWarning, item.Database, item.Server), MessageBoxButtons.OK);
                                }
                            }

                            if (cp == null)
                            {
                                item.SyntaxMode = "SQL";
                                if (item.ItemType == RecoverContentType.Script)
                                {
                                    item.ItemType = RecoverContentType.Text;
                                }
                                else if (item.ItemType == RecoverContentType.ScriptFile)
                                {
                                    item.ItemType = RecoverContentType.TextFile;
                                }
                                showTextEditorInfoHeader = true;
                                scriptWarningText        = !item.HasConnectionInfo ? Properties.Resources.RecoverScript_NoConnWarningInfoHeader
                  : String.Format(Properties.Resources.RecoverScriptWarningInfoHeader, item.Database, item.Server);
                            }
                            else
                            {
                                if (item.ItemType == RecoverContentType.Script)
                                {
                                    scriptEditor = ScriptEditorFactory.CreateWithAsyncConnection(itemCaption, item.Content, cp, cp.Database, String.Empty);
                                }
                                else if (item.ItemType == RecoverContentType.ScriptFile)
                                {
                                    scriptEditor = ScriptEditorFactory.CreateWithAsyncConnection(itemCaption, item.Content, cp, cp.Database, item.FileName);
                                }

                                scriptEditor.Uid = item.Uid;
                                scriptEditor.IsRecoveredContent = true;
                                scriptEditor.ObjectType         = item.ObjectType;
                                if (OpMode == OperationMode.Recover)
                                {
                                    scriptEditor.ShowInfo(String.Format("Recovered content. Content automatically saved on {0}", DateTime.FromFileTime(item.Time)));
                                }
                                scriptEditors.Add(scriptEditor);
                            }
                        }

                        txtEditor = null;
                        switch (item.ItemType)
                        {
                        case RecoverContentType.Script:
                        case RecoverContentType.ScriptFile:
                            break;

                        case RecoverContentType.SharedScript:
                            txtEditor = TextEditorFactory.CreateSharedScript(itemCaption, item.Content);
                            txtEditor.SetSyntaxMode("SQL");
                            txtEditor.Uid = item.Uid;
                            txtEditor.IsRecoveredContent = true;
                            break;

                        case RecoverContentType.SharedSnippet:
                            txtEditor = TextEditorFactory.CreateSharedSnippet(itemCaption, item.Content);
                            txtEditor.SetSyntaxMode("SQL");
                            txtEditor.Uid = item.Uid;
                            txtEditor.IsRecoveredContent = true;
                            break;

                        case RecoverContentType.Text:
                            txtEditor     = TextEditorFactory.Create(itemCaption, item.Content, item.SyntaxMode);
                            txtEditor.Uid = item.Uid;
                            txtEditor.IsRecoveredContent = true;
                            break;

                        case RecoverContentType.TextFile:
                            txtEditor     = TextEditorFactory.Create(itemCaption, item.Content, item.SyntaxMode, item.FileName);
                            txtEditor.Uid = item.Uid;
                            txtEditor.IsRecoveredContent = true;
                            break;

                        default:
                            throw new Exception(String.Format("Unknowm item type: {0}", item.ItemType));
                        }

                        if (txtEditor != null)
                        {
                            if (showTextEditorInfoHeader)
                            {
                                txtEditor.ShowInfo(scriptWarningText);
                            }
                            else if (OpMode == OperationMode.Recover)
                            {
                                txtEditor.ShowInfo(String.Format("Recovered content. Automatically saved on: {0}", DateTime.FromFileTime(item.Time)));
                            }

                            textEditors.Add(txtEditor);
                        }

                        ChangeProgress(String.Format("Restoring {0}", item.Title));
                    }
                    catch (Exception ex)
                    {
                        sbErrors.AppendLine(String.Format("- Can not restore '{0} ({1})'. Error: {2}", item.Title, item.ItemType, ex.Message));
                    }
                    Application.DoEvents();
                }
            }
            finally
            {
                ResetProgress();
            }

            try
            {
                this.Visible = false;
                foreach (frmTextEditor editor in textEditors)
                {
                    TextEditorFactory.ShowTextEditor(editor);
                }
                foreach (frmScriptEditor editor in scriptEditors)
                {
                    ScriptEditorFactory.ShowScriptEditor(editor);
                }
            }
            catch (Exception ex)
            {
                this.Visible = true;
                throw ex;
            }

            if (sbErrors.Length > 0)
            {
                GenericErrorDialog.ShowError("Content Restore Error", "Some content items can not be restored.", sbErrors.ToString());
            }
        }
Exemplo n.º 11
0
        public static void ExportAll(IList <ScriptExecutionResult> executionResults)
        {
            if (executionResults == null || executionResults.Count == 0)
            {
                return;
            }


            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            ApplicationClass excelApp = null;

            try
            {
                // Create the Excel Application object
                excelApp         = new ApplicationClass();
                excelApp.Visible = true;

                // Create a new Excel Workbook
                Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);

                //for (int i = 1; i <= excelWorkbook.Sheets.Count ;i++ )
                //{
                //  Worksheet sheet = (Worksheet)excelWorkbook.Sheets.get_Item(i);
                //  sheet.Visible = XlSheetVisibility.xlSheetVeryHidden;
                //}

                int sheetIndex = 0;
                int erIndex    = 0;
                int dsIndex    = 0;

                for (int i = executionResults.Count - 1; i >= 0; i--)
                {
                    ScriptExecutionResult sr = executionResults[i];
                    erIndex++;
                    dsIndex = 0;
                    foreach (System.Data.DataSet dataset in sr.DataSets)
                    {
                        dsIndex++;
                        sheetIndex = 0;
                        System.Windows.Forms.Application.DoEvents();

                        // Copy each DataTable
                        foreach (System.Data.DataTable dt in dataset.Tables)
                        {
                            // Copy the DataTable to an object array
                            object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];

                            // Copy the column names to the first row of the object array
                            for (int col = 0; col < dt.Columns.Count; col++)
                            {
                                rawData[0, col] = dt.Columns[col].ColumnName;
                            }


                            // Copy the values to the object array
                            for (int col = 0; col < dt.Columns.Count; col++)
                            {
                                for (int row = 0; row < dt.Rows.Count; row++)
                                {
                                    rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                                    System.Windows.Forms.Application.DoEvents();
                                }
                            }

                            // Calculate the final column letter
                            string finalColLetter = string.Empty;
                            //string colCharset = "ABCDEFGÐHIÝJKLMNOÖPQRSÞTUÜVWXYZ";
                            string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

                            int colCharsetLen = colCharset.Length;

                            if (dt.Columns.Count > colCharsetLen)
                            {
                                finalColLetter = colCharset.Substring(
                                    (dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                            }

                            finalColLetter += colCharset.Substring(
                                (dt.Columns.Count - 1) % colCharsetLen, 1);

                            // Create a new Sheet
                            sheetIndex++;
                            Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
                                Type.Missing, excelWorkbook.Sheets.get_Item(excelWorkbook.Sheets.Count), 1, XlSheetType.xlWorksheet);

                            excelSheet.Name = String.Format("{0}.{1} Result {2}", erIndex, dsIndex, sheetIndex);

                            // Fast data export to Excel
                            string excelRange = string.Format("A1:{0}{1}",
                                                              finalColLetter, dt.Rows.Count + 1);

                            excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;

                            // Mark the first row as BOLD
                            ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
                        }
                    }
                }

                excelApp.Visible     = true;
                excelApp.UserControl = true;
                Utils.ShowInfo("Fast export to excel completed.", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                GenericErrorDialog.ShowError("Error", "Can not export resultsets to excel.", ex);
                if (excelApp != null)
                {
                    excelApp.Quit();
                    excelApp = null;

                    // Collect the unreferenced objects
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
        }
Exemplo n.º 12
0
        public static void Export(System.Data.DataTable dt)
        {
            if (dt == null)
            {
                return;
            }

            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            ApplicationClass excelApp = null;

            try
            {
                excelApp         = new ApplicationClass();
                excelApp.Visible = true;

                Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);

                int sheetIndex = 0;
                object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];

                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    rawData[0, col] = dt.Columns[col].ColumnName;
                }

                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    for (int row = 0; row < dt.Rows.Count; row++)
                    {
                        rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                        System.Windows.Forms.Application.DoEvents();
                    }
                }

                string finalColLetter = string.Empty;
                string colCharset     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                int    colCharsetLen  = colCharset.Length;

                if (dt.Columns.Count > colCharsetLen)
                {
                    finalColLetter = colCharset.Substring(
                        (dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                }

                finalColLetter += colCharset.Substring(
                    (dt.Columns.Count - 1) % colCharsetLen, 1);

                // Create a new Sheet
                sheetIndex++;
                Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
                    Type.Missing, excelWorkbook.Sheets.get_Item(excelWorkbook.Sheets.Count), 1, XlSheetType.xlWorksheet);

                excelSheet.Name = String.Format("Result {0}", sheetIndex);

                // Fast data export to Excel
                string excelRange = string.Format("A1:{0}{1}",
                                                  finalColLetter, dt.Rows.Count + 1);

                excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;

                // Mark the first row as BOLD
                ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;
                excelApp.Visible     = true;
                excelApp.UserControl = true;
                Utils.ShowInfo("Fast export to excel completed.", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                GenericErrorDialog.ShowError("Error", "Can not export resultsets to excel.", ex);
                if (excelApp != null)
                {
                    excelApp.Quit();
                    excelApp = null;

                    // Collect the unreferenced objects
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
        }
Exemplo n.º 13
0
        private void UpdatePrivileges(bool updateAll)
        {
            grd.EndEdit();
            string objName  = String.Empty;
            string owner    = String.Empty;
            string filter   = String.Empty;
            bool   hasError = false;
            string errorMsg = "Can not update some object privileges!\r\n";

            try
            {
                _isInitializing = true;
                filter          = bs.Filter;

                using (SqlConnection conn = _cp.CreateSqlConnection(true))
                {
                    foreach (ObjectType type in _filters.Keys)
                    {
                        if (!updateAll && type != GetCurrentObjectType())
                        {
                            continue;
                        }

                        bs.Filter = _filters[type];
                        RemoveFromModifiedViewList(type);
                        foreach (DataRow row in _tbl.Rows)
                        {
                            if (!Utils.IsRowItemValid(row, "objName") || !Utils.IsRowItemValid(row, "owner"))
                            {
                                continue;
                            }

                            objName = (string)row["objName"];
                            owner   = (string)row["owner"];
                            try
                            {
                                TryToUpdateObjectPrivileges(conn, row, objName, owner);
                            }
                            catch (Exception ex)
                            {
                                errorMsg += "- Error: " + ex.Message + "\r\n";
                                hasError  = true;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (_modifiedViewList.Count == 0)
                {
                    SetModified(false);
                }

                bs.Filter = filter;

                _isInitializing = false;
                if (hasError)
                {
                    GenericErrorDialog.ShowError("PragmaSQL Error", "Some privileges can not be updated.", errorMsg);
                }
            }
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            ConfigHelper.LoadFromDefault();
            bool singleInstanceOn = true;

            if (ConfigHelper.Current != null && ConfigHelper.Current.GeneralOptions != null)
            {
                singleInstanceOn = ConfigHelper.Current.GeneralOptions.IsSingleInstance;
            }

            if (!singleInstanceOn || SingletonController.IamFirst(new SingletonController.ReceiveDelegate(OnSingletonControllerReceive)))
            {
                if (User32.FindWindow(null, "PragmaSQL") != IntPtr.Zero)
                {
                    if (SendJumpListMsg(args))
                    {
                        return;
                    }
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.ThreadException += new ThreadExceptionEventHandler(Program.OnThreadException);
                splashScreen = new frmSplashScreen();
                splashScreen.Show();

                try
                {
                    ICSharpCoreWrapper.StartCoreServices();
                }
                catch (Exception ex)
                {
                    frmSplashScreen.HideSplash();
                    GenericErrorDialog.ShowError("PragmaSQL Error", "Fatal Error : Core services can not be started.", ex);
                    return;
                }

                AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(splashScreen.ShowAssemblies);
                HostServices hostSvc = new HostServices();
#if PERSONAL_EDITION
                hostSvc.HostEdition = HostEditionType.Personal;
#endif
                HostServicesSingleton.HostServices = hostSvc;


                _mainForm = new frmMain();

                if (args != null && args.Length > 0)
                {
                    FileInfo fi = new FileInfo(args[0]);
                    if (fi.Exists)
                    {
                        if (fi.Extension.ToLowerInvariant() == ".sqlprj")
                        {
                            _mainForm.CommandLineProjectFileName = args[0];
                        }
                        else
                        {
                            _mainForm.CommandLineScriptFileName = args[0];
                        }
                    }
                }
                else
                {
                    SendJumpListMsg(args);
                }
                Application.Run(_mainForm);
            }
            else
            {
                // send command line args to running app, then terminate
                SingletonController.Send(args);
                SingletonController.Cleanup();
            }
        }